github.com/daragao/go-ethereum@v1.8.14-0.20180809141559-45eaef243198/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  import (
    20  	"archive/tar"
    21  	"context"
    22  	"fmt"
    23  	"io"
    24  	"math/big"
    25  	"net/http"
    26  	"path"
    27  	"strings"
    28  
    29  	"bytes"
    30  	"mime"
    31  	"path/filepath"
    32  	"time"
    33  
    34  	"github.com/ethereum/go-ethereum/common"
    35  	"github.com/ethereum/go-ethereum/contracts/ens"
    36  	"github.com/ethereum/go-ethereum/core/types"
    37  	"github.com/ethereum/go-ethereum/metrics"
    38  	"github.com/ethereum/go-ethereum/swarm/log"
    39  	"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  	apiResolveCount        = metrics.NewRegisteredCounter("api.resolve.count", nil)
    48  	apiResolveFail         = metrics.NewRegisteredCounter("api.resolve.fail", nil)
    49  	apiPutCount            = metrics.NewRegisteredCounter("api.put.count", nil)
    50  	apiPutFail             = metrics.NewRegisteredCounter("api.put.fail", nil)
    51  	apiGetCount            = metrics.NewRegisteredCounter("api.get.count", nil)
    52  	apiGetNotFound         = metrics.NewRegisteredCounter("api.get.notfound", nil)
    53  	apiGetHTTP300          = metrics.NewRegisteredCounter("api.get.http.300", nil)
    54  	apiManifestUpdateCount = metrics.NewRegisteredCounter("api.manifestupdate.count", nil)
    55  	apiManifestUpdateFail  = metrics.NewRegisteredCounter("api.manifestupdate.fail", nil)
    56  	apiManifestListCount   = metrics.NewRegisteredCounter("api.manifestlist.count", nil)
    57  	apiManifestListFail    = metrics.NewRegisteredCounter("api.manifestlist.fail", nil)
    58  	apiDeleteCount         = metrics.NewRegisteredCounter("api.delete.count", nil)
    59  	apiDeleteFail          = metrics.NewRegisteredCounter("api.delete.fail", nil)
    60  	apiGetTarCount         = metrics.NewRegisteredCounter("api.gettar.count", nil)
    61  	apiGetTarFail          = metrics.NewRegisteredCounter("api.gettar.fail", nil)
    62  	apiUploadTarCount      = metrics.NewRegisteredCounter("api.uploadtar.count", nil)
    63  	apiUploadTarFail       = metrics.NewRegisteredCounter("api.uploadtar.fail", nil)
    64  	apiModifyCount         = metrics.NewRegisteredCounter("api.modify.count", nil)
    65  	apiModifyFail          = metrics.NewRegisteredCounter("api.modify.fail", nil)
    66  	apiAddFileCount        = metrics.NewRegisteredCounter("api.addfile.count", nil)
    67  	apiAddFileFail         = metrics.NewRegisteredCounter("api.addfile.fail", nil)
    68  	apiRmFileCount         = metrics.NewRegisteredCounter("api.removefile.count", nil)
    69  	apiRmFileFail          = metrics.NewRegisteredCounter("api.removefile.fail", nil)
    70  	apiAppendFileCount     = metrics.NewRegisteredCounter("api.appendfile.count", nil)
    71  	apiAppendFileFail      = metrics.NewRegisteredCounter("api.appendfile.fail", nil)
    72  	apiGetInvalid          = metrics.NewRegisteredCounter("api.get.invalid", nil)
    73  )
    74  
    75  // Resolver interface resolve a domain name to a hash using ENS
    76  type Resolver interface {
    77  	Resolve(string) (common.Hash, error)
    78  }
    79  
    80  // ResolveValidator is used to validate the contained Resolver
    81  type ResolveValidator interface {
    82  	Resolver
    83  	Owner(node [32]byte) (common.Address, error)
    84  	HeaderByNumber(context.Context, *big.Int) (*types.Header, error)
    85  }
    86  
    87  // NoResolverError is returned by MultiResolver.Resolve if no resolver
    88  // can be found for the address.
    89  type NoResolverError struct {
    90  	TLD string
    91  }
    92  
    93  // NewNoResolverError creates a NoResolverError for the given top level domain
    94  func NewNoResolverError(tld string) *NoResolverError {
    95  	return &NoResolverError{TLD: tld}
    96  }
    97  
    98  // Error NoResolverError implements error
    99  func (e *NoResolverError) Error() string {
   100  	if e.TLD == "" {
   101  		return "no ENS resolver"
   102  	}
   103  	return fmt.Sprintf("no ENS endpoint configured to resolve .%s TLD names", e.TLD)
   104  }
   105  
   106  // MultiResolver is used to resolve URL addresses based on their TLDs.
   107  // Each TLD can have multiple resolvers, and the resoluton from the
   108  // first one in the sequence will be returned.
   109  type MultiResolver struct {
   110  	resolvers map[string][]ResolveValidator
   111  	nameHash  func(string) common.Hash
   112  }
   113  
   114  // MultiResolverOption sets options for MultiResolver and is used as
   115  // arguments for its constructor.
   116  type MultiResolverOption func(*MultiResolver)
   117  
   118  // MultiResolverOptionWithResolver adds a Resolver to a list of resolvers
   119  // for a specific TLD. If TLD is an empty string, the resolver will be added
   120  // to the list of default resolver, the ones that will be used for resolution
   121  // of addresses which do not have their TLD resolver specified.
   122  func MultiResolverOptionWithResolver(r ResolveValidator, tld string) MultiResolverOption {
   123  	return func(m *MultiResolver) {
   124  		m.resolvers[tld] = append(m.resolvers[tld], r)
   125  	}
   126  }
   127  
   128  // MultiResolverOptionWithNameHash is unused at the time of this writing
   129  func MultiResolverOptionWithNameHash(nameHash func(string) common.Hash) MultiResolverOption {
   130  	return func(m *MultiResolver) {
   131  		m.nameHash = nameHash
   132  	}
   133  }
   134  
   135  // NewMultiResolver creates a new instance of MultiResolver.
   136  func NewMultiResolver(opts ...MultiResolverOption) (m *MultiResolver) {
   137  	m = &MultiResolver{
   138  		resolvers: make(map[string][]ResolveValidator),
   139  		nameHash:  ens.EnsNode,
   140  	}
   141  	for _, o := range opts {
   142  		o(m)
   143  	}
   144  	return m
   145  }
   146  
   147  // Resolve resolves address by choosing a Resolver by TLD.
   148  // If there are more default Resolvers, or for a specific TLD,
   149  // the Hash from the the first one which does not return error
   150  // will be returned.
   151  func (m *MultiResolver) Resolve(addr string) (h common.Hash, err error) {
   152  	rs, err := m.getResolveValidator(addr)
   153  	if err != nil {
   154  		return h, err
   155  	}
   156  	for _, r := range rs {
   157  		h, err = r.Resolve(addr)
   158  		if err == nil {
   159  			return
   160  		}
   161  	}
   162  	return
   163  }
   164  
   165  // ValidateOwner checks the ENS to validate that the owner of the given domain is the given eth address
   166  func (m *MultiResolver) ValidateOwner(name string, address common.Address) (bool, error) {
   167  	rs, err := m.getResolveValidator(name)
   168  	if err != nil {
   169  		return false, err
   170  	}
   171  	var addr common.Address
   172  	for _, r := range rs {
   173  		addr, err = r.Owner(m.nameHash(name))
   174  		// we hide the error if it is not for the last resolver we check
   175  		if err == nil {
   176  			return addr == address, nil
   177  		}
   178  	}
   179  	return false, err
   180  }
   181  
   182  // HeaderByNumber uses the validator of the given domainname and retrieves the header for the given block number
   183  func (m *MultiResolver) HeaderByNumber(ctx context.Context, name string, blockNr *big.Int) (*types.Header, error) {
   184  	rs, err := m.getResolveValidator(name)
   185  	if err != nil {
   186  		return nil, err
   187  	}
   188  	for _, r := range rs {
   189  		var header *types.Header
   190  		header, err = r.HeaderByNumber(ctx, blockNr)
   191  		// we hide the error if it is not for the last resolver we check
   192  		if err == nil {
   193  			return header, nil
   194  		}
   195  	}
   196  	return nil, err
   197  }
   198  
   199  // getResolveValidator uses the hostname to retrieve the resolver associated with the top level domain
   200  func (m *MultiResolver) getResolveValidator(name string) ([]ResolveValidator, error) {
   201  	rs := m.resolvers[""]
   202  	tld := path.Ext(name)
   203  	if tld != "" {
   204  		tld = tld[1:]
   205  		rstld, ok := m.resolvers[tld]
   206  		if ok {
   207  			return rstld, nil
   208  		}
   209  	}
   210  	if len(rs) == 0 {
   211  		return rs, NewNoResolverError(tld)
   212  	}
   213  	return rs, nil
   214  }
   215  
   216  // SetNameHash sets the hasher function that hashes the domain into a name hash that ENS uses
   217  func (m *MultiResolver) SetNameHash(nameHash func(string) common.Hash) {
   218  	m.nameHash = nameHash
   219  }
   220  
   221  /*
   222  API implements webserver/file system related content storage and retrieval
   223  on top of the FileStore
   224  it is the public interface of the FileStore which is included in the ethereum stack
   225  */
   226  type API struct {
   227  	resource  *mru.Handler
   228  	fileStore *storage.FileStore
   229  	dns       Resolver
   230  }
   231  
   232  // NewAPI the api constructor initialises a new API instance.
   233  func NewAPI(fileStore *storage.FileStore, dns Resolver, resourceHandler *mru.Handler) (self *API) {
   234  	self = &API{
   235  		fileStore: fileStore,
   236  		dns:       dns,
   237  		resource:  resourceHandler,
   238  	}
   239  	return
   240  }
   241  
   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  	fs := NewFileSystem(a)
   245  	hash, err = fs.Upload(uploadDir, index, toEncrypt)
   246  	return hash, err
   247  }
   248  
   249  // Retrieve FileStore reader API
   250  func (a *API) Retrieve(ctx context.Context, addr storage.Address) (reader storage.LazySectionReader, isEncrypted bool) {
   251  	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  type ErrResolve error
   262  
   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  	var sp opentracing.Span
   269  	ctx, sp = spancontext.StartSpan(
   270  		ctx,
   271  		"api.resolve")
   272  	defer sp.Finish()
   273  
   274  	// if the URI is immutable, check if the address looks like a hash
   275  	if uri.Immutable() {
   276  		key := uri.Address()
   277  		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  	if a.dns == nil {
   285  		key := uri.Address()
   286  		if key == nil {
   287  			apiResolveFail.Inc(1)
   288  			return nil, fmt.Errorf("no DNS to resolve name: %q", uri.Addr)
   289  		}
   290  		return key, nil
   291  	}
   292  
   293  	// try and resolve the address
   294  	resolved, err := a.dns.Resolve(uri.Addr)
   295  	if err == nil {
   296  		return resolved[:], nil
   297  	}
   298  
   299  	key := uri.Address()
   300  	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  	manifest := fmt.Sprintf(`{"entries":[{"hash":"%v","contentType":"%s"}]}`, key, contentType)
   317  	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  	return key, func(ctx context.Context) error {
   324  		err := waitContent(ctx)
   325  		if err != nil {
   326  			return err
   327  		}
   328  		return waitManifest(ctx)
   329  	}, nil
   330  }
   331  
   332  // Get uses iterative manifest retrieval and prefix matching
   333  // to resolve basePath to content using FileStore retrieve
   334  // 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  		return nil, "", http.StatusNotFound, nil, err
   343  	}
   344  
   345  	log.Debug("trie getting entry", "key", manifestAddr, "path", path)
   346  	entry, _ := trie.getEntry(path)
   347  
   348  	if entry != nil {
   349  		log.Debug("trie got entry", "key", manifestAddr, "path", path, "entry.Hash", entry.Hash)
   350  		// we need to do some extra work if this is a mutable resource manifest
   351  		if entry.ContentType == ResourceContentType {
   352  
   353  			// get the resource rootAddr
   354  			log.Trace("resource type", "menifestAddr", manifestAddr, "hash", entry.Hash)
   355  			ctx, cancel := context.WithCancel(context.Background())
   356  			defer cancel()
   357  			rootAddr := storage.Address(common.FromHex(entry.Hash))
   358  			rsrc, err := a.resource.Load(ctx, rootAddr)
   359  			if err != nil {
   360  				apiGetNotFound.Inc(1)
   361  				status = http.StatusNotFound
   362  				log.Debug(fmt.Sprintf("get resource content error: %v", err))
   363  				return reader, mimeType, status, nil, err
   364  			}
   365  
   366  			// use this key to retrieve the latest update
   367  			params := mru.LookupLatest(rootAddr)
   368  			rsrc, err = a.resource.Lookup(ctx, params)
   369  			if err != nil {
   370  				apiGetNotFound.Inc(1)
   371  				status = http.StatusNotFound
   372  				log.Debug(fmt.Sprintf("get resource content error: %v", err))
   373  				return reader, mimeType, status, nil, err
   374  			}
   375  
   376  			// if it's multihash, we will transparently serve the content this multihash points to
   377  			// \TODO this resolve is rather expensive all in all, review to see if it can be achieved cheaper
   378  			if rsrc.Multihash() {
   379  
   380  				// get the data of the update
   381  				_, rsrcData, err := a.resource.GetContent(rootAddr)
   382  				if err != nil {
   383  					apiGetNotFound.Inc(1)
   384  					status = http.StatusNotFound
   385  					log.Warn(fmt.Sprintf("get resource content error: %v", err))
   386  					return reader, mimeType, status, nil, err
   387  				}
   388  
   389  				// validate that data as multihash
   390  				decodedMultihash, err := multihash.FromMultihash(rsrcData)
   391  				if err != nil {
   392  					apiGetInvalid.Inc(1)
   393  					status = http.StatusUnprocessableEntity
   394  					log.Warn("invalid resource multihash", "err", err)
   395  					return reader, mimeType, status, nil, err
   396  				}
   397  				manifestAddr = storage.Address(decodedMultihash)
   398  				log.Trace("resource is multihash", "key", manifestAddr)
   399  
   400  				// get the manifest the multihash digest points to
   401  				trie, err := loadManifest(ctx, a.fileStore, manifestAddr, nil)
   402  				if err != nil {
   403  					apiGetNotFound.Inc(1)
   404  					status = http.StatusNotFound
   405  					log.Warn(fmt.Sprintf("loadManifestTrie (resource multihash) error: %v", err))
   406  					return reader, mimeType, status, nil, err
   407  				}
   408  
   409  				// finally, get the manifest entry
   410  				// it will always be the entry on path ""
   411  				entry, _ = trie.getEntry(path)
   412  				if entry == nil {
   413  					status = http.StatusNotFound
   414  					apiGetNotFound.Inc(1)
   415  					err = fmt.Errorf("manifest (resource multihash) entry for '%s' not found", path)
   416  					log.Trace("manifest (resource multihash) entry not found", "key", manifestAddr, "path", path)
   417  					return reader, mimeType, status, nil, err
   418  				}
   419  
   420  			} else {
   421  				// data is returned verbatim since it's not a multihash
   422  				return rsrc, "application/octet-stream", http.StatusOK, nil, nil
   423  			}
   424  		}
   425  
   426  		// regardless of resource update manifests or normal manifests we will converge at this point
   427  		// get the key the manifest entry points to and serve it if it's unambiguous
   428  		contentAddr = common.Hex2Bytes(entry.Hash)
   429  		status = entry.Status
   430  		if status == http.StatusMultipleChoices {
   431  			apiGetHTTP300.Inc(1)
   432  			return nil, entry.ContentType, status, contentAddr, err
   433  		}
   434  		mimeType = entry.ContentType
   435  		log.Debug("content lookup key", "key", contentAddr, "mimetype", mimeType)
   436  		reader, _ = a.fileStore.Retrieve(ctx, contentAddr)
   437  	} else {
   438  		// no entry found
   439  		status = http.StatusNotFound
   440  		apiGetNotFound.Inc(1)
   441  		err = fmt.Errorf("manifest entry for '%s' not found", path)
   442  		log.Trace("manifest entry not found", "key", contentAddr, "path", path)
   443  	}
   444  	return
   445  }
   446  
   447  func (a *API) Delete(ctx context.Context, addr string, path string) (storage.Address, error) {
   448  	apiDeleteCount.Inc(1)
   449  	uri, err := Parse("bzz:/" + addr)
   450  	if err != nil {
   451  		apiDeleteFail.Inc(1)
   452  		return nil, err
   453  	}
   454  	key, err := a.Resolve(ctx, uri)
   455  
   456  	if err != nil {
   457  		return nil, err
   458  	}
   459  	newKey, err := a.UpdateManifest(ctx, key, func(mw *ManifestWriter) error {
   460  		log.Debug(fmt.Sprintf("removing %s from manifest %s", path, key.Log()))
   461  		return mw.RemoveEntry(path)
   462  	})
   463  	if err != nil {
   464  		apiDeleteFail.Inc(1)
   465  		return nil, err
   466  	}
   467  
   468  	return newKey, nil
   469  }
   470  
   471  // GetDirectoryTar fetches a requested directory as a tarstream
   472  // it returns an io.Reader and an error. Do not forget to Close() the returned ReadCloser
   473  func (a *API) GetDirectoryTar(ctx context.Context, uri *URI) (io.ReadCloser, error) {
   474  	apiGetTarCount.Inc(1)
   475  	addr, err := a.Resolve(ctx, uri)
   476  	if err != nil {
   477  		return nil, err
   478  	}
   479  	walker, err := a.NewManifestWalker(ctx, addr, nil)
   480  	if err != nil {
   481  		apiGetTarFail.Inc(1)
   482  		return nil, err
   483  	}
   484  
   485  	piper, pipew := io.Pipe()
   486  
   487  	tw := tar.NewWriter(pipew)
   488  
   489  	go func() {
   490  		err := walker.Walk(func(entry *ManifestEntry) error {
   491  			// ignore manifests (walk will recurse into them)
   492  			if entry.ContentType == ManifestType {
   493  				return nil
   494  			}
   495  
   496  			// retrieve the entry's key and size
   497  			reader, _ := a.Retrieve(ctx, storage.Address(common.Hex2Bytes(entry.Hash)))
   498  			size, err := reader.Size(ctx, nil)
   499  			if err != nil {
   500  				return err
   501  			}
   502  
   503  			// write a tar header for the entry
   504  			hdr := &tar.Header{
   505  				Name:    entry.Path,
   506  				Mode:    entry.Mode,
   507  				Size:    size,
   508  				ModTime: entry.ModTime,
   509  				Xattrs: map[string]string{
   510  					"user.swarm.content-type": entry.ContentType,
   511  				},
   512  			}
   513  
   514  			if err := tw.WriteHeader(hdr); err != nil {
   515  				return err
   516  			}
   517  
   518  			// copy the file into the tar stream
   519  			n, err := io.Copy(tw, io.LimitReader(reader, hdr.Size))
   520  			if err != nil {
   521  				return err
   522  			} else if n != size {
   523  				return fmt.Errorf("error writing %s: expected %d bytes but sent %d", entry.Path, size, n)
   524  			}
   525  
   526  			return nil
   527  		})
   528  		// close tar writer before closing pipew
   529  		// to flush remaining data to pipew
   530  		// regardless of error value
   531  		tw.Close()
   532  		if err != nil {
   533  			apiGetTarFail.Inc(1)
   534  			pipew.CloseWithError(err)
   535  		} else {
   536  			pipew.Close()
   537  		}
   538  	}()
   539  
   540  	return piper, nil
   541  }
   542  
   543  // GetManifestList lists the manifest entries for the specified address and prefix
   544  // and returns it as a ManifestList
   545  func (a *API) GetManifestList(ctx context.Context, addr storage.Address, prefix string) (list ManifestList, err error) {
   546  	apiManifestListCount.Inc(1)
   547  	walker, err := a.NewManifestWalker(ctx, addr, nil)
   548  	if err != nil {
   549  		apiManifestListFail.Inc(1)
   550  		return ManifestList{}, err
   551  	}
   552  
   553  	err = walker.Walk(func(entry *ManifestEntry) error {
   554  		// handle non-manifest files
   555  		if entry.ContentType != ManifestType {
   556  			// ignore the file if it doesn't have the specified prefix
   557  			if !strings.HasPrefix(entry.Path, prefix) {
   558  				return nil
   559  			}
   560  
   561  			// if the path after the prefix contains a slash, add a
   562  			// common prefix to the list, otherwise add the entry
   563  			suffix := strings.TrimPrefix(entry.Path, prefix)
   564  			if index := strings.Index(suffix, "/"); index > -1 {
   565  				list.CommonPrefixes = append(list.CommonPrefixes, prefix+suffix[:index+1])
   566  				return nil
   567  			}
   568  			if entry.Path == "" {
   569  				entry.Path = "/"
   570  			}
   571  			list.Entries = append(list.Entries, entry)
   572  			return nil
   573  		}
   574  
   575  		// if the manifest's path is a prefix of the specified prefix
   576  		// then just recurse into the manifest by returning nil and
   577  		// continuing the walk
   578  		if strings.HasPrefix(prefix, entry.Path) {
   579  			return nil
   580  		}
   581  
   582  		// if the manifest's path has the specified prefix, then if the
   583  		// path after the prefix contains a slash, add a common prefix
   584  		// to the list and skip the manifest, otherwise recurse into
   585  		// the manifest by returning nil and continuing the walk
   586  		if strings.HasPrefix(entry.Path, prefix) {
   587  			suffix := strings.TrimPrefix(entry.Path, prefix)
   588  			if index := strings.Index(suffix, "/"); index > -1 {
   589  				list.CommonPrefixes = append(list.CommonPrefixes, prefix+suffix[:index+1])
   590  				return ErrSkipManifest
   591  			}
   592  			return nil
   593  		}
   594  
   595  		// the manifest neither has the prefix or needs recursing in to
   596  		// so just skip it
   597  		return ErrSkipManifest
   598  	})
   599  
   600  	if err != nil {
   601  		apiManifestListFail.Inc(1)
   602  		return ManifestList{}, err
   603  	}
   604  
   605  	return list, nil
   606  }
   607  
   608  func (a *API) UpdateManifest(ctx context.Context, addr storage.Address, update func(mw *ManifestWriter) error) (storage.Address, error) {
   609  	apiManifestUpdateCount.Inc(1)
   610  	mw, err := a.NewManifestWriter(ctx, addr, nil)
   611  	if err != nil {
   612  		apiManifestUpdateFail.Inc(1)
   613  		return nil, err
   614  	}
   615  
   616  	if err := update(mw); err != nil {
   617  		apiManifestUpdateFail.Inc(1)
   618  		return nil, err
   619  	}
   620  
   621  	addr, err = mw.Store()
   622  	if err != nil {
   623  		apiManifestUpdateFail.Inc(1)
   624  		return nil, err
   625  	}
   626  	log.Debug(fmt.Sprintf("generated manifest %s", addr))
   627  	return addr, nil
   628  }
   629  
   630  // Modify loads manifest and checks the content hash before recalculating and storing the manifest.
   631  func (a *API) Modify(ctx context.Context, addr storage.Address, path, contentHash, contentType string) (storage.Address, error) {
   632  	apiModifyCount.Inc(1)
   633  	quitC := make(chan bool)
   634  	trie, err := loadManifest(ctx, a.fileStore, addr, quitC)
   635  	if err != nil {
   636  		apiModifyFail.Inc(1)
   637  		return nil, err
   638  	}
   639  	if contentHash != "" {
   640  		entry := newManifestTrieEntry(&ManifestEntry{
   641  			Path:        path,
   642  			ContentType: contentType,
   643  		}, nil)
   644  		entry.Hash = contentHash
   645  		trie.addEntry(entry, quitC)
   646  	} else {
   647  		trie.deleteEntry(path, quitC)
   648  	}
   649  
   650  	if err := trie.recalcAndStore(); err != nil {
   651  		apiModifyFail.Inc(1)
   652  		return nil, err
   653  	}
   654  	return trie.ref, nil
   655  }
   656  
   657  // AddFile creates a new manifest entry, adds it to swarm, then adds a file to swarm.
   658  func (a *API) AddFile(ctx context.Context, mhash, path, fname string, content []byte, nameresolver bool) (storage.Address, string, error) {
   659  	apiAddFileCount.Inc(1)
   660  
   661  	uri, err := Parse("bzz:/" + mhash)
   662  	if err != nil {
   663  		apiAddFileFail.Inc(1)
   664  		return nil, "", err
   665  	}
   666  	mkey, err := a.Resolve(ctx, uri)
   667  	if err != nil {
   668  		apiAddFileFail.Inc(1)
   669  		return nil, "", err
   670  	}
   671  
   672  	// trim the root dir we added
   673  	if path[:1] == "/" {
   674  		path = path[1:]
   675  	}
   676  
   677  	entry := &ManifestEntry{
   678  		Path:        filepath.Join(path, fname),
   679  		ContentType: mime.TypeByExtension(filepath.Ext(fname)),
   680  		Mode:        0700,
   681  		Size:        int64(len(content)),
   682  		ModTime:     time.Now(),
   683  	}
   684  
   685  	mw, err := a.NewManifestWriter(ctx, mkey, nil)
   686  	if err != nil {
   687  		apiAddFileFail.Inc(1)
   688  		return nil, "", err
   689  	}
   690  
   691  	fkey, err := mw.AddEntry(ctx, bytes.NewReader(content), entry)
   692  	if err != nil {
   693  		apiAddFileFail.Inc(1)
   694  		return nil, "", err
   695  	}
   696  
   697  	newMkey, err := mw.Store()
   698  	if err != nil {
   699  		apiAddFileFail.Inc(1)
   700  		return nil, "", err
   701  
   702  	}
   703  
   704  	return fkey, newMkey.String(), nil
   705  }
   706  
   707  func (a *API) UploadTar(ctx context.Context, bodyReader io.ReadCloser, manifestPath string, mw *ManifestWriter) (storage.Address, error) {
   708  	apiUploadTarCount.Inc(1)
   709  	var contentKey storage.Address
   710  	tr := tar.NewReader(bodyReader)
   711  	defer bodyReader.Close()
   712  	for {
   713  		hdr, err := tr.Next()
   714  		if err == io.EOF {
   715  			break
   716  		} else if err != nil {
   717  			apiUploadTarFail.Inc(1)
   718  			return nil, fmt.Errorf("error reading tar stream: %s", err)
   719  		}
   720  
   721  		// only store regular files
   722  		if !hdr.FileInfo().Mode().IsRegular() {
   723  			continue
   724  		}
   725  
   726  		// add the entry under the path from the request
   727  		manifestPath := path.Join(manifestPath, hdr.Name)
   728  		entry := &ManifestEntry{
   729  			Path:        manifestPath,
   730  			ContentType: hdr.Xattrs["user.swarm.content-type"],
   731  			Mode:        hdr.Mode,
   732  			Size:        hdr.Size,
   733  			ModTime:     hdr.ModTime,
   734  		}
   735  		contentKey, err = mw.AddEntry(ctx, tr, entry)
   736  		if err != nil {
   737  			apiUploadTarFail.Inc(1)
   738  			return nil, fmt.Errorf("error adding manifest entry from tar stream: %s", err)
   739  		}
   740  	}
   741  	return contentKey, nil
   742  }
   743  
   744  // RemoveFile removes a file entry in a manifest.
   745  func (a *API) RemoveFile(ctx context.Context, mhash string, path string, fname string, nameresolver bool) (string, error) {
   746  	apiRmFileCount.Inc(1)
   747  
   748  	uri, err := Parse("bzz:/" + mhash)
   749  	if err != nil {
   750  		apiRmFileFail.Inc(1)
   751  		return "", err
   752  	}
   753  	mkey, err := a.Resolve(ctx, uri)
   754  	if err != nil {
   755  		apiRmFileFail.Inc(1)
   756  		return "", err
   757  	}
   758  
   759  	// trim the root dir we added
   760  	if path[:1] == "/" {
   761  		path = path[1:]
   762  	}
   763  
   764  	mw, err := a.NewManifestWriter(ctx, mkey, nil)
   765  	if err != nil {
   766  		apiRmFileFail.Inc(1)
   767  		return "", err
   768  	}
   769  
   770  	err = mw.RemoveEntry(filepath.Join(path, fname))
   771  	if err != nil {
   772  		apiRmFileFail.Inc(1)
   773  		return "", err
   774  	}
   775  
   776  	newMkey, err := mw.Store()
   777  	if err != nil {
   778  		apiRmFileFail.Inc(1)
   779  		return "", err
   780  
   781  	}
   782  
   783  	return newMkey.String(), nil
   784  }
   785  
   786  // AppendFile removes old manifest, appends file entry to new manifest and adds it to Swarm.
   787  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) {
   788  	apiAppendFileCount.Inc(1)
   789  
   790  	buffSize := offset + addSize
   791  	if buffSize < existingSize {
   792  		buffSize = existingSize
   793  	}
   794  
   795  	buf := make([]byte, buffSize)
   796  
   797  	oldReader, _ := a.Retrieve(ctx, oldAddr)
   798  	io.ReadAtLeast(oldReader, buf, int(offset))
   799  
   800  	newReader := bytes.NewReader(content)
   801  	io.ReadAtLeast(newReader, buf[offset:], int(addSize))
   802  
   803  	if buffSize < existingSize {
   804  		io.ReadAtLeast(oldReader, buf[addSize:], int(buffSize))
   805  	}
   806  
   807  	combinedReader := bytes.NewReader(buf)
   808  	totalSize := int64(len(buf))
   809  
   810  	// TODO(jmozah): to append using pyramid chunker when it is ready
   811  	//oldReader := a.Retrieve(oldKey)
   812  	//newReader := bytes.NewReader(content)
   813  	//combinedReader := io.MultiReader(oldReader, newReader)
   814  
   815  	uri, err := Parse("bzz:/" + mhash)
   816  	if err != nil {
   817  		apiAppendFileFail.Inc(1)
   818  		return nil, "", err
   819  	}
   820  	mkey, err := a.Resolve(ctx, uri)
   821  	if err != nil {
   822  		apiAppendFileFail.Inc(1)
   823  		return nil, "", err
   824  	}
   825  
   826  	// trim the root dir we added
   827  	if path[:1] == "/" {
   828  		path = path[1:]
   829  	}
   830  
   831  	mw, err := a.NewManifestWriter(ctx, mkey, nil)
   832  	if err != nil {
   833  		apiAppendFileFail.Inc(1)
   834  		return nil, "", err
   835  	}
   836  
   837  	err = mw.RemoveEntry(filepath.Join(path, fname))
   838  	if err != nil {
   839  		apiAppendFileFail.Inc(1)
   840  		return nil, "", err
   841  	}
   842  
   843  	entry := &ManifestEntry{
   844  		Path:        filepath.Join(path, fname),
   845  		ContentType: mime.TypeByExtension(filepath.Ext(fname)),
   846  		Mode:        0700,
   847  		Size:        totalSize,
   848  		ModTime:     time.Now(),
   849  	}
   850  
   851  	fkey, err := mw.AddEntry(ctx, io.Reader(combinedReader), entry)
   852  	if err != nil {
   853  		apiAppendFileFail.Inc(1)
   854  		return nil, "", err
   855  	}
   856  
   857  	newMkey, err := mw.Store()
   858  	if err != nil {
   859  		apiAppendFileFail.Inc(1)
   860  		return nil, "", err
   861  
   862  	}
   863  
   864  	return fkey, newMkey.String(), nil
   865  }
   866  
   867  // BuildDirectoryTree used by swarmfs_unix
   868  func (a *API) BuildDirectoryTree(ctx context.Context, mhash string, nameresolver bool) (addr storage.Address, manifestEntryMap map[string]*manifestTrieEntry, err error) {
   869  
   870  	uri, err := Parse("bzz:/" + mhash)
   871  	if err != nil {
   872  		return nil, nil, err
   873  	}
   874  	addr, err = a.Resolve(ctx, uri)
   875  	if err != nil {
   876  		return nil, nil, err
   877  	}
   878  
   879  	quitC := make(chan bool)
   880  	rootTrie, err := loadManifest(ctx, a.fileStore, addr, quitC)
   881  	if err != nil {
   882  		return nil, nil, fmt.Errorf("can't load manifest %v: %v", addr.String(), err)
   883  	}
   884  
   885  	manifestEntryMap = map[string]*manifestTrieEntry{}
   886  	err = rootTrie.listWithPrefix(uri.Path, quitC, func(entry *manifestTrieEntry, suffix string) {
   887  		manifestEntryMap[suffix] = entry
   888  	})
   889  
   890  	if err != nil {
   891  		return nil, nil, fmt.Errorf("list with prefix failed %v: %v", addr.String(), err)
   892  	}
   893  	return addr, manifestEntryMap, nil
   894  }
   895  
   896  // ResourceLookup finds mutable resource updates at specific periods and versions
   897  func (a *API) ResourceLookup(ctx context.Context, params *mru.LookupParams) (string, []byte, error) {
   898  	var err error
   899  	rsrc, err := a.resource.Load(ctx, params.RootAddr())
   900  	if err != nil {
   901  		return "", nil, err
   902  	}
   903  	_, err = a.resource.Lookup(ctx, params)
   904  	if err != nil {
   905  		return "", nil, err
   906  	}
   907  	var data []byte
   908  	_, data, err = a.resource.GetContent(params.RootAddr())
   909  	if err != nil {
   910  		return "", nil, err
   911  	}
   912  	return rsrc.Name(), data, nil
   913  }
   914  
   915  // Create Mutable resource
   916  func (a *API) ResourceCreate(ctx context.Context, request *mru.Request) error {
   917  	return a.resource.New(ctx, request)
   918  }
   919  
   920  // ResourceNewRequest creates a Request object to update a specific mutable resource
   921  func (a *API) ResourceNewRequest(ctx context.Context, rootAddr storage.Address) (*mru.Request, error) {
   922  	return a.resource.NewUpdateRequest(ctx, rootAddr)
   923  }
   924  
   925  // ResourceUpdate updates a Mutable Resource with arbitrary data.
   926  // Upon retrieval the update will be retrieved verbatim as bytes.
   927  func (a *API) ResourceUpdate(ctx context.Context, request *mru.SignedResourceUpdate) (storage.Address, error) {
   928  	return a.resource.Update(ctx, request)
   929  }
   930  
   931  // ResourceHashSize returned the size of the digest produced by the Mutable Resource hashing function
   932  func (a *API) ResourceHashSize() int {
   933  	return a.resource.HashSize
   934  }
   935  
   936  // ResolveResourceManifest retrieves the Mutable Resource manifest for the given address, and returns the address of the metadata chunk.
   937  func (a *API) ResolveResourceManifest(ctx context.Context, addr storage.Address) (storage.Address, error) {
   938  	trie, err := loadManifest(ctx, a.fileStore, addr, nil)
   939  	if err != nil {
   940  		return nil, fmt.Errorf("cannot load resource manifest: %v", err)
   941  	}
   942  
   943  	entry, _ := trie.getEntry("")
   944  	if entry.ContentType != ResourceContentType {
   945  		return nil, fmt.Errorf("not a resource manifest: %s", addr)
   946  	}
   947  
   948  	return storage.Address(common.FromHex(entry.Hash)), nil
   949  }