api.go 28 KB

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