server.go 33 KB

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