api.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  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 resoluton 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. // Upload to be used only in TEST
  230. func (a *API) Upload(ctx context.Context, uploadDir, index string, toEncrypt bool) (hash string, err error) {
  231. fs := NewFileSystem(a)
  232. hash, err = fs.Upload(uploadDir, index, toEncrypt)
  233. return hash, err
  234. }
  235. // Retrieve FileStore reader API
  236. func (a *API) Retrieve(ctx context.Context, addr storage.Address) (reader storage.LazySectionReader, isEncrypted bool) {
  237. return a.fileStore.Retrieve(ctx, addr)
  238. }
  239. // Store wraps the Store API call of the embedded FileStore
  240. 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) {
  241. log.Debug("api.store", "size", size)
  242. return a.fileStore.Store(ctx, data, size, toEncrypt)
  243. }
  244. // ErrResolve is returned when an URI cannot be resolved from ENS.
  245. type ErrResolve error
  246. // Resolve a name into a content-addressed hash
  247. // where address could be an ENS name, or a content addressed hash
  248. func (a *API) Resolve(ctx context.Context, address string) (storage.Address, error) {
  249. // if DNS is not configured, return an error
  250. if a.dns == nil {
  251. if hashMatcher.MatchString(address) {
  252. return common.Hex2Bytes(address), nil
  253. }
  254. apiResolveFail.Inc(1)
  255. return nil, fmt.Errorf("no DNS to resolve name: %q", address)
  256. }
  257. // try and resolve the address
  258. resolved, err := a.dns.Resolve(address)
  259. if err != nil {
  260. if hashMatcher.MatchString(address) {
  261. return common.Hex2Bytes(address), nil
  262. }
  263. return nil, err
  264. }
  265. return resolved[:], nil
  266. }
  267. // Resolve resolves a URI to an Address using the MultiResolver.
  268. func (a *API) ResolveURI(ctx context.Context, uri *URI, credentials string) (storage.Address, error) {
  269. apiResolveCount.Inc(1)
  270. log.Trace("resolving", "uri", uri.Addr)
  271. var sp opentracing.Span
  272. ctx, sp = spancontext.StartSpan(
  273. ctx,
  274. "api.resolve")
  275. defer sp.Finish()
  276. // if the URI is immutable, check if the address looks like a hash
  277. if uri.Immutable() {
  278. key := uri.Address()
  279. if key == nil {
  280. return nil, fmt.Errorf("immutable address not a content hash: %q", uri.Addr)
  281. }
  282. return key, nil
  283. }
  284. addr, err := a.Resolve(ctx, uri.Addr)
  285. if err != nil {
  286. return nil, err
  287. }
  288. if uri.Path == "" {
  289. return addr, nil
  290. }
  291. walker, err := a.NewManifestWalker(ctx, addr, a.Decryptor(ctx, credentials), nil)
  292. if err != nil {
  293. return nil, err
  294. }
  295. var entry *ManifestEntry
  296. walker.Walk(func(e *ManifestEntry) error {
  297. // if the entry matches the path, set entry and stop
  298. // the walk
  299. if e.Path == uri.Path {
  300. entry = e
  301. // return an error to cancel the walk
  302. return errors.New("found")
  303. }
  304. // ignore non-manifest files
  305. if e.ContentType != ManifestType {
  306. return nil
  307. }
  308. // if the manifest's path is a prefix of the
  309. // requested path, recurse into it by returning
  310. // nil and continuing the walk
  311. if strings.HasPrefix(uri.Path, e.Path) {
  312. return nil
  313. }
  314. return ErrSkipManifest
  315. })
  316. if entry == nil {
  317. return nil, errors.New("not found")
  318. }
  319. addr = storage.Address(common.Hex2Bytes(entry.Hash))
  320. return addr, nil
  321. }
  322. // Put provides singleton manifest creation on top of FileStore store
  323. func (a *API) Put(ctx context.Context, content string, contentType string, toEncrypt bool) (k storage.Address, wait func(context.Context) error, err error) {
  324. apiPutCount.Inc(1)
  325. r := strings.NewReader(content)
  326. key, waitContent, err := a.fileStore.Store(ctx, r, int64(len(content)), toEncrypt)
  327. if err != nil {
  328. apiPutFail.Inc(1)
  329. return nil, nil, err
  330. }
  331. manifest := fmt.Sprintf(`{"entries":[{"hash":"%v","contentType":"%s"}]}`, key, contentType)
  332. r = strings.NewReader(manifest)
  333. key, waitManifest, err := a.fileStore.Store(ctx, r, int64(len(manifest)), toEncrypt)
  334. if err != nil {
  335. apiPutFail.Inc(1)
  336. return nil, nil, err
  337. }
  338. return key, func(ctx context.Context) error {
  339. err := waitContent(ctx)
  340. if err != nil {
  341. return err
  342. }
  343. return waitManifest(ctx)
  344. }, nil
  345. }
  346. // Get uses iterative manifest retrieval and prefix matching
  347. // to resolve basePath to content using FileStore retrieve
  348. // it returns a section reader, mimeType, status, the key of the actual content and an error
  349. 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) {
  350. log.Debug("api.get", "key", manifestAddr, "path", path)
  351. apiGetCount.Inc(1)
  352. trie, err := loadManifest(ctx, a.fileStore, manifestAddr, nil, decrypt)
  353. if err != nil {
  354. apiGetNotFound.Inc(1)
  355. status = http.StatusNotFound
  356. return nil, "", http.StatusNotFound, nil, err
  357. }
  358. log.Debug("trie getting entry", "key", manifestAddr, "path", path)
  359. entry, _ := trie.getEntry(path)
  360. if entry != nil {
  361. log.Debug("trie got entry", "key", manifestAddr, "path", path, "entry.Hash", entry.Hash)
  362. if entry.ContentType == ManifestType {
  363. log.Debug("entry is manifest", "key", manifestAddr, "new key", entry.Hash)
  364. adr, err := hex.DecodeString(entry.Hash)
  365. if err != nil {
  366. return nil, "", 0, nil, err
  367. }
  368. return a.Get(ctx, decrypt, adr, entry.Path)
  369. }
  370. // we need to do some extra work if this is a mutable resource manifest
  371. if entry.ContentType == ResourceContentType {
  372. // get the resource rootAddr
  373. log.Trace("resource type", "menifestAddr", manifestAddr, "hash", entry.Hash)
  374. ctx, cancel := context.WithCancel(context.Background())
  375. defer cancel()
  376. rootAddr := storage.Address(common.FromHex(entry.Hash))
  377. rsrc, err := a.resource.Load(ctx, rootAddr)
  378. if err != nil {
  379. apiGetNotFound.Inc(1)
  380. status = http.StatusNotFound
  381. log.Debug(fmt.Sprintf("get resource content error: %v", err))
  382. return reader, mimeType, status, nil, err
  383. }
  384. // use this key to retrieve the latest update
  385. params := mru.LookupLatest(rootAddr)
  386. rsrc, err = a.resource.Lookup(ctx, params)
  387. if err != nil {
  388. apiGetNotFound.Inc(1)
  389. status = http.StatusNotFound
  390. log.Debug(fmt.Sprintf("get resource content error: %v", err))
  391. return reader, mimeType, status, nil, err
  392. }
  393. // if it's multihash, we will transparently serve the content this multihash points to
  394. // \TODO this resolve is rather expensive all in all, review to see if it can be achieved cheaper
  395. if rsrc.Multihash() {
  396. // get the data of the update
  397. _, rsrcData, err := a.resource.GetContent(rootAddr)
  398. if err != nil {
  399. apiGetNotFound.Inc(1)
  400. status = http.StatusNotFound
  401. log.Warn(fmt.Sprintf("get resource content error: %v", err))
  402. return reader, mimeType, status, nil, err
  403. }
  404. // validate that data as multihash
  405. decodedMultihash, err := multihash.FromMultihash(rsrcData)
  406. if err != nil {
  407. apiGetInvalid.Inc(1)
  408. status = http.StatusUnprocessableEntity
  409. log.Warn("invalid resource multihash", "err", err)
  410. return reader, mimeType, status, nil, err
  411. }
  412. manifestAddr = storage.Address(decodedMultihash)
  413. log.Trace("resource is multihash", "key", manifestAddr)
  414. // get the manifest the multihash digest points to
  415. trie, err := loadManifest(ctx, a.fileStore, manifestAddr, nil, decrypt)
  416. if err != nil {
  417. apiGetNotFound.Inc(1)
  418. status = http.StatusNotFound
  419. log.Warn(fmt.Sprintf("loadManifestTrie (resource multihash) error: %v", err))
  420. return reader, mimeType, status, nil, err
  421. }
  422. // finally, get the manifest entry
  423. // it will always be the entry on path ""
  424. entry, _ = trie.getEntry(path)
  425. if entry == nil {
  426. status = http.StatusNotFound
  427. apiGetNotFound.Inc(1)
  428. err = fmt.Errorf("manifest (resource multihash) entry for '%s' not found", path)
  429. log.Trace("manifest (resource multihash) entry not found", "key", manifestAddr, "path", path)
  430. return reader, mimeType, status, nil, err
  431. }
  432. } else {
  433. // data is returned verbatim since it's not a multihash
  434. return rsrc, "application/octet-stream", http.StatusOK, nil, nil
  435. }
  436. }
  437. // regardless of resource update manifests or normal manifests we will converge at this point
  438. // get the key the manifest entry points to and serve it if it's unambiguous
  439. contentAddr = common.Hex2Bytes(entry.Hash)
  440. status = entry.Status
  441. if status == http.StatusMultipleChoices {
  442. apiGetHTTP300.Inc(1)
  443. return nil, entry.ContentType, status, contentAddr, err
  444. }
  445. mimeType = entry.ContentType
  446. log.Debug("content lookup key", "key", contentAddr, "mimetype", mimeType)
  447. reader, _ = a.fileStore.Retrieve(ctx, contentAddr)
  448. } else {
  449. // no entry found
  450. status = http.StatusNotFound
  451. apiGetNotFound.Inc(1)
  452. err = fmt.Errorf("manifest entry for '%s' not found", path)
  453. log.Trace("manifest entry not found", "key", contentAddr, "path", path)
  454. }
  455. return
  456. }
  457. func (a *API) Delete(ctx context.Context, addr string, path string) (storage.Address, error) {
  458. apiDeleteCount.Inc(1)
  459. uri, err := Parse("bzz:/" + addr)
  460. if err != nil {
  461. apiDeleteFail.Inc(1)
  462. return nil, err
  463. }
  464. key, err := a.ResolveURI(ctx, uri, EMPTY_CREDENTIALS)
  465. if err != nil {
  466. return nil, err
  467. }
  468. newKey, err := a.UpdateManifest(ctx, key, func(mw *ManifestWriter) error {
  469. log.Debug(fmt.Sprintf("removing %s from manifest %s", path, key.Log()))
  470. return mw.RemoveEntry(path)
  471. })
  472. if err != nil {
  473. apiDeleteFail.Inc(1)
  474. return nil, err
  475. }
  476. return newKey, nil
  477. }
  478. // GetDirectoryTar fetches a requested directory as a tarstream
  479. // it returns an io.Reader and an error. Do not forget to Close() the returned ReadCloser
  480. func (a *API) GetDirectoryTar(ctx context.Context, decrypt DecryptFunc, uri *URI) (io.ReadCloser, error) {
  481. apiGetTarCount.Inc(1)
  482. addr, err := a.Resolve(ctx, uri.Addr)
  483. if err != nil {
  484. return nil, err
  485. }
  486. walker, err := a.NewManifestWalker(ctx, addr, decrypt, nil)
  487. if err != nil {
  488. apiGetTarFail.Inc(1)
  489. return nil, err
  490. }
  491. piper, pipew := io.Pipe()
  492. tw := tar.NewWriter(pipew)
  493. go func() {
  494. err := walker.Walk(func(entry *ManifestEntry) error {
  495. // ignore manifests (walk will recurse into them)
  496. if entry.ContentType == ManifestType {
  497. return nil
  498. }
  499. // retrieve the entry's key and size
  500. reader, _ := a.Retrieve(ctx, storage.Address(common.Hex2Bytes(entry.Hash)))
  501. size, err := reader.Size(ctx, nil)
  502. if err != nil {
  503. return err
  504. }
  505. // write a tar header for the entry
  506. hdr := &tar.Header{
  507. Name: entry.Path,
  508. Mode: entry.Mode,
  509. Size: size,
  510. ModTime: entry.ModTime,
  511. Xattrs: map[string]string{
  512. "user.swarm.content-type": entry.ContentType,
  513. },
  514. }
  515. if err := tw.WriteHeader(hdr); err != nil {
  516. return err
  517. }
  518. // copy the file into the tar stream
  519. n, err := io.Copy(tw, io.LimitReader(reader, hdr.Size))
  520. if err != nil {
  521. return err
  522. } else if n != size {
  523. return fmt.Errorf("error writing %s: expected %d bytes but sent %d", entry.Path, size, n)
  524. }
  525. return nil
  526. })
  527. // close tar writer before closing pipew
  528. // to flush remaining data to pipew
  529. // regardless of error value
  530. tw.Close()
  531. if err != nil {
  532. apiGetTarFail.Inc(1)
  533. pipew.CloseWithError(err)
  534. } else {
  535. pipew.Close()
  536. }
  537. }()
  538. return piper, nil
  539. }
  540. // GetManifestList lists the manifest entries for the specified address and prefix
  541. // and returns it as a ManifestList
  542. func (a *API) GetManifestList(ctx context.Context, decryptor DecryptFunc, addr storage.Address, prefix string) (list ManifestList, err error) {
  543. apiManifestListCount.Inc(1)
  544. walker, err := a.NewManifestWalker(ctx, addr, decryptor, nil)
  545. if err != nil {
  546. apiManifestListFail.Inc(1)
  547. return ManifestList{}, err
  548. }
  549. err = walker.Walk(func(entry *ManifestEntry) error {
  550. // handle non-manifest files
  551. if entry.ContentType != ManifestType {
  552. // ignore the file if it doesn't have the specified prefix
  553. if !strings.HasPrefix(entry.Path, prefix) {
  554. return nil
  555. }
  556. // if the path after the prefix contains a slash, add a
  557. // common prefix to the list, otherwise add the entry
  558. suffix := strings.TrimPrefix(entry.Path, prefix)
  559. if index := strings.Index(suffix, "/"); index > -1 {
  560. list.CommonPrefixes = append(list.CommonPrefixes, prefix+suffix[:index+1])
  561. return nil
  562. }
  563. if entry.Path == "" {
  564. entry.Path = "/"
  565. }
  566. list.Entries = append(list.Entries, entry)
  567. return nil
  568. }
  569. // if the manifest's path is a prefix of the specified prefix
  570. // then just recurse into the manifest by returning nil and
  571. // continuing the walk
  572. if strings.HasPrefix(prefix, entry.Path) {
  573. return nil
  574. }
  575. // if the manifest's path has the specified prefix, then if the
  576. // path after the prefix contains a slash, add a common prefix
  577. // to the list and skip the manifest, otherwise recurse into
  578. // the manifest by returning nil and continuing the walk
  579. if strings.HasPrefix(entry.Path, prefix) {
  580. suffix := strings.TrimPrefix(entry.Path, prefix)
  581. if index := strings.Index(suffix, "/"); index > -1 {
  582. list.CommonPrefixes = append(list.CommonPrefixes, prefix+suffix[:index+1])
  583. return ErrSkipManifest
  584. }
  585. return nil
  586. }
  587. // the manifest neither has the prefix or needs recursing in to
  588. // so just skip it
  589. return ErrSkipManifest
  590. })
  591. if err != nil {
  592. apiManifestListFail.Inc(1)
  593. return ManifestList{}, err
  594. }
  595. return list, nil
  596. }
  597. func (a *API) UpdateManifest(ctx context.Context, addr storage.Address, update func(mw *ManifestWriter) error) (storage.Address, error) {
  598. apiManifestUpdateCount.Inc(1)
  599. mw, err := a.NewManifestWriter(ctx, addr, nil)
  600. if err != nil {
  601. apiManifestUpdateFail.Inc(1)
  602. return nil, err
  603. }
  604. if err := update(mw); err != nil {
  605. apiManifestUpdateFail.Inc(1)
  606. return nil, err
  607. }
  608. addr, err = mw.Store()
  609. if err != nil {
  610. apiManifestUpdateFail.Inc(1)
  611. return nil, err
  612. }
  613. log.Debug(fmt.Sprintf("generated manifest %s", addr))
  614. return addr, nil
  615. }
  616. // Modify loads manifest and checks the content hash before recalculating and storing the manifest.
  617. func (a *API) Modify(ctx context.Context, addr storage.Address, path, contentHash, contentType string) (storage.Address, error) {
  618. apiModifyCount.Inc(1)
  619. quitC := make(chan bool)
  620. trie, err := loadManifest(ctx, a.fileStore, addr, quitC, NOOPDecrypt)
  621. if err != nil {
  622. apiModifyFail.Inc(1)
  623. return nil, err
  624. }
  625. if contentHash != "" {
  626. entry := newManifestTrieEntry(&ManifestEntry{
  627. Path: path,
  628. ContentType: contentType,
  629. }, nil)
  630. entry.Hash = contentHash
  631. trie.addEntry(entry, quitC)
  632. } else {
  633. trie.deleteEntry(path, quitC)
  634. }
  635. if err := trie.recalcAndStore(); err != nil {
  636. apiModifyFail.Inc(1)
  637. return nil, err
  638. }
  639. return trie.ref, nil
  640. }
  641. // AddFile creates a new manifest entry, adds it to swarm, then adds a file to swarm.
  642. func (a *API) AddFile(ctx context.Context, mhash, path, fname string, content []byte, nameresolver bool) (storage.Address, string, error) {
  643. apiAddFileCount.Inc(1)
  644. uri, err := Parse("bzz:/" + mhash)
  645. if err != nil {
  646. apiAddFileFail.Inc(1)
  647. return nil, "", err
  648. }
  649. mkey, err := a.ResolveURI(ctx, uri, EMPTY_CREDENTIALS)
  650. if err != nil {
  651. apiAddFileFail.Inc(1)
  652. return nil, "", err
  653. }
  654. // trim the root dir we added
  655. if path[:1] == "/" {
  656. path = path[1:]
  657. }
  658. entry := &ManifestEntry{
  659. Path: filepath.Join(path, fname),
  660. ContentType: mime.TypeByExtension(filepath.Ext(fname)),
  661. Mode: 0700,
  662. Size: int64(len(content)),
  663. ModTime: time.Now(),
  664. }
  665. mw, err := a.NewManifestWriter(ctx, mkey, nil)
  666. if err != nil {
  667. apiAddFileFail.Inc(1)
  668. return nil, "", err
  669. }
  670. fkey, err := mw.AddEntry(ctx, bytes.NewReader(content), entry)
  671. if err != nil {
  672. apiAddFileFail.Inc(1)
  673. return nil, "", err
  674. }
  675. newMkey, err := mw.Store()
  676. if err != nil {
  677. apiAddFileFail.Inc(1)
  678. return nil, "", err
  679. }
  680. return fkey, newMkey.String(), nil
  681. }
  682. func (a *API) UploadTar(ctx context.Context, bodyReader io.ReadCloser, manifestPath, defaultPath string, mw *ManifestWriter) (storage.Address, error) {
  683. apiUploadTarCount.Inc(1)
  684. var contentKey storage.Address
  685. tr := tar.NewReader(bodyReader)
  686. defer bodyReader.Close()
  687. var defaultPathFound bool
  688. for {
  689. hdr, err := tr.Next()
  690. if err == io.EOF {
  691. break
  692. } else if err != nil {
  693. apiUploadTarFail.Inc(1)
  694. return nil, fmt.Errorf("error reading tar stream: %s", err)
  695. }
  696. // only store regular files
  697. if !hdr.FileInfo().Mode().IsRegular() {
  698. continue
  699. }
  700. // add the entry under the path from the request
  701. manifestPath := path.Join(manifestPath, hdr.Name)
  702. entry := &ManifestEntry{
  703. Path: manifestPath,
  704. ContentType: hdr.Xattrs["user.swarm.content-type"],
  705. Mode: hdr.Mode,
  706. Size: hdr.Size,
  707. ModTime: hdr.ModTime,
  708. }
  709. contentKey, err = mw.AddEntry(ctx, tr, entry)
  710. if err != nil {
  711. apiUploadTarFail.Inc(1)
  712. return nil, fmt.Errorf("error adding manifest entry from tar stream: %s", err)
  713. }
  714. if hdr.Name == defaultPath {
  715. entry := &ManifestEntry{
  716. Hash: contentKey.Hex(),
  717. Path: "", // default entry
  718. ContentType: hdr.Xattrs["user.swarm.content-type"],
  719. Mode: hdr.Mode,
  720. Size: hdr.Size,
  721. ModTime: hdr.ModTime,
  722. }
  723. contentKey, err = mw.AddEntry(ctx, nil, entry)
  724. if err != nil {
  725. apiUploadTarFail.Inc(1)
  726. return nil, fmt.Errorf("error adding default manifest entry from tar stream: %s", err)
  727. }
  728. defaultPathFound = true
  729. }
  730. }
  731. if defaultPath != "" && !defaultPathFound {
  732. return contentKey, fmt.Errorf("default path %q not found", defaultPath)
  733. }
  734. return contentKey, nil
  735. }
  736. // RemoveFile removes a file entry in a manifest.
  737. func (a *API) RemoveFile(ctx context.Context, mhash string, path string, fname string, nameresolver bool) (string, error) {
  738. apiRmFileCount.Inc(1)
  739. uri, err := Parse("bzz:/" + mhash)
  740. if err != nil {
  741. apiRmFileFail.Inc(1)
  742. return "", err
  743. }
  744. mkey, err := a.ResolveURI(ctx, uri, EMPTY_CREDENTIALS)
  745. if err != nil {
  746. apiRmFileFail.Inc(1)
  747. return "", err
  748. }
  749. // trim the root dir we added
  750. if path[:1] == "/" {
  751. path = path[1:]
  752. }
  753. mw, err := a.NewManifestWriter(ctx, mkey, nil)
  754. if err != nil {
  755. apiRmFileFail.Inc(1)
  756. return "", err
  757. }
  758. err = mw.RemoveEntry(filepath.Join(path, fname))
  759. if err != nil {
  760. apiRmFileFail.Inc(1)
  761. return "", err
  762. }
  763. newMkey, err := mw.Store()
  764. if err != nil {
  765. apiRmFileFail.Inc(1)
  766. return "", err
  767. }
  768. return newMkey.String(), nil
  769. }
  770. // AppendFile removes old manifest, appends file entry to new manifest and adds it to Swarm.
  771. 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) {
  772. apiAppendFileCount.Inc(1)
  773. buffSize := offset + addSize
  774. if buffSize < existingSize {
  775. buffSize = existingSize
  776. }
  777. buf := make([]byte, buffSize)
  778. oldReader, _ := a.Retrieve(ctx, oldAddr)
  779. io.ReadAtLeast(oldReader, buf, int(offset))
  780. newReader := bytes.NewReader(content)
  781. io.ReadAtLeast(newReader, buf[offset:], int(addSize))
  782. if buffSize < existingSize {
  783. io.ReadAtLeast(oldReader, buf[addSize:], int(buffSize))
  784. }
  785. combinedReader := bytes.NewReader(buf)
  786. totalSize := int64(len(buf))
  787. // TODO(jmozah): to append using pyramid chunker when it is ready
  788. //oldReader := a.Retrieve(oldKey)
  789. //newReader := bytes.NewReader(content)
  790. //combinedReader := io.MultiReader(oldReader, newReader)
  791. uri, err := Parse("bzz:/" + mhash)
  792. if err != nil {
  793. apiAppendFileFail.Inc(1)
  794. return nil, "", err
  795. }
  796. mkey, err := a.ResolveURI(ctx, uri, EMPTY_CREDENTIALS)
  797. if err != nil {
  798. apiAppendFileFail.Inc(1)
  799. return nil, "", err
  800. }
  801. // trim the root dir we added
  802. if path[:1] == "/" {
  803. path = path[1:]
  804. }
  805. mw, err := a.NewManifestWriter(ctx, mkey, nil)
  806. if err != nil {
  807. apiAppendFileFail.Inc(1)
  808. return nil, "", err
  809. }
  810. err = mw.RemoveEntry(filepath.Join(path, fname))
  811. if err != nil {
  812. apiAppendFileFail.Inc(1)
  813. return nil, "", err
  814. }
  815. entry := &ManifestEntry{
  816. Path: filepath.Join(path, fname),
  817. ContentType: mime.TypeByExtension(filepath.Ext(fname)),
  818. Mode: 0700,
  819. Size: totalSize,
  820. ModTime: time.Now(),
  821. }
  822. fkey, err := mw.AddEntry(ctx, io.Reader(combinedReader), entry)
  823. if err != nil {
  824. apiAppendFileFail.Inc(1)
  825. return nil, "", err
  826. }
  827. newMkey, err := mw.Store()
  828. if err != nil {
  829. apiAppendFileFail.Inc(1)
  830. return nil, "", err
  831. }
  832. return fkey, newMkey.String(), nil
  833. }
  834. // BuildDirectoryTree used by swarmfs_unix
  835. func (a *API) BuildDirectoryTree(ctx context.Context, mhash string, nameresolver bool) (addr storage.Address, manifestEntryMap map[string]*manifestTrieEntry, err error) {
  836. uri, err := Parse("bzz:/" + mhash)
  837. if err != nil {
  838. return nil, nil, err
  839. }
  840. addr, err = a.Resolve(ctx, uri.Addr)
  841. if err != nil {
  842. return nil, nil, err
  843. }
  844. quitC := make(chan bool)
  845. rootTrie, err := loadManifest(ctx, a.fileStore, addr, quitC, NOOPDecrypt)
  846. if err != nil {
  847. return nil, nil, fmt.Errorf("can't load manifest %v: %v", addr.String(), err)
  848. }
  849. manifestEntryMap = map[string]*manifestTrieEntry{}
  850. err = rootTrie.listWithPrefix(uri.Path, quitC, func(entry *manifestTrieEntry, suffix string) {
  851. manifestEntryMap[suffix] = entry
  852. })
  853. if err != nil {
  854. return nil, nil, fmt.Errorf("list with prefix failed %v: %v", addr.String(), err)
  855. }
  856. return addr, manifestEntryMap, nil
  857. }
  858. // ResourceLookup finds mutable resource updates at specific periods and versions
  859. func (a *API) ResourceLookup(ctx context.Context, params *mru.LookupParams) (string, []byte, error) {
  860. var err error
  861. rsrc, err := a.resource.Load(ctx, params.RootAddr())
  862. if err != nil {
  863. return "", nil, err
  864. }
  865. _, err = a.resource.Lookup(ctx, params)
  866. if err != nil {
  867. return "", nil, err
  868. }
  869. var data []byte
  870. _, data, err = a.resource.GetContent(params.RootAddr())
  871. if err != nil {
  872. return "", nil, err
  873. }
  874. return rsrc.Name(), data, nil
  875. }
  876. // Create Mutable resource
  877. func (a *API) ResourceCreate(ctx context.Context, request *mru.Request) error {
  878. return a.resource.New(ctx, request)
  879. }
  880. // ResourceNewRequest creates a Request object to update a specific mutable resource
  881. func (a *API) ResourceNewRequest(ctx context.Context, rootAddr storage.Address) (*mru.Request, error) {
  882. return a.resource.NewUpdateRequest(ctx, rootAddr)
  883. }
  884. // ResourceUpdate updates a Mutable Resource with arbitrary data.
  885. // Upon retrieval the update will be retrieved verbatim as bytes.
  886. func (a *API) ResourceUpdate(ctx context.Context, request *mru.SignedResourceUpdate) (storage.Address, error) {
  887. return a.resource.Update(ctx, request)
  888. }
  889. // ResourceHashSize returned the size of the digest produced by the Mutable Resource hashing function
  890. func (a *API) ResourceHashSize() int {
  891. return a.resource.HashSize
  892. }
  893. // ResolveResourceManifest retrieves the Mutable Resource manifest for the given address, and returns the address of the metadata chunk.
  894. func (a *API) ResolveResourceManifest(ctx context.Context, addr storage.Address) (storage.Address, error) {
  895. trie, err := loadManifest(ctx, a.fileStore, addr, nil, NOOPDecrypt)
  896. if err != nil {
  897. return nil, fmt.Errorf("cannot load resource manifest: %v", err)
  898. }
  899. entry, _ := trie.getEntry("")
  900. if entry.ContentType != ResourceContentType {
  901. return nil, fmt.Errorf("not a resource manifest: %s", addr)
  902. }
  903. return storage.Address(common.FromHex(entry.Hash)), nil
  904. }