api.go 29 KB

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