api.go 31 KB

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