server.go 32 KB

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