api.go 31 KB

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