1
0

server.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. // Package web is the server behind the converter form on
  2. // rekopub.monoexp.com. It checks the address a visitor enters, runs the
  3. // rekopub command on it and serves the finished books for a limited time.
  4. //
  5. // The site is open to everyone, so conversions are limited: in total and
  6. // per visitor within a time window, by how many run at once, and by how much
  7. // disk the kept books may use. nginx serves the rest of the site and passes
  8. // /api/ and /books/ to this server.
  9. package web
  10. import (
  11. "context"
  12. "crypto/rand"
  13. "embed"
  14. "encoding/hex"
  15. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "html/template"
  19. "io/fs"
  20. "log"
  21. "net"
  22. "net/http"
  23. "net/netip"
  24. "net/url"
  25. "os"
  26. "path/filepath"
  27. "regexp"
  28. "strings"
  29. "sync"
  30. "sync/atomic"
  31. "time"
  32. "unicode"
  33. "git.monoexp.com/bajdev/rekopub/internal/fetch"
  34. )
  35. // Config holds the server's settings. New fills in defaults for zero values
  36. // where noted.
  37. type Config struct {
  38. CLI string // path of the rekopub command (required)
  39. Dir string // books are kept here, one folder per conversion (required)
  40. Keep time.Duration // how long books are kept (24h)
  41. Limit int // conversions allowed for all visitors together... (50)
  42. Window time.Duration // ...and per visitor, within this period (15m)
  43. PerVisitor int // conversions allowed per visitor (10)
  44. MaxRunning int // conversions running at the same time (2)
  45. MaxWaiting int // conversions waiting for a free slot (10)
  46. Wait time.Duration // how long a conversion may wait for a slot (60s)
  47. RunTimeout time.Duration // how long one run of the command may take (2m)
  48. MaxStorage int64 // bytes of kept books before conversions pause (2 GB)
  49. }
  50. // Formats a visitor can choose, and the command's flags for each book.
  51. var formats = map[string][]struct {
  52. name string
  53. kepub bool
  54. }{
  55. "epub": {{"EPUB", false}},
  56. "kepub": {{"KEPUB", true}},
  57. "both": {{"EPUB", false}, {"KEPUB", true}},
  58. }
  59. const (
  60. maxURLLen = 2000
  61. maxBodyLen = 8 << 10
  62. )
  63. var (
  64. idPattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
  65. bookPattern = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*(\.kepub)?\.epub$`)
  66. )
  67. // Server handles the converter's requests.
  68. type Server struct {
  69. cfg Config
  70. root *os.Root
  71. run runFunc
  72. now func() time.Time
  73. isLocal func(ctx context.Context, host string) bool
  74. mu sync.Mutex
  75. all window
  76. visitor map[string]*window
  77. slots chan struct{}
  78. waiting atomic.Int32
  79. stored atomic.Int64 // bytes of kept books
  80. }
  81. // New returns a server for cfg. It creates cfg.Dir if needed.
  82. func New(cfg Config) (*Server, error) {
  83. if cfg.CLI == "" || cfg.Dir == "" {
  84. return nil, errors.New("web: CLI and Dir are required")
  85. }
  86. def := func(v *time.Duration, d time.Duration) {
  87. if *v <= 0 {
  88. *v = d
  89. }
  90. }
  91. defInt := func(v *int, d int) {
  92. if *v <= 0 {
  93. *v = d
  94. }
  95. }
  96. def(&cfg.Keep, 24*time.Hour)
  97. def(&cfg.Window, 15*time.Minute)
  98. def(&cfg.Wait, time.Minute)
  99. def(&cfg.RunTimeout, 2*time.Minute)
  100. defInt(&cfg.Limit, 50)
  101. defInt(&cfg.PerVisitor, 10)
  102. defInt(&cfg.MaxRunning, 2)
  103. defInt(&cfg.MaxWaiting, 10)
  104. if cfg.MaxStorage <= 0 {
  105. cfg.MaxStorage = 2 << 30
  106. }
  107. // The command prints the absolute path of each book it saves.
  108. dir, err := filepath.Abs(cfg.Dir)
  109. if err != nil {
  110. return nil, err
  111. }
  112. cfg.Dir = dir
  113. if err := os.MkdirAll(cfg.Dir, 0o750); err != nil {
  114. return nil, err
  115. }
  116. root, err := os.OpenRoot(cfg.Dir)
  117. if err != nil {
  118. return nil, err
  119. }
  120. return &Server{
  121. cfg: cfg,
  122. root: root,
  123. run: execRunner(cfg.CLI),
  124. now: time.Now,
  125. isLocal: fetch.IsLocal,
  126. visitor: map[string]*window{},
  127. slots: make(chan struct{}, cfg.MaxRunning),
  128. }, nil
  129. }
  130. // Handler returns the server's routes. Cross-origin form posts are refused,
  131. // so other sites can't use the converter through their visitors' browsers.
  132. func (s *Server) Handler() http.Handler {
  133. mux := http.NewServeMux()
  134. mux.HandleFunc("GET /api/status", s.status)
  135. mux.HandleFunc("POST /api/convert", s.convert)
  136. mux.HandleFunc("GET /books/{id}/{name}", s.book)
  137. return http.NewCrossOriginProtection().Handler(headers(mux))
  138. }
  139. // headers sets security headers on every response.
  140. func headers(next http.Handler) http.Handler {
  141. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  142. h := w.Header()
  143. h.Set("X-Content-Type-Options", "nosniff")
  144. h.Set("Referrer-Policy", "no-referrer")
  145. h.Set("X-Robots-Tag", "noindex")
  146. h.Set("Content-Security-Policy", "default-src 'none'; style-src 'self'; img-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'")
  147. next.ServeHTTP(w, r)
  148. })
  149. }
  150. // file is a finished book in a reply.
  151. type file struct {
  152. Format string `json:"format"`
  153. Name string `json:"name"`
  154. URL string `json:"url"`
  155. Size int64 `json:"size"`
  156. }
  157. // reply is the answer to a status or convert request.
  158. type reply struct {
  159. Title string `json:"-"` // heading of the HTML page, if not the default
  160. Paused bool `json:"paused,omitempty"`
  161. Error string `json:"error,omitempty"`
  162. Warning string `json:"warning,omitempty"`
  163. Files []file `json:"files,omitempty"`
  164. KeepHours int `json:"keepHours"`
  165. }
  166. func (s *Server) keepHours() int { return int(s.cfg.Keep.Hours()) }
  167. // status tells the page whether the form can be used right now.
  168. func (s *Server) status(w http.ResponseWriter, r *http.Request) {
  169. rep := reply{KeepHours: s.keepHours()}
  170. if msg := s.pausedFor(visitorKey(r)); msg != "" {
  171. rep.Paused, rep.Error = true, msg
  172. }
  173. w.Header().Set("Cache-Control", "no-store")
  174. writeJSON(w, http.StatusOK, rep)
  175. }
  176. // convert checks the form, waits for a free slot and runs the command once
  177. // per chosen format.
  178. func (s *Server) convert(w http.ResponseWriter, r *http.Request) {
  179. r.Body = http.MaxBytesReader(w, r.Body, maxBodyLen)
  180. if err := r.ParseForm(); err != nil {
  181. s.respond(w, r, http.StatusBadRequest, reply{Error: "The form couldn't be read."})
  182. return
  183. }
  184. format := r.PostForm.Get("format")
  185. if format == "" {
  186. format = "epub"
  187. }
  188. books, ok := formats[format]
  189. if !ok {
  190. s.respond(w, r, http.StatusBadRequest, reply{Error: "Choose EPUB, KEPUB or both."})
  191. return
  192. }
  193. u, msg := checkURL(r.PostForm.Get("url"))
  194. if msg != "" {
  195. s.respond(w, r, http.StatusBadRequest, reply{Error: msg})
  196. return
  197. }
  198. // The command refuses local addresses anyway (-NOLOCAL); checking here
  199. // too gives a clear message and doesn't use up a conversion.
  200. if s.isLocal(r.Context(), u.Hostname()) {
  201. s.respond(w, r, http.StatusBadRequest, reply{Error: "That address is on a local or private network, which this site doesn't connect to."})
  202. return
  203. }
  204. key := visitorKey(r)
  205. undo, msg := s.reserve(key)
  206. if msg != "" {
  207. log.Printf("limited %s: %s", key, msg)
  208. s.respond(w, r, http.StatusTooManyRequests, reply{Paused: true, Error: msg})
  209. return
  210. }
  211. release, msg := s.acquire(r.Context())
  212. if msg != "" {
  213. undo()
  214. s.respond(w, r, http.StatusServiceUnavailable, reply{Error: msg})
  215. return
  216. }
  217. defer release()
  218. start := s.now()
  219. rep, code := s.convertAll(r.Context(), u, books)
  220. if rep.Error != "" {
  221. log.Printf("convert %s %s: failed in %s: %s", u.Hostname(), format, s.now().Sub(start).Round(time.Millisecond), rep.Error)
  222. } else {
  223. log.Printf("convert %s %s: ok in %s", u.Hostname(), format, s.now().Sub(start).Round(time.Millisecond))
  224. }
  225. s.respond(w, r, code, rep)
  226. }
  227. // convertAll converts u into each of books, in a new folder.
  228. func (s *Server) convertAll(ctx context.Context, u *url.URL, books []struct {
  229. name string
  230. kepub bool
  231. }) (reply, int) {
  232. rep := reply{KeepHours: s.keepHours()}
  233. id := newID()
  234. dir := filepath.Join(s.cfg.Dir, id)
  235. if err := s.root.Mkdir(id, 0o750); err != nil {
  236. log.Printf("creating %s: %v", dir, err)
  237. rep.Error = "Something went wrong while converting that page."
  238. return rep, http.StatusInternalServerError
  239. }
  240. for _, b := range books {
  241. f, msg := s.runOnce(ctx, u, dir, b.kepub)
  242. if msg != "" {
  243. if len(rep.Files) > 0 {
  244. // The first book is fine; offer it and say what's missing.
  245. rep.Warning = fmt.Sprintf("The %s couldn't be made: %s", b.name, msg)
  246. break
  247. }
  248. s.root.RemoveAll(id)
  249. rep.Error = msg
  250. return rep, http.StatusUnprocessableEntity
  251. }
  252. f.Format = b.name
  253. f.URL = "/books/" + id + "/" + f.Name
  254. rep.Files = append(rep.Files, f)
  255. s.stored.Add(f.Size)
  256. }
  257. return rep, http.StatusOK
  258. }
  259. // runOnce runs the command for one book and checks what it wrote.
  260. func (s *Server) runOnce(ctx context.Context, u *url.URL, dir string, kepub bool) (file, string) {
  261. ctx, cancel := context.WithTimeout(ctx, s.cfg.RunTimeout)
  262. defer cancel()
  263. // "-FLAG=value" keeps a value from ever being read as a flag.
  264. args := []string{"-NOLOCAL", "-URL=" + u.String(), "-SAVE=" + dir + string(filepath.Separator)}
  265. if kepub {
  266. args = append(args, "-KEPUB")
  267. }
  268. res := s.run(ctx, args)
  269. if res.Code != 0 {
  270. return file{}, explain(ctx, res)
  271. }
  272. name := filepath.Base(res.Path)
  273. if filepath.Dir(res.Path) != dir || !bookPattern.MatchString(name) {
  274. log.Printf("unexpected output path %q", res.Path)
  275. return file{}, "Something went wrong while converting that page."
  276. }
  277. info, err := os.Stat(res.Path)
  278. if err != nil {
  279. log.Printf("checking output: %v", err)
  280. return file{}, "Something went wrong while converting that page."
  281. }
  282. return file{Name: name, Size: info.Size()}, ""
  283. }
  284. // reserve counts a conversion against the limits, or says why it can't
  285. // start. undo takes the conversion back if it never runs.
  286. func (s *Server) reserve(key string) (undo func(), msg string) {
  287. s.mu.Lock()
  288. defer s.mu.Unlock()
  289. now := s.now()
  290. if msg := s.pausedLocked(key, now); msg != "" {
  291. return nil, msg
  292. }
  293. v := s.visitor[key]
  294. if v == nil {
  295. v = &window{}
  296. s.visitor[key] = v
  297. }
  298. s.all = append(s.all, now)
  299. *v = append(*v, now)
  300. return func() {
  301. s.mu.Lock()
  302. defer s.mu.Unlock()
  303. s.all.remove(now)
  304. v.remove(now)
  305. }, ""
  306. }
  307. // pausedFor returns why a visitor can't convert right now, or "".
  308. func (s *Server) pausedFor(key string) string {
  309. s.mu.Lock()
  310. defer s.mu.Unlock()
  311. return s.pausedLocked(key, s.now())
  312. }
  313. func (s *Server) pausedLocked(key string, now time.Time) string {
  314. if s.stored.Load() >= s.cfg.MaxStorage {
  315. return "Conversions are temporarily paused. Please try again in an hour."
  316. }
  317. s.all.prune(now, s.cfg.Window)
  318. if full, until := s.all.full(now, s.cfg.Limit, s.cfg.Window); full {
  319. return "Conversions are temporarily paused. Please try again in " + minutes(until.Sub(now)) + "."
  320. }
  321. if v := s.visitor[key]; v != nil {
  322. v.prune(now, s.cfg.Window)
  323. if full, until := v.full(now, s.cfg.PerVisitor, s.cfg.Window); full {
  324. return fmt.Sprintf("You've made %d conversions in the last %s. Please try again in %s.",
  325. s.cfg.PerVisitor, minutes(s.cfg.Window), minutes(until.Sub(now)))
  326. }
  327. }
  328. return ""
  329. }
  330. // acquire waits for a free slot. It gives up when too many conversions are
  331. // already waiting, after cfg.Wait, or when the visitor leaves.
  332. func (s *Server) acquire(ctx context.Context) (release func(), msg string) {
  333. const busy = "The converter is busy. Please try again in a minute."
  334. if s.waiting.Add(1) > int32(s.cfg.MaxWaiting) {
  335. s.waiting.Add(-1)
  336. return nil, busy
  337. }
  338. defer s.waiting.Add(-1)
  339. timer := time.NewTimer(s.cfg.Wait)
  340. defer timer.Stop()
  341. select {
  342. case s.slots <- struct{}{}:
  343. return func() { <-s.slots }, ""
  344. case <-timer.C:
  345. return nil, busy
  346. case <-ctx.Done():
  347. return nil, busy
  348. }
  349. }
  350. // book serves a finished book as a download.
  351. func (s *Server) book(w http.ResponseWriter, r *http.Request) {
  352. id, name := r.PathValue("id"), r.PathValue("name")
  353. gone := func() {
  354. s.respond(w, r, http.StatusNotFound, reply{Title: "Link expired", Error: fmt.Sprintf(
  355. "This download link has expired or doesn't exist. Links work for %d hours after a conversion.", s.keepHours())})
  356. }
  357. if !idPattern.MatchString(id) || !bookPattern.MatchString(name) {
  358. gone()
  359. return
  360. }
  361. // os.Root keeps the open inside cfg.Dir, whatever the path holds.
  362. f, err := s.root.Open(id + "/" + name)
  363. if err != nil {
  364. gone()
  365. return
  366. }
  367. defer f.Close()
  368. info, err := f.Stat()
  369. if err != nil || !info.Mode().IsRegular() || s.now().Sub(info.ModTime()) >= s.cfg.Keep {
  370. gone()
  371. return
  372. }
  373. h := w.Header()
  374. h.Set("Content-Type", "application/epub+zip")
  375. h.Set("Content-Disposition", `attachment; filename="`+name+`"`)
  376. h.Set("Cache-Control", "private, max-age=3600")
  377. http.ServeContent(w, r, name, info.ModTime(), f)
  378. }
  379. // Clean deletes books older than cfg.Keep, adds up what's left and forgets
  380. // visitors with no recent conversions. Run it at start-up and then
  381. // regularly.
  382. func (s *Server) Clean() {
  383. now := s.now()
  384. entries, err := fs.ReadDir(s.root.FS(), ".")
  385. if err != nil {
  386. log.Printf("clean: %v", err)
  387. return
  388. }
  389. var total int64
  390. removed := 0
  391. for _, e := range entries {
  392. info, err := e.Info()
  393. if err != nil || !e.IsDir() || !idPattern.MatchString(e.Name()) {
  394. continue
  395. }
  396. if now.Sub(info.ModTime()) >= s.cfg.Keep {
  397. if err := s.root.RemoveAll(e.Name()); err != nil {
  398. log.Printf("clean: %v", err)
  399. } else {
  400. removed++
  401. }
  402. continue
  403. }
  404. fs.WalkDir(s.root.FS(), e.Name(), func(_ string, d fs.DirEntry, err error) error {
  405. if err == nil && d.Type().IsRegular() {
  406. if fi, err := d.Info(); err == nil {
  407. total += fi.Size()
  408. }
  409. }
  410. return nil
  411. })
  412. }
  413. s.stored.Store(total)
  414. if removed > 0 {
  415. log.Printf("clean: removed %d expired conversions; %d MB kept", removed, total>>20)
  416. }
  417. s.mu.Lock()
  418. defer s.mu.Unlock()
  419. for key, v := range s.visitor {
  420. if v.prune(now, s.cfg.Window); len(*v) == 0 {
  421. delete(s.visitor, key)
  422. }
  423. }
  424. }
  425. // CleanEvery runs Clean every interval until ctx ends.
  426. func (s *Server) CleanEvery(ctx context.Context, interval time.Duration) {
  427. s.Clean()
  428. t := time.NewTicker(interval)
  429. defer t.Stop()
  430. for {
  431. select {
  432. case <-ctx.Done():
  433. return
  434. case <-t.C:
  435. s.Clean()
  436. }
  437. }
  438. }
  439. // checkURL checks a visitor's address, returning it or a message saying
  440. // what's wrong.
  441. func checkURL(raw string) (*url.URL, string) {
  442. raw = strings.TrimSpace(raw)
  443. switch {
  444. case raw == "":
  445. return nil, "Enter the address of a web page."
  446. case len(raw) > maxURLLen:
  447. return nil, "That address is too long."
  448. case strings.ContainsFunc(raw, unicode.IsControl):
  449. return nil, "That isn't a valid web address."
  450. }
  451. u, err := url.Parse(raw)
  452. if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.Opaque != "" {
  453. return nil, "Enter a full web address starting with http:// or https://."
  454. }
  455. if u.User != nil {
  456. return nil, "Addresses with a user name or password can't be converted."
  457. }
  458. // Other ports would let visitors use the server to probe other
  459. // people's machines.
  460. if p := u.Port(); p != "" && p != "80" && p != "443" {
  461. return nil, "Only addresses on the standard web ports can be converted."
  462. }
  463. u.Fragment, u.RawFragment = "", ""
  464. return u, ""
  465. }
  466. // visitorKey identifies a visitor for the per-visitor limit: their IPv4
  467. // address, or the /64 network of an IPv6 address, since one IPv6
  468. // connection usually has a whole /64 to choose from. The server listens on
  469. // 127.0.0.1 behind nginx, which sets X-Real-IP; any value the visitor sent
  470. // is replaced.
  471. func visitorKey(r *http.Request) string {
  472. raw := r.Header.Get("X-Real-IP")
  473. if raw == "" {
  474. raw, _, _ = net.SplitHostPort(r.RemoteAddr)
  475. }
  476. ip, err := netip.ParseAddr(raw)
  477. if err != nil {
  478. return raw
  479. }
  480. ip = ip.Unmap()
  481. if ip.Is6() {
  482. p, _ := ip.Prefix(64)
  483. return p.String()
  484. }
  485. return ip.String()
  486. }
  487. func newID() string {
  488. b := make([]byte, 16)
  489. rand.Read(b)
  490. return hex.EncodeToString(b)
  491. }
  492. // respond answers in JSON for the page's script and as a page for a
  493. // browser without JavaScript.
  494. func (s *Server) respond(w http.ResponseWriter, r *http.Request, code int, rep reply) {
  495. rep.KeepHours = s.keepHours()
  496. if strings.Contains(r.Header.Get("Accept"), "application/json") {
  497. writeJSON(w, code, rep)
  498. return
  499. }
  500. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  501. w.WriteHeader(code)
  502. if err := pages.ExecuteTemplate(w, "result.html", rep); err != nil {
  503. log.Printf("result page: %v", err)
  504. }
  505. }
  506. func writeJSON(w http.ResponseWriter, code int, v any) {
  507. w.Header().Set("Content-Type", "application/json")
  508. w.WriteHeader(code)
  509. json.NewEncoder(w).Encode(v)
  510. }
  511. //go:embed templates
  512. var templateFS embed.FS
  513. var pages = template.Must(template.New("").Funcs(template.FuncMap{
  514. "kb": func(n int64) string { return fmt.Sprintf("%d KB", (n+1023)/1024) },
  515. }).ParseFS(templateFS, "templates/*.html"))