api.go 28 KB

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