server.go 29 KB

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