api.go 28 KB

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