server.go 30 KB

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