api.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  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. log.Warn(fmt.Sprintf("loadManifestTrie error: %v", err))
  309. return
  310. }
  311. log.Debug("trie getting entry", "key", manifestAddr, "path", path)
  312. entry, _ := trie.getEntry(path)
  313. if entry != nil {
  314. log.Debug("trie got entry", "key", manifestAddr, "path", path, "entry.Hash", entry.Hash)
  315. // we need to do some extra work if this is a mutable resource manifest
  316. if entry.ContentType == ResourceContentType {
  317. // get the resource root chunk key
  318. log.Trace("resource type", "key", manifestAddr, "hash", entry.Hash)
  319. ctx, cancel := context.WithCancel(context.Background())
  320. defer cancel()
  321. rsrc, err := a.resource.Load(ctx, storage.Address(common.FromHex(entry.Hash)))
  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. rsrc, err = a.resource.LookupLatest(ctx, rsrc.NameHash(), true, &mru.LookupParams{})
  330. if err != nil {
  331. apiGetNotFound.Inc(1)
  332. status = http.StatusNotFound
  333. log.Debug(fmt.Sprintf("get resource content error: %v", err))
  334. return reader, mimeType, status, nil, err
  335. }
  336. // if it's multihash, we will transparently serve the content this multihash points to
  337. // \TODO this resolve is rather expensive all in all, review to see if it can be achieved cheaper
  338. if rsrc.Multihash {
  339. // get the data of the update
  340. _, rsrcData, err := a.resource.GetContent(rsrc.NameHash().Hex())
  341. if err != nil {
  342. apiGetNotFound.Inc(1)
  343. status = http.StatusNotFound
  344. log.Warn(fmt.Sprintf("get resource content error: %v", err))
  345. return reader, mimeType, status, nil, err
  346. }
  347. // validate that data as multihash
  348. decodedMultihash, err := multihash.FromMultihash(rsrcData)
  349. if err != nil {
  350. apiGetInvalid.Inc(1)
  351. status = http.StatusUnprocessableEntity
  352. log.Warn("invalid resource multihash", "err", err)
  353. return reader, mimeType, status, nil, err
  354. }
  355. manifestAddr = storage.Address(decodedMultihash)
  356. log.Trace("resource is multihash", "key", manifestAddr)
  357. // get the manifest the multihash digest points to
  358. trie, err := loadManifest(ctx, a.fileStore, manifestAddr, nil)
  359. if err != nil {
  360. apiGetNotFound.Inc(1)
  361. status = http.StatusNotFound
  362. log.Warn(fmt.Sprintf("loadManifestTrie (resource multihash) error: %v", err))
  363. return reader, mimeType, status, nil, err
  364. }
  365. // finally, get the manifest entry
  366. // it will always be the entry on path ""
  367. entry, _ = trie.getEntry(path)
  368. if entry == nil {
  369. status = http.StatusNotFound
  370. apiGetNotFound.Inc(1)
  371. err = fmt.Errorf("manifest (resource multihash) entry for '%s' not found", path)
  372. log.Trace("manifest (resource multihash) entry not found", "key", manifestAddr, "path", path)
  373. return reader, mimeType, status, nil, err
  374. }
  375. } else {
  376. // data is returned verbatim since it's not a multihash
  377. return rsrc, "application/octet-stream", http.StatusOK, nil, nil
  378. }
  379. }
  380. // regardless of resource update manifests or normal manifests we will converge at this point
  381. // get the key the manifest entry points to and serve it if it's unambiguous
  382. contentAddr = common.Hex2Bytes(entry.Hash)
  383. status = entry.Status
  384. if status == http.StatusMultipleChoices {
  385. apiGetHTTP300.Inc(1)
  386. return nil, entry.ContentType, status, contentAddr, err
  387. }
  388. mimeType = entry.ContentType
  389. log.Debug("content lookup key", "key", contentAddr, "mimetype", mimeType)
  390. reader, _ = a.fileStore.Retrieve(ctx, contentAddr)
  391. } else {
  392. // no entry found
  393. status = http.StatusNotFound
  394. apiGetNotFound.Inc(1)
  395. err = fmt.Errorf("manifest entry for '%s' not found", path)
  396. log.Trace("manifest entry not found", "key", contentAddr, "path", path)
  397. }
  398. return
  399. }
  400. func (a *API) Delete(ctx context.Context, addr string, path string) (storage.Address, error) {
  401. apiDeleteCount.Inc(1)
  402. uri, err := Parse("bzz:/" + addr)
  403. if err != nil {
  404. apiDeleteFail.Inc(1)
  405. return nil, err
  406. }
  407. key, err := a.Resolve(ctx, uri)
  408. if err != nil {
  409. return nil, err
  410. }
  411. newKey, err := a.UpdateManifest(ctx, key, func(mw *ManifestWriter) error {
  412. log.Debug(fmt.Sprintf("removing %s from manifest %s", path, key.Log()))
  413. return mw.RemoveEntry(path)
  414. })
  415. if err != nil {
  416. apiDeleteFail.Inc(1)
  417. return nil, err
  418. }
  419. return newKey, nil
  420. }
  421. // GetDirectoryTar fetches a requested directory as a tarstream
  422. // it returns an io.Reader and an error. Do not forget to Close() the returned ReadCloser
  423. func (a *API) GetDirectoryTar(ctx context.Context, uri *URI) (io.ReadCloser, error) {
  424. apiGetTarCount.Inc(1)
  425. addr, err := a.Resolve(ctx, uri)
  426. if err != nil {
  427. return nil, err
  428. }
  429. walker, err := a.NewManifestWalker(ctx, addr, nil)
  430. if err != nil {
  431. apiGetTarFail.Inc(1)
  432. return nil, err
  433. }
  434. piper, pipew := io.Pipe()
  435. tw := tar.NewWriter(pipew)
  436. go func() {
  437. err := walker.Walk(func(entry *ManifestEntry) error {
  438. // ignore manifests (walk will recurse into them)
  439. if entry.ContentType == ManifestType {
  440. return nil
  441. }
  442. // retrieve the entry's key and size
  443. reader, _ := a.Retrieve(ctx, storage.Address(common.Hex2Bytes(entry.Hash)))
  444. size, err := reader.Size(ctx, nil)
  445. if err != nil {
  446. return err
  447. }
  448. // write a tar header for the entry
  449. hdr := &tar.Header{
  450. Name: entry.Path,
  451. Mode: entry.Mode,
  452. Size: size,
  453. ModTime: entry.ModTime,
  454. Xattrs: map[string]string{
  455. "user.swarm.content-type": entry.ContentType,
  456. },
  457. }
  458. if err := tw.WriteHeader(hdr); err != nil {
  459. return err
  460. }
  461. // copy the file into the tar stream
  462. n, err := io.Copy(tw, io.LimitReader(reader, hdr.Size))
  463. if err != nil {
  464. return err
  465. } else if n != size {
  466. return fmt.Errorf("error writing %s: expected %d bytes but sent %d", entry.Path, size, n)
  467. }
  468. return nil
  469. })
  470. if err != nil {
  471. apiGetTarFail.Inc(1)
  472. pipew.CloseWithError(err)
  473. } else {
  474. pipew.Close()
  475. }
  476. }()
  477. return piper, nil
  478. }
  479. // GetManifestList lists the manifest entries for the specified address and prefix
  480. // and returns it as a ManifestList
  481. func (a *API) GetManifestList(ctx context.Context, addr storage.Address, prefix string) (list ManifestList, err error) {
  482. apiManifestListCount.Inc(1)
  483. walker, err := a.NewManifestWalker(ctx, addr, nil)
  484. if err != nil {
  485. apiManifestListFail.Inc(1)
  486. return ManifestList{}, err
  487. }
  488. err = walker.Walk(func(entry *ManifestEntry) error {
  489. // handle non-manifest files
  490. if entry.ContentType != ManifestType {
  491. // ignore the file if it doesn't have the specified prefix
  492. if !strings.HasPrefix(entry.Path, prefix) {
  493. return nil
  494. }
  495. // if the path after the prefix contains a slash, add a
  496. // common prefix to the list, otherwise add the entry
  497. suffix := strings.TrimPrefix(entry.Path, prefix)
  498. if index := strings.Index(suffix, "/"); index > -1 {
  499. list.CommonPrefixes = append(list.CommonPrefixes, prefix+suffix[:index+1])
  500. return nil
  501. }
  502. if entry.Path == "" {
  503. entry.Path = "/"
  504. }
  505. list.Entries = append(list.Entries, entry)
  506. return nil
  507. }
  508. // if the manifest's path is a prefix of the specified prefix
  509. // then just recurse into the manifest by returning nil and
  510. // continuing the walk
  511. if strings.HasPrefix(prefix, entry.Path) {
  512. return nil
  513. }
  514. // if the manifest's path has the specified prefix, then if the
  515. // path after the prefix contains a slash, add a common prefix
  516. // to the list and skip the manifest, otherwise recurse into
  517. // the manifest by returning nil and continuing the walk
  518. if strings.HasPrefix(entry.Path, prefix) {
  519. suffix := strings.TrimPrefix(entry.Path, prefix)
  520. if index := strings.Index(suffix, "/"); index > -1 {
  521. list.CommonPrefixes = append(list.CommonPrefixes, prefix+suffix[:index+1])
  522. return ErrSkipManifest
  523. }
  524. return nil
  525. }
  526. // the manifest neither has the prefix or needs recursing in to
  527. // so just skip it
  528. return ErrSkipManifest
  529. })
  530. if err != nil {
  531. apiManifestListFail.Inc(1)
  532. return ManifestList{}, err
  533. }
  534. return list, nil
  535. }
  536. func (a *API) UpdateManifest(ctx context.Context, addr storage.Address, update func(mw *ManifestWriter) error) (storage.Address, error) {
  537. apiManifestUpdateCount.Inc(1)
  538. mw, err := a.NewManifestWriter(ctx, addr, nil)
  539. if err != nil {
  540. apiManifestUpdateFail.Inc(1)
  541. return nil, err
  542. }
  543. if err := update(mw); err != nil {
  544. apiManifestUpdateFail.Inc(1)
  545. return nil, err
  546. }
  547. addr, err = mw.Store()
  548. if err != nil {
  549. apiManifestUpdateFail.Inc(1)
  550. return nil, err
  551. }
  552. log.Debug(fmt.Sprintf("generated manifest %s", addr))
  553. return addr, nil
  554. }
  555. // Modify loads manifest and checks the content hash before recalculating and storing the manifest.
  556. func (a *API) Modify(ctx context.Context, addr storage.Address, path, contentHash, contentType string) (storage.Address, error) {
  557. apiModifyCount.Inc(1)
  558. quitC := make(chan bool)
  559. trie, err := loadManifest(ctx, a.fileStore, addr, quitC)
  560. if err != nil {
  561. apiModifyFail.Inc(1)
  562. return nil, err
  563. }
  564. if contentHash != "" {
  565. entry := newManifestTrieEntry(&ManifestEntry{
  566. Path: path,
  567. ContentType: contentType,
  568. }, nil)
  569. entry.Hash = contentHash
  570. trie.addEntry(entry, quitC)
  571. } else {
  572. trie.deleteEntry(path, quitC)
  573. }
  574. if err := trie.recalcAndStore(); err != nil {
  575. apiModifyFail.Inc(1)
  576. return nil, err
  577. }
  578. return trie.ref, nil
  579. }
  580. // AddFile creates a new manifest entry, adds it to swarm, then adds a file to swarm.
  581. func (a *API) AddFile(ctx context.Context, mhash, path, fname string, content []byte, nameresolver bool) (storage.Address, string, error) {
  582. apiAddFileCount.Inc(1)
  583. uri, err := Parse("bzz:/" + mhash)
  584. if err != nil {
  585. apiAddFileFail.Inc(1)
  586. return nil, "", err
  587. }
  588. mkey, err := a.Resolve(ctx, uri)
  589. if err != nil {
  590. apiAddFileFail.Inc(1)
  591. return nil, "", err
  592. }
  593. // trim the root dir we added
  594. if path[:1] == "/" {
  595. path = path[1:]
  596. }
  597. entry := &ManifestEntry{
  598. Path: filepath.Join(path, fname),
  599. ContentType: mime.TypeByExtension(filepath.Ext(fname)),
  600. Mode: 0700,
  601. Size: int64(len(content)),
  602. ModTime: time.Now(),
  603. }
  604. mw, err := a.NewManifestWriter(ctx, mkey, nil)
  605. if err != nil {
  606. apiAddFileFail.Inc(1)
  607. return nil, "", err
  608. }
  609. fkey, err := mw.AddEntry(ctx, bytes.NewReader(content), entry)
  610. if err != nil {
  611. apiAddFileFail.Inc(1)
  612. return nil, "", err
  613. }
  614. newMkey, err := mw.Store()
  615. if err != nil {
  616. apiAddFileFail.Inc(1)
  617. return nil, "", err
  618. }
  619. return fkey, newMkey.String(), nil
  620. }
  621. func (a *API) UploadTar(ctx context.Context, bodyReader io.ReadCloser, manifestPath string, mw *ManifestWriter) (storage.Address, error) {
  622. apiUploadTarCount.Inc(1)
  623. var contentKey storage.Address
  624. tr := tar.NewReader(bodyReader)
  625. defer bodyReader.Close()
  626. for {
  627. hdr, err := tr.Next()
  628. if err == io.EOF {
  629. break
  630. } else if err != nil {
  631. apiUploadTarFail.Inc(1)
  632. return nil, fmt.Errorf("error reading tar stream: %s", err)
  633. }
  634. // only store regular files
  635. if !hdr.FileInfo().Mode().IsRegular() {
  636. continue
  637. }
  638. // add the entry under the path from the request
  639. manifestPath := path.Join(manifestPath, hdr.Name)
  640. entry := &ManifestEntry{
  641. Path: manifestPath,
  642. ContentType: hdr.Xattrs["user.swarm.content-type"],
  643. Mode: hdr.Mode,
  644. Size: hdr.Size,
  645. ModTime: hdr.ModTime,
  646. }
  647. contentKey, err = mw.AddEntry(ctx, tr, entry)
  648. if err != nil {
  649. apiUploadTarFail.Inc(1)
  650. return nil, fmt.Errorf("error adding manifest entry from tar stream: %s", err)
  651. }
  652. }
  653. return contentKey, nil
  654. }
  655. // RemoveFile removes a file entry in a manifest.
  656. func (a *API) RemoveFile(ctx context.Context, mhash string, path string, fname string, nameresolver bool) (string, error) {
  657. apiRmFileCount.Inc(1)
  658. uri, err := Parse("bzz:/" + mhash)
  659. if err != nil {
  660. apiRmFileFail.Inc(1)
  661. return "", err
  662. }
  663. mkey, err := a.Resolve(ctx, uri)
  664. if err != nil {
  665. apiRmFileFail.Inc(1)
  666. return "", err
  667. }
  668. // trim the root dir we added
  669. if path[:1] == "/" {
  670. path = path[1:]
  671. }
  672. mw, err := a.NewManifestWriter(ctx, mkey, nil)
  673. if err != nil {
  674. apiRmFileFail.Inc(1)
  675. return "", err
  676. }
  677. err = mw.RemoveEntry(filepath.Join(path, fname))
  678. if err != nil {
  679. apiRmFileFail.Inc(1)
  680. return "", err
  681. }
  682. newMkey, err := mw.Store()
  683. if err != nil {
  684. apiRmFileFail.Inc(1)
  685. return "", err
  686. }
  687. return newMkey.String(), nil
  688. }
  689. // AppendFile removes old manifest, appends file entry to new manifest and adds it to Swarm.
  690. 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) {
  691. apiAppendFileCount.Inc(1)
  692. buffSize := offset + addSize
  693. if buffSize < existingSize {
  694. buffSize = existingSize
  695. }
  696. buf := make([]byte, buffSize)
  697. oldReader, _ := a.Retrieve(ctx, oldAddr)
  698. io.ReadAtLeast(oldReader, buf, int(offset))
  699. newReader := bytes.NewReader(content)
  700. io.ReadAtLeast(newReader, buf[offset:], int(addSize))
  701. if buffSize < existingSize {
  702. io.ReadAtLeast(oldReader, buf[addSize:], int(buffSize))
  703. }
  704. combinedReader := bytes.NewReader(buf)
  705. totalSize := int64(len(buf))
  706. // TODO(jmozah): to append using pyramid chunker when it is ready
  707. //oldReader := a.Retrieve(oldKey)
  708. //newReader := bytes.NewReader(content)
  709. //combinedReader := io.MultiReader(oldReader, newReader)
  710. uri, err := Parse("bzz:/" + mhash)
  711. if err != nil {
  712. apiAppendFileFail.Inc(1)
  713. return nil, "", err
  714. }
  715. mkey, err := a.Resolve(ctx, uri)
  716. if err != nil {
  717. apiAppendFileFail.Inc(1)
  718. return nil, "", err
  719. }
  720. // trim the root dir we added
  721. if path[:1] == "/" {
  722. path = path[1:]
  723. }
  724. mw, err := a.NewManifestWriter(ctx, mkey, nil)
  725. if err != nil {
  726. apiAppendFileFail.Inc(1)
  727. return nil, "", err
  728. }
  729. err = mw.RemoveEntry(filepath.Join(path, fname))
  730. if err != nil {
  731. apiAppendFileFail.Inc(1)
  732. return nil, "", err
  733. }
  734. entry := &ManifestEntry{
  735. Path: filepath.Join(path, fname),
  736. ContentType: mime.TypeByExtension(filepath.Ext(fname)),
  737. Mode: 0700,
  738. Size: totalSize,
  739. ModTime: time.Now(),
  740. }
  741. fkey, err := mw.AddEntry(ctx, io.Reader(combinedReader), entry)
  742. if err != nil {
  743. apiAppendFileFail.Inc(1)
  744. return nil, "", err
  745. }
  746. newMkey, err := mw.Store()
  747. if err != nil {
  748. apiAppendFileFail.Inc(1)
  749. return nil, "", err
  750. }
  751. return fkey, newMkey.String(), nil
  752. }
  753. // BuildDirectoryTree used by swarmfs_unix
  754. func (a *API) BuildDirectoryTree(ctx context.Context, mhash string, nameresolver bool) (addr storage.Address, manifestEntryMap map[string]*manifestTrieEntry, err error) {
  755. uri, err := Parse("bzz:/" + mhash)
  756. if err != nil {
  757. return nil, nil, err
  758. }
  759. addr, err = a.Resolve(ctx, uri)
  760. if err != nil {
  761. return nil, nil, err
  762. }
  763. quitC := make(chan bool)
  764. rootTrie, err := loadManifest(ctx, a.fileStore, addr, quitC)
  765. if err != nil {
  766. return nil, nil, fmt.Errorf("can't load manifest %v: %v", addr.String(), err)
  767. }
  768. manifestEntryMap = map[string]*manifestTrieEntry{}
  769. err = rootTrie.listWithPrefix(uri.Path, quitC, func(entry *manifestTrieEntry, suffix string) {
  770. manifestEntryMap[suffix] = entry
  771. })
  772. if err != nil {
  773. return nil, nil, fmt.Errorf("list with prefix failed %v: %v", addr.String(), err)
  774. }
  775. return addr, manifestEntryMap, nil
  776. }
  777. // ResourceLookup Looks up mutable resource updates at specific periods and versions
  778. func (a *API) ResourceLookup(ctx context.Context, addr storage.Address, period uint32, version uint32, maxLookup *mru.LookupParams) (string, []byte, error) {
  779. var err error
  780. rsrc, err := a.resource.Load(ctx, addr)
  781. if err != nil {
  782. return "", nil, err
  783. }
  784. if version != 0 {
  785. if period == 0 {
  786. return "", nil, mru.NewError(mru.ErrInvalidValue, "Period can't be 0")
  787. }
  788. _, err = a.resource.LookupVersion(ctx, rsrc.NameHash(), period, version, true, maxLookup)
  789. } else if period != 0 {
  790. _, err = a.resource.LookupHistorical(ctx, rsrc.NameHash(), period, true, maxLookup)
  791. } else {
  792. _, err = a.resource.LookupLatest(ctx, rsrc.NameHash(), true, maxLookup)
  793. }
  794. if err != nil {
  795. return "", nil, err
  796. }
  797. var data []byte
  798. _, data, err = a.resource.GetContent(rsrc.NameHash().Hex())
  799. if err != nil {
  800. return "", nil, err
  801. }
  802. return rsrc.Name(), data, nil
  803. }
  804. // ResourceCreate creates Resource and returns its key
  805. func (a *API) ResourceCreate(ctx context.Context, name string, frequency uint64) (storage.Address, error) {
  806. key, _, err := a.resource.New(ctx, name, frequency)
  807. if err != nil {
  808. return nil, err
  809. }
  810. return key, nil
  811. }
  812. // ResourceUpdateMultihash updates a Mutable Resource and marks the update's content to be of multihash type, which will be recognized upon retrieval.
  813. // It will fail if the data is not a valid multihash.
  814. func (a *API) ResourceUpdateMultihash(ctx context.Context, name string, data []byte) (storage.Address, uint32, uint32, error) {
  815. return a.resourceUpdate(ctx, name, data, true)
  816. }
  817. // ResourceUpdate updates a Mutable Resource with arbitrary data.
  818. // Upon retrieval the update will be retrieved verbatim as bytes.
  819. func (a *API) ResourceUpdate(ctx context.Context, name string, data []byte) (storage.Address, uint32, uint32, error) {
  820. return a.resourceUpdate(ctx, name, data, false)
  821. }
  822. func (a *API) resourceUpdate(ctx context.Context, name string, data []byte, multihash bool) (storage.Address, uint32, uint32, error) {
  823. var addr storage.Address
  824. var err error
  825. if multihash {
  826. addr, err = a.resource.UpdateMultihash(ctx, name, data)
  827. } else {
  828. addr, err = a.resource.Update(ctx, name, data)
  829. }
  830. period, _ := a.resource.GetLastPeriod(name)
  831. version, _ := a.resource.GetVersion(name)
  832. return addr, period, version, err
  833. }
  834. // ResourceHashSize returned the size of the digest produced by the Mutable Resource hashing function
  835. func (a *API) ResourceHashSize() int {
  836. return a.resource.HashSize
  837. }
  838. // ResourceIsValidated checks if the Mutable Resource has an active content validator.
  839. func (a *API) ResourceIsValidated() bool {
  840. return a.resource.IsValidated()
  841. }
  842. // ResolveResourceManifest retrieves the Mutable Resource manifest for the given address, and returns the address of the metadata chunk.
  843. func (a *API) ResolveResourceManifest(ctx context.Context, addr storage.Address) (storage.Address, error) {
  844. trie, err := loadManifest(ctx, a.fileStore, addr, nil)
  845. if err != nil {
  846. return nil, fmt.Errorf("cannot load resource manifest: %v", err)
  847. }
  848. entry, _ := trie.getEntry("")
  849. if entry.ContentType != ResourceContentType {
  850. return nil, fmt.Errorf("not a resource manifest: %s", addr)
  851. }
  852. return storage.Address(common.FromHex(entry.Hash)), nil
  853. }