server.go 29 KB

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