api.go 30 KB

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