server.go 32 KB

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