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