server.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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. /*
  17. A simple http server interface to Swarm
  18. */
  19. package http
  20. import (
  21. "bufio"
  22. "bytes"
  23. "encoding/json"
  24. "fmt"
  25. "io"
  26. "io/ioutil"
  27. "mime"
  28. "mime/multipart"
  29. "net/http"
  30. "os"
  31. "path"
  32. "strconv"
  33. "strings"
  34. "time"
  35. "github.com/ethereum/go-ethereum/common"
  36. "github.com/ethereum/go-ethereum/metrics"
  37. "github.com/ethereum/go-ethereum/swarm/api"
  38. "github.com/ethereum/go-ethereum/swarm/log"
  39. "github.com/ethereum/go-ethereum/swarm/storage"
  40. "github.com/ethereum/go-ethereum/swarm/storage/feed"
  41. "github.com/rs/cors"
  42. )
  43. type resourceResponse struct {
  44. Manifest storage.Address `json:"manifest"`
  45. Resource string `json:"resource"`
  46. Update storage.Address `json:"update"`
  47. }
  48. var (
  49. postRawCount = metrics.NewRegisteredCounter("api.http.post.raw.count", nil)
  50. postRawFail = metrics.NewRegisteredCounter("api.http.post.raw.fail", nil)
  51. postFilesCount = metrics.NewRegisteredCounter("api.http.post.files.count", nil)
  52. postFilesFail = metrics.NewRegisteredCounter("api.http.post.files.fail", nil)
  53. deleteCount = metrics.NewRegisteredCounter("api.http.delete.count", nil)
  54. deleteFail = metrics.NewRegisteredCounter("api.http.delete.fail", nil)
  55. getCount = metrics.NewRegisteredCounter("api.http.get.count", nil)
  56. getFail = metrics.NewRegisteredCounter("api.http.get.fail", nil)
  57. getFileCount = metrics.NewRegisteredCounter("api.http.get.file.count", nil)
  58. getFileNotFound = metrics.NewRegisteredCounter("api.http.get.file.notfound", nil)
  59. getFileFail = metrics.NewRegisteredCounter("api.http.get.file.fail", nil)
  60. getListCount = metrics.NewRegisteredCounter("api.http.get.list.count", nil)
  61. getListFail = metrics.NewRegisteredCounter("api.http.get.list.fail", nil)
  62. )
  63. type methodHandler map[string]http.Handler
  64. func (m methodHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  65. v, ok := m[r.Method]
  66. if ok {
  67. v.ServeHTTP(rw, r)
  68. return
  69. }
  70. rw.WriteHeader(http.StatusMethodNotAllowed)
  71. }
  72. func NewServer(api *api.API, corsString string) *Server {
  73. var allowedOrigins []string
  74. for _, domain := range strings.Split(corsString, ",") {
  75. allowedOrigins = append(allowedOrigins, strings.TrimSpace(domain))
  76. }
  77. c := cors.New(cors.Options{
  78. AllowedOrigins: allowedOrigins,
  79. AllowedMethods: []string{http.MethodPost, http.MethodGet, http.MethodDelete, http.MethodPatch, http.MethodPut},
  80. MaxAge: 600,
  81. AllowedHeaders: []string{"*"},
  82. })
  83. server := &Server{api: api}
  84. defaultMiddlewares := []Adapter{
  85. RecoverPanic,
  86. SetRequestID,
  87. SetRequestHost,
  88. InitLoggingResponseWriter,
  89. ParseURI,
  90. InstrumentOpenTracing,
  91. }
  92. mux := http.NewServeMux()
  93. mux.Handle("/bzz:/", methodHandler{
  94. "GET": Adapt(
  95. http.HandlerFunc(server.HandleBzzGet),
  96. defaultMiddlewares...,
  97. ),
  98. "POST": Adapt(
  99. http.HandlerFunc(server.HandlePostFiles),
  100. defaultMiddlewares...,
  101. ),
  102. "DELETE": Adapt(
  103. http.HandlerFunc(server.HandleDelete),
  104. defaultMiddlewares...,
  105. ),
  106. })
  107. mux.Handle("/bzz-raw:/", methodHandler{
  108. "GET": Adapt(
  109. http.HandlerFunc(server.HandleGet),
  110. defaultMiddlewares...,
  111. ),
  112. "POST": Adapt(
  113. http.HandlerFunc(server.HandlePostRaw),
  114. defaultMiddlewares...,
  115. ),
  116. })
  117. mux.Handle("/bzz-immutable:/", methodHandler{
  118. "GET": Adapt(
  119. http.HandlerFunc(server.HandleBzzGet),
  120. defaultMiddlewares...,
  121. ),
  122. })
  123. mux.Handle("/bzz-hash:/", methodHandler{
  124. "GET": Adapt(
  125. http.HandlerFunc(server.HandleGet),
  126. defaultMiddlewares...,
  127. ),
  128. })
  129. mux.Handle("/bzz-list:/", methodHandler{
  130. "GET": Adapt(
  131. http.HandlerFunc(server.HandleGetList),
  132. defaultMiddlewares...,
  133. ),
  134. })
  135. mux.Handle("/bzz-feed:/", methodHandler{
  136. "GET": Adapt(
  137. http.HandlerFunc(server.HandleGetFeed),
  138. defaultMiddlewares...,
  139. ),
  140. "POST": Adapt(
  141. http.HandlerFunc(server.HandlePostFeed),
  142. defaultMiddlewares...,
  143. ),
  144. })
  145. mux.Handle("/", methodHandler{
  146. "GET": Adapt(
  147. http.HandlerFunc(server.HandleRootPaths),
  148. SetRequestID,
  149. InitLoggingResponseWriter,
  150. ),
  151. })
  152. server.Handler = c.Handler(mux)
  153. return server
  154. }
  155. func (s *Server) ListenAndServe(addr string) error {
  156. s.listenAddr = addr
  157. return http.ListenAndServe(addr, s)
  158. }
  159. // browser API for registering bzz url scheme handlers:
  160. // https://developer.mozilla.org/en/docs/Web-based_protocol_handlers
  161. // electron (chromium) api for registering bzz url scheme handlers:
  162. // https://github.com/atom/electron/blob/master/docs/api/protocol.md
  163. type Server struct {
  164. http.Handler
  165. api *api.API
  166. listenAddr string
  167. }
  168. func (s *Server) HandleBzzGet(w http.ResponseWriter, r *http.Request) {
  169. log.Debug("handleBzzGet", "ruid", GetRUID(r.Context()), "uri", r.RequestURI)
  170. if r.Header.Get("Accept") == "application/x-tar" {
  171. uri := GetURI(r.Context())
  172. _, credentials, _ := r.BasicAuth()
  173. reader, err := s.api.GetDirectoryTar(r.Context(), s.api.Decryptor(r.Context(), credentials), uri)
  174. if err != nil {
  175. if isDecryptError(err) {
  176. w.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=%q", uri.Address().String()))
  177. RespondError(w, r, err.Error(), http.StatusUnauthorized)
  178. return
  179. }
  180. RespondError(w, r, fmt.Sprintf("Had an error building the tarball: %v", err), http.StatusInternalServerError)
  181. return
  182. }
  183. defer reader.Close()
  184. w.Header().Set("Content-Type", "application/x-tar")
  185. fileName := uri.Addr
  186. if found := path.Base(uri.Path); found != "" && found != "." && found != "/" {
  187. fileName = found
  188. }
  189. w.Header().Set("Content-Disposition", fmt.Sprintf("inline; filename=\"%s.tar\"", fileName))
  190. w.WriteHeader(http.StatusOK)
  191. io.Copy(w, reader)
  192. return
  193. }
  194. s.HandleGetFile(w, r)
  195. }
  196. func (s *Server) HandleRootPaths(w http.ResponseWriter, r *http.Request) {
  197. switch r.RequestURI {
  198. case "/":
  199. RespondTemplate(w, r, "landing-page", "Swarm: Please request a valid ENS or swarm hash with the appropriate bzz scheme", 200)
  200. return
  201. case "/robots.txt":
  202. w.Header().Set("Last-Modified", time.Now().Format(http.TimeFormat))
  203. fmt.Fprintf(w, "User-agent: *\nDisallow: /")
  204. case "/favicon.ico":
  205. w.WriteHeader(http.StatusOK)
  206. w.Write(faviconBytes)
  207. default:
  208. RespondError(w, r, "Not Found", http.StatusNotFound)
  209. }
  210. }
  211. // HandlePostRaw handles a POST request to a raw bzz-raw:/ URI, stores the request
  212. // body in swarm and returns the resulting storage address as a text/plain response
  213. func (s *Server) HandlePostRaw(w http.ResponseWriter, r *http.Request) {
  214. ruid := GetRUID(r.Context())
  215. log.Debug("handle.post.raw", "ruid", ruid)
  216. postRawCount.Inc(1)
  217. toEncrypt := false
  218. uri := GetURI(r.Context())
  219. if uri.Addr == "encrypt" {
  220. toEncrypt = true
  221. }
  222. if uri.Path != "" {
  223. postRawFail.Inc(1)
  224. RespondError(w, r, "raw POST request cannot contain a path", http.StatusBadRequest)
  225. return
  226. }
  227. if uri.Addr != "" && uri.Addr != "encrypt" {
  228. postRawFail.Inc(1)
  229. RespondError(w, r, "raw POST request addr can only be empty or \"encrypt\"", http.StatusBadRequest)
  230. return
  231. }
  232. if r.Header.Get("Content-Length") == "" {
  233. postRawFail.Inc(1)
  234. RespondError(w, r, "missing Content-Length header in request", http.StatusBadRequest)
  235. return
  236. }
  237. addr, _, err := s.api.Store(r.Context(), r.Body, r.ContentLength, toEncrypt)
  238. if err != nil {
  239. postRawFail.Inc(1)
  240. RespondError(w, r, err.Error(), http.StatusInternalServerError)
  241. return
  242. }
  243. log.Debug("stored content", "ruid", ruid, "key", addr)
  244. w.Header().Set("Content-Type", "text/plain")
  245. w.WriteHeader(http.StatusOK)
  246. fmt.Fprint(w, addr)
  247. }
  248. // HandlePostFiles handles a POST request to
  249. // bzz:/<hash>/<path> which contains either a single file or multiple files
  250. // (either a tar archive or multipart form), adds those files either to an
  251. // existing manifest or to a new manifest under <path> and returns the
  252. // resulting manifest hash as a text/plain response
  253. func (s *Server) HandlePostFiles(w http.ResponseWriter, r *http.Request) {
  254. ruid := GetRUID(r.Context())
  255. log.Debug("handle.post.files", "ruid", ruid)
  256. postFilesCount.Inc(1)
  257. contentType, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
  258. if err != nil {
  259. postFilesFail.Inc(1)
  260. RespondError(w, r, err.Error(), http.StatusBadRequest)
  261. return
  262. }
  263. toEncrypt := false
  264. uri := GetURI(r.Context())
  265. if uri.Addr == "encrypt" {
  266. toEncrypt = true
  267. }
  268. var addr storage.Address
  269. if uri.Addr != "" && uri.Addr != "encrypt" {
  270. addr, err = s.api.Resolve(r.Context(), uri.Addr)
  271. if err != nil {
  272. postFilesFail.Inc(1)
  273. RespondError(w, r, fmt.Sprintf("cannot resolve %s: %s", uri.Addr, err), http.StatusInternalServerError)
  274. return
  275. }
  276. log.Debug("resolved key", "ruid", ruid, "key", addr)
  277. } else {
  278. addr, err = s.api.NewManifest(r.Context(), toEncrypt)
  279. if err != nil {
  280. postFilesFail.Inc(1)
  281. RespondError(w, r, err.Error(), http.StatusInternalServerError)
  282. return
  283. }
  284. log.Debug("new manifest", "ruid", ruid, "key", addr)
  285. }
  286. newAddr, err := s.api.UpdateManifest(r.Context(), addr, func(mw *api.ManifestWriter) error {
  287. switch contentType {
  288. case "application/x-tar":
  289. _, err := s.handleTarUpload(r, mw)
  290. if err != nil {
  291. RespondError(w, r, fmt.Sprintf("error uploading tarball: %v", err), http.StatusInternalServerError)
  292. return err
  293. }
  294. return nil
  295. case "multipart/form-data":
  296. return s.handleMultipartUpload(r, params["boundary"], mw)
  297. default:
  298. return s.handleDirectUpload(r, mw)
  299. }
  300. })
  301. if err != nil {
  302. postFilesFail.Inc(1)
  303. RespondError(w, r, fmt.Sprintf("cannot create manifest: %s", err), http.StatusInternalServerError)
  304. return
  305. }
  306. log.Debug("stored content", "ruid", ruid, "key", newAddr)
  307. w.Header().Set("Content-Type", "text/plain")
  308. w.WriteHeader(http.StatusOK)
  309. fmt.Fprint(w, newAddr)
  310. }
  311. func (s *Server) handleTarUpload(r *http.Request, mw *api.ManifestWriter) (storage.Address, error) {
  312. log.Debug("handle.tar.upload", "ruid", GetRUID(r.Context()))
  313. defaultPath := r.URL.Query().Get("defaultpath")
  314. key, err := s.api.UploadTar(r.Context(), r.Body, GetURI(r.Context()).Path, defaultPath, mw)
  315. if err != nil {
  316. return nil, err
  317. }
  318. return key, nil
  319. }
  320. func (s *Server) handleMultipartUpload(r *http.Request, boundary string, mw *api.ManifestWriter) error {
  321. ruid := GetRUID(r.Context())
  322. log.Debug("handle.multipart.upload", "ruid", ruid)
  323. mr := multipart.NewReader(r.Body, boundary)
  324. for {
  325. part, err := mr.NextPart()
  326. if err == io.EOF {
  327. return nil
  328. } else if err != nil {
  329. return fmt.Errorf("error reading multipart form: %s", err)
  330. }
  331. var size int64
  332. var reader io.Reader = part
  333. if contentLength := part.Header.Get("Content-Length"); contentLength != "" {
  334. size, err = strconv.ParseInt(contentLength, 10, 64)
  335. if err != nil {
  336. return fmt.Errorf("error parsing multipart content length: %s", err)
  337. }
  338. reader = part
  339. } else {
  340. // copy the part to a tmp file to get its size
  341. tmp, err := ioutil.TempFile("", "swarm-multipart")
  342. if err != nil {
  343. return err
  344. }
  345. defer os.Remove(tmp.Name())
  346. defer tmp.Close()
  347. size, err = io.Copy(tmp, part)
  348. if err != nil {
  349. return fmt.Errorf("error copying multipart content: %s", err)
  350. }
  351. if _, err := tmp.Seek(0, io.SeekStart); err != nil {
  352. return fmt.Errorf("error copying multipart content: %s", err)
  353. }
  354. reader = tmp
  355. }
  356. // add the entry under the path from the request
  357. name := part.FileName()
  358. if name == "" {
  359. name = part.FormName()
  360. }
  361. uri := GetURI(r.Context())
  362. path := path.Join(uri.Path, name)
  363. entry := &api.ManifestEntry{
  364. Path: path,
  365. ContentType: part.Header.Get("Content-Type"),
  366. Size: size,
  367. ModTime: time.Now(),
  368. }
  369. log.Debug("adding path to new manifest", "ruid", ruid, "bytes", entry.Size, "path", entry.Path)
  370. contentKey, err := mw.AddEntry(r.Context(), reader, entry)
  371. if err != nil {
  372. return fmt.Errorf("error adding manifest entry from multipart form: %s", err)
  373. }
  374. log.Debug("stored content", "ruid", ruid, "key", contentKey)
  375. }
  376. }
  377. func (s *Server) handleDirectUpload(r *http.Request, mw *api.ManifestWriter) error {
  378. ruid := GetRUID(r.Context())
  379. log.Debug("handle.direct.upload", "ruid", ruid)
  380. key, err := mw.AddEntry(r.Context(), r.Body, &api.ManifestEntry{
  381. Path: GetURI(r.Context()).Path,
  382. ContentType: r.Header.Get("Content-Type"),
  383. Mode: 0644,
  384. Size: r.ContentLength,
  385. ModTime: time.Now(),
  386. })
  387. if err != nil {
  388. return err
  389. }
  390. log.Debug("stored content", "ruid", ruid, "key", key)
  391. return nil
  392. }
  393. // HandleDelete handles a DELETE request to bzz:/<manifest>/<path>, removes
  394. // <path> from <manifest> and returns the resulting manifest hash as a
  395. // text/plain response
  396. func (s *Server) HandleDelete(w http.ResponseWriter, r *http.Request) {
  397. ruid := GetRUID(r.Context())
  398. uri := GetURI(r.Context())
  399. log.Debug("handle.delete", "ruid", ruid)
  400. deleteCount.Inc(1)
  401. newKey, err := s.api.Delete(r.Context(), uri.Addr, uri.Path)
  402. if err != nil {
  403. deleteFail.Inc(1)
  404. RespondError(w, r, fmt.Sprintf("could not delete from manifest: %v", err), http.StatusInternalServerError)
  405. return
  406. }
  407. w.Header().Set("Content-Type", "text/plain")
  408. w.WriteHeader(http.StatusOK)
  409. fmt.Fprint(w, newKey)
  410. }
  411. // Handles feed manifest creation and feed updates
  412. // The POST request admits a JSON structure as defined in the feeds package: `feed.updateRequestJSON`
  413. // The requests can be to a) create a feed manifest, b) update a feed or c) both a+b: create a feed manifest and publish a first update
  414. func (s *Server) HandlePostFeed(w http.ResponseWriter, r *http.Request) {
  415. ruid := GetRUID(r.Context())
  416. uri := GetURI(r.Context())
  417. log.Debug("handle.post.feed", "ruid", ruid)
  418. var err error
  419. // Creation and update must send feed.updateRequestJSON JSON structure
  420. body, err := ioutil.ReadAll(r.Body)
  421. if err != nil {
  422. RespondError(w, r, err.Error(), http.StatusInternalServerError)
  423. return
  424. }
  425. fd, err := s.api.ResolveFeed(r.Context(), uri, r.URL.Query())
  426. if err != nil { // couldn't parse query string or retrieve manifest
  427. getFail.Inc(1)
  428. httpStatus := http.StatusBadRequest
  429. if err == api.ErrCannotLoadFeedManifest || err == api.ErrCannotResolveFeedURI {
  430. httpStatus = http.StatusNotFound
  431. }
  432. RespondError(w, r, fmt.Sprintf("cannot retrieve feed from manifest: %s", err), httpStatus)
  433. return
  434. }
  435. var updateRequest feed.Request
  436. updateRequest.Feed = *fd
  437. query := r.URL.Query()
  438. if err := updateRequest.FromValues(query, body); err != nil { // decodes request from query parameters
  439. RespondError(w, r, err.Error(), http.StatusBadRequest)
  440. return
  441. }
  442. if updateRequest.IsUpdate() {
  443. // Verify that the signature is intact and that the signer is authorized
  444. // to update this feed
  445. // Check this early, to avoid creating a feed and then not being able to set its first update.
  446. if err = updateRequest.Verify(); err != nil {
  447. RespondError(w, r, err.Error(), http.StatusForbidden)
  448. return
  449. }
  450. _, err = s.api.FeedsUpdate(r.Context(), &updateRequest)
  451. if err != nil {
  452. RespondError(w, r, err.Error(), http.StatusInternalServerError)
  453. return
  454. }
  455. }
  456. if query.Get("manifest") == "1" {
  457. // we create a manifest so we can retrieve feed updates with bzz:// later
  458. // this manifest has a special "feed type" manifest, and saves the
  459. // feed identification used to retrieve feed updates later
  460. m, err := s.api.NewFeedManifest(r.Context(), &updateRequest.Feed)
  461. if err != nil {
  462. RespondError(w, r, fmt.Sprintf("failed to create feed manifest: %v", err), http.StatusInternalServerError)
  463. return
  464. }
  465. // the key to the manifest will be passed back to the client
  466. // the client can access the feed directly through its Feed member
  467. // the manifest key can be set as content in the resolver of the ENS name
  468. outdata, err := json.Marshal(m)
  469. if err != nil {
  470. RespondError(w, r, fmt.Sprintf("failed to create json response: %s", err), http.StatusInternalServerError)
  471. return
  472. }
  473. fmt.Fprint(w, string(outdata))
  474. w.Header().Add("Content-type", "application/json")
  475. }
  476. }
  477. // HandleGetFeed retrieves Swarm feeds updates:
  478. // bzz-feed://<manifest address or ENS name> - get latest feed update, given a manifest address
  479. // - or -
  480. // specify user + topic (optional), subtopic name (optional) directly, without manifest:
  481. // bzz-feed://?user=0x...&topic=0x...&name=subtopic name
  482. // topic defaults to 0x000... if not specified.
  483. // name defaults to empty string if not specified.
  484. // thus, empty name and topic refers to the user's default feed.
  485. //
  486. // Optional parameters:
  487. // time=xx - get the latest update before time (in epoch seconds)
  488. // hint.time=xx - hint the lookup algorithm looking for updates at around that time
  489. // hint.level=xx - hint the lookup algorithm looking for updates at around this frequency level
  490. // meta=1 - get feed metadata and status information instead of performing a feed query
  491. // NOTE: meta=1 will be deprecated in the near future
  492. func (s *Server) HandleGetFeed(w http.ResponseWriter, r *http.Request) {
  493. ruid := GetRUID(r.Context())
  494. uri := GetURI(r.Context())
  495. log.Debug("handle.get.feed", "ruid", ruid)
  496. var err error
  497. fd, err := s.api.ResolveFeed(r.Context(), uri, r.URL.Query())
  498. if err != nil { // couldn't parse query string or retrieve manifest
  499. getFail.Inc(1)
  500. httpStatus := http.StatusBadRequest
  501. if err == api.ErrCannotLoadFeedManifest || err == api.ErrCannotResolveFeedURI {
  502. httpStatus = http.StatusNotFound
  503. }
  504. RespondError(w, r, fmt.Sprintf("cannot retrieve feed information from manifest: %s", err), httpStatus)
  505. return
  506. }
  507. // determine if the query specifies period and version or it is a metadata query
  508. if r.URL.Query().Get("meta") == "1" {
  509. unsignedUpdateRequest, err := s.api.FeedsNewRequest(r.Context(), fd)
  510. if err != nil {
  511. getFail.Inc(1)
  512. RespondError(w, r, fmt.Sprintf("cannot retrieve feed metadata for feed=%s: %s", fd.Hex(), err), http.StatusNotFound)
  513. return
  514. }
  515. rawResponse, err := unsignedUpdateRequest.MarshalJSON()
  516. if err != nil {
  517. RespondError(w, r, fmt.Sprintf("cannot encode unsigned feed update request: %v", err), http.StatusInternalServerError)
  518. return
  519. }
  520. w.Header().Add("Content-type", "application/json")
  521. w.WriteHeader(http.StatusOK)
  522. fmt.Fprint(w, string(rawResponse))
  523. return
  524. }
  525. lookupParams := &feed.Query{Feed: *fd}
  526. if err = lookupParams.FromValues(r.URL.Query()); err != nil { // parse period, version
  527. RespondError(w, r, fmt.Sprintf("invalid feed update request:%s", err), http.StatusBadRequest)
  528. return
  529. }
  530. data, err := s.api.FeedsLookup(r.Context(), lookupParams)
  531. // any error from the switch statement will end up here
  532. if err != nil {
  533. code, err2 := s.translateFeedError(w, r, "feed lookup fail", err)
  534. RespondError(w, r, err2.Error(), code)
  535. return
  536. }
  537. // All ok, serve the retrieved update
  538. log.Debug("Found update", "feed", fd.Hex(), "ruid", ruid)
  539. w.Header().Set("Content-Type", api.MimeOctetStream)
  540. http.ServeContent(w, r, "", time.Now(), bytes.NewReader(data))
  541. }
  542. func (s *Server) translateFeedError(w http.ResponseWriter, r *http.Request, supErr string, err error) (int, error) {
  543. code := 0
  544. defaultErr := fmt.Errorf("%s: %v", supErr, err)
  545. rsrcErr, ok := err.(*feed.Error)
  546. if !ok && rsrcErr != nil {
  547. code = rsrcErr.Code()
  548. }
  549. switch code {
  550. case storage.ErrInvalidValue:
  551. return http.StatusBadRequest, defaultErr
  552. case storage.ErrNotFound, storage.ErrNotSynced, storage.ErrNothingToReturn, storage.ErrInit:
  553. return http.StatusNotFound, defaultErr
  554. case storage.ErrUnauthorized, storage.ErrInvalidSignature:
  555. return http.StatusUnauthorized, defaultErr
  556. case storage.ErrDataOverflow:
  557. return http.StatusRequestEntityTooLarge, defaultErr
  558. }
  559. return http.StatusInternalServerError, defaultErr
  560. }
  561. // HandleGet handles a GET request to
  562. // - bzz-raw://<key> and responds with the raw content stored at the
  563. // given storage key
  564. // - bzz-hash://<key> and responds with the hash of the content stored
  565. // at the given storage key as a text/plain response
  566. func (s *Server) HandleGet(w http.ResponseWriter, r *http.Request) {
  567. ruid := GetRUID(r.Context())
  568. uri := GetURI(r.Context())
  569. log.Debug("handle.get", "ruid", ruid, "uri", uri)
  570. getCount.Inc(1)
  571. _, pass, _ := r.BasicAuth()
  572. addr, err := s.api.ResolveURI(r.Context(), uri, pass)
  573. if err != nil {
  574. getFail.Inc(1)
  575. RespondError(w, r, fmt.Sprintf("cannot resolve %s: %s", uri.Addr, err), http.StatusNotFound)
  576. return
  577. }
  578. w.Header().Set("Cache-Control", "max-age=2147483648, immutable") // url was of type bzz://<hex key>/path, so we are sure it is immutable.
  579. log.Debug("handle.get: resolved", "ruid", ruid, "key", addr)
  580. // if path is set, interpret <key> as a manifest and return the
  581. // raw entry at the given path
  582. etag := common.Bytes2Hex(addr)
  583. noneMatchEtag := r.Header.Get("If-None-Match")
  584. w.Header().Set("ETag", fmt.Sprintf("%q", etag)) // set etag to manifest key or raw entry key.
  585. if noneMatchEtag != "" {
  586. if bytes.Equal(storage.Address(common.Hex2Bytes(noneMatchEtag)), addr) {
  587. w.WriteHeader(http.StatusNotModified)
  588. return
  589. }
  590. }
  591. // check the root chunk exists by retrieving the file's size
  592. reader, isEncrypted := s.api.Retrieve(r.Context(), addr)
  593. if _, err := reader.Size(r.Context(), nil); err != nil {
  594. getFail.Inc(1)
  595. RespondError(w, r, fmt.Sprintf("root chunk not found %s: %s", addr, err), http.StatusNotFound)
  596. return
  597. }
  598. w.Header().Set("X-Decrypted", fmt.Sprintf("%v", isEncrypted))
  599. switch {
  600. case uri.Raw():
  601. // allow the request to overwrite the content type using a query
  602. // parameter
  603. if typ := r.URL.Query().Get("content_type"); typ != "" {
  604. w.Header().Set("Content-Type", typ)
  605. }
  606. http.ServeContent(w, r, "", time.Now(), reader)
  607. case uri.Hash():
  608. w.Header().Set("Content-Type", "text/plain")
  609. w.WriteHeader(http.StatusOK)
  610. fmt.Fprint(w, addr)
  611. }
  612. }
  613. // HandleGetList handles a GET request to bzz-list:/<manifest>/<path> and returns
  614. // a list of all files contained in <manifest> under <path> grouped into
  615. // common prefixes using "/" as a delimiter
  616. func (s *Server) HandleGetList(w http.ResponseWriter, r *http.Request) {
  617. ruid := GetRUID(r.Context())
  618. uri := GetURI(r.Context())
  619. _, credentials, _ := r.BasicAuth()
  620. log.Debug("handle.get.list", "ruid", ruid, "uri", uri)
  621. getListCount.Inc(1)
  622. // ensure the root path has a trailing slash so that relative URLs work
  623. if uri.Path == "" && !strings.HasSuffix(r.URL.Path, "/") {
  624. http.Redirect(w, r, r.URL.Path+"/", http.StatusMovedPermanently)
  625. return
  626. }
  627. addr, err := s.api.Resolve(r.Context(), uri.Addr)
  628. if err != nil {
  629. getListFail.Inc(1)
  630. RespondError(w, r, fmt.Sprintf("cannot resolve %s: %s", uri.Addr, err), http.StatusNotFound)
  631. return
  632. }
  633. log.Debug("handle.get.list: resolved", "ruid", ruid, "key", addr)
  634. list, err := s.api.GetManifestList(r.Context(), s.api.Decryptor(r.Context(), credentials), addr, uri.Path)
  635. if err != nil {
  636. getListFail.Inc(1)
  637. if isDecryptError(err) {
  638. w.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=%q", addr.String()))
  639. RespondError(w, r, err.Error(), http.StatusUnauthorized)
  640. return
  641. }
  642. RespondError(w, r, err.Error(), http.StatusInternalServerError)
  643. return
  644. }
  645. // if the client wants HTML (e.g. a browser) then render the list as a
  646. // HTML index with relative URLs
  647. if strings.Contains(r.Header.Get("Accept"), "text/html") {
  648. w.Header().Set("Content-Type", "text/html")
  649. err := TemplatesMap["bzz-list"].Execute(w, &htmlListData{
  650. URI: &api.URI{
  651. Scheme: "bzz",
  652. Addr: uri.Addr,
  653. Path: uri.Path,
  654. },
  655. List: &list,
  656. })
  657. if err != nil {
  658. getListFail.Inc(1)
  659. log.Error(fmt.Sprintf("error rendering list HTML: %s", err))
  660. }
  661. return
  662. }
  663. w.Header().Set("Content-Type", "application/json")
  664. json.NewEncoder(w).Encode(&list)
  665. }
  666. // HandleGetFile handles a GET request to bzz://<manifest>/<path> and responds
  667. // with the content of the file at <path> from the given <manifest>
  668. func (s *Server) HandleGetFile(w http.ResponseWriter, r *http.Request) {
  669. ruid := GetRUID(r.Context())
  670. uri := GetURI(r.Context())
  671. _, credentials, _ := r.BasicAuth()
  672. log.Debug("handle.get.file", "ruid", ruid, "uri", r.RequestURI)
  673. getFileCount.Inc(1)
  674. // ensure the root path has a trailing slash so that relative URLs work
  675. if uri.Path == "" && !strings.HasSuffix(r.URL.Path, "/") {
  676. http.Redirect(w, r, r.URL.Path+"/", http.StatusMovedPermanently)
  677. return
  678. }
  679. var err error
  680. manifestAddr := uri.Address()
  681. if manifestAddr == nil {
  682. manifestAddr, err = s.api.Resolve(r.Context(), uri.Addr)
  683. if err != nil {
  684. getFileFail.Inc(1)
  685. RespondError(w, r, fmt.Sprintf("cannot resolve %s: %s", uri.Addr, err), http.StatusNotFound)
  686. return
  687. }
  688. } else {
  689. w.Header().Set("Cache-Control", "max-age=2147483648, immutable") // url was of type bzz://<hex key>/path, so we are sure it is immutable.
  690. }
  691. log.Debug("handle.get.file: resolved", "ruid", ruid, "key", manifestAddr)
  692. reader, contentType, status, contentKey, err := s.api.Get(r.Context(), s.api.Decryptor(r.Context(), credentials), manifestAddr, uri.Path)
  693. etag := common.Bytes2Hex(contentKey)
  694. noneMatchEtag := r.Header.Get("If-None-Match")
  695. w.Header().Set("ETag", fmt.Sprintf("%q", etag)) // set etag to actual content key.
  696. if noneMatchEtag != "" {
  697. if bytes.Equal(storage.Address(common.Hex2Bytes(noneMatchEtag)), contentKey) {
  698. w.WriteHeader(http.StatusNotModified)
  699. return
  700. }
  701. }
  702. if err != nil {
  703. if isDecryptError(err) {
  704. w.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=%q", manifestAddr))
  705. RespondError(w, r, err.Error(), http.StatusUnauthorized)
  706. return
  707. }
  708. switch status {
  709. case http.StatusNotFound:
  710. getFileNotFound.Inc(1)
  711. RespondError(w, r, err.Error(), http.StatusNotFound)
  712. default:
  713. getFileFail.Inc(1)
  714. RespondError(w, r, err.Error(), http.StatusInternalServerError)
  715. }
  716. return
  717. }
  718. //the request results in ambiguous files
  719. //e.g. /read with readme.md and readinglist.txt available in manifest
  720. if status == http.StatusMultipleChoices {
  721. list, err := s.api.GetManifestList(r.Context(), s.api.Decryptor(r.Context(), credentials), manifestAddr, uri.Path)
  722. if err != nil {
  723. getFileFail.Inc(1)
  724. if isDecryptError(err) {
  725. w.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=%q", manifestAddr))
  726. RespondError(w, r, err.Error(), http.StatusUnauthorized)
  727. return
  728. }
  729. RespondError(w, r, err.Error(), http.StatusInternalServerError)
  730. return
  731. }
  732. log.Debug(fmt.Sprintf("Multiple choices! --> %v", list), "ruid", ruid)
  733. //show a nice page links to available entries
  734. ShowMultipleChoices(w, r, list)
  735. return
  736. }
  737. // check the root chunk exists by retrieving the file's size
  738. if _, err := reader.Size(r.Context(), nil); err != nil {
  739. getFileNotFound.Inc(1)
  740. RespondError(w, r, fmt.Sprintf("file not found %s: %s", uri, err), http.StatusNotFound)
  741. return
  742. }
  743. if contentType != "" {
  744. w.Header().Set("Content-Type", contentType)
  745. }
  746. fileName := uri.Addr
  747. if found := path.Base(uri.Path); found != "" && found != "." && found != "/" {
  748. fileName = found
  749. }
  750. w.Header().Set("Content-Disposition", fmt.Sprintf("inline; filename=\"%s\"", fileName))
  751. http.ServeContent(w, r, fileName, time.Now(), newBufferedReadSeeker(reader, getFileBufferSize))
  752. }
  753. // The size of buffer used for bufio.Reader on LazyChunkReader passed to
  754. // http.ServeContent in HandleGetFile.
  755. // Warning: This value influences the number of chunk requests and chunker join goroutines
  756. // per file request.
  757. // Recommended value is 4 times the io.Copy default buffer value which is 32kB.
  758. const getFileBufferSize = 4 * 32 * 1024
  759. // bufferedReadSeeker wraps bufio.Reader to expose Seek method
  760. // from the provied io.ReadSeeker in newBufferedReadSeeker.
  761. type bufferedReadSeeker struct {
  762. r io.Reader
  763. s io.Seeker
  764. }
  765. // newBufferedReadSeeker creates a new instance of bufferedReadSeeker,
  766. // out of io.ReadSeeker. Argument `size` is the size of the read buffer.
  767. func newBufferedReadSeeker(readSeeker io.ReadSeeker, size int) bufferedReadSeeker {
  768. return bufferedReadSeeker{
  769. r: bufio.NewReaderSize(readSeeker, size),
  770. s: readSeeker,
  771. }
  772. }
  773. func (b bufferedReadSeeker) Read(p []byte) (n int, err error) {
  774. return b.r.Read(p)
  775. }
  776. func (b bufferedReadSeeker) Seek(offset int64, whence int) (int64, error) {
  777. return b.s.Seek(offset, whence)
  778. }
  779. type loggingResponseWriter struct {
  780. http.ResponseWriter
  781. statusCode int
  782. }
  783. func newLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
  784. return &loggingResponseWriter{w, http.StatusOK}
  785. }
  786. func (lrw *loggingResponseWriter) WriteHeader(code int) {
  787. lrw.statusCode = code
  788. lrw.ResponseWriter.WriteHeader(code)
  789. }
  790. func isDecryptError(err error) bool {
  791. return strings.Contains(err.Error(), api.ErrDecrypt.Error())
  792. }