main.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "net"
  7. "net/http"
  8. "os"
  9. "os/exec"
  10. "runtime"
  11. "strconv"
  12. "strings"
  13. "syscall"
  14. "time"
  15. config "codeberg.org/vnpower/pixivfe/v2/core/config"
  16. session "codeberg.org/vnpower/pixivfe/v2/core/session"
  17. "codeberg.org/vnpower/pixivfe/v2/core/kmutex"
  18. "codeberg.org/vnpower/pixivfe/v2/pages"
  19. "codeberg.org/vnpower/pixivfe/v2/serve"
  20. "github.com/goccy/go-json"
  21. "github.com/gofiber/fiber/v2"
  22. "github.com/gofiber/fiber/v2/middleware/cache"
  23. "github.com/gofiber/fiber/v2/middleware/compress"
  24. "github.com/gofiber/fiber/v2/middleware/limiter"
  25. "github.com/gofiber/fiber/v2/middleware/logger"
  26. "github.com/gofiber/fiber/v2/middleware/recover"
  27. "github.com/gofiber/fiber/v2/utils"
  28. "github.com/gofiber/template/jet/v2"
  29. )
  30. func CanRequestSkipLimiter(c *fiber.Ctx) bool {
  31. path := c.Path()
  32. return strings.HasPrefix(path, "/assets/") ||
  33. strings.HasPrefix(path, "/css/") ||
  34. strings.HasPrefix(path, "/js/") ||
  35. strings.HasPrefix(path, "/proxy/s.pximg.net/")
  36. }
  37. func CanRequestSkipLogger(c *fiber.Ctx) bool {
  38. path := c.Path()
  39. return CanRequestSkipLimiter(c) ||
  40. strings.HasPrefix(path, "/proxy/i.pximg.net/")
  41. }
  42. func main() {
  43. config.GlobalServerConfig.InitializeConfig()
  44. engine := jet.New("./views", ".jet.html")
  45. engine.AddFuncMap(serve.GetTemplateFunctions())
  46. if config.GlobalServerConfig.InDevelopment {
  47. engine.Reload(true)
  48. }
  49. // gofiber bug: no error even if the templates are invalid??? https://github.com/gofiber/template/issues/341
  50. err := engine.Load()
  51. if err != nil {
  52. panic(err)
  53. }
  54. server := fiber.New(fiber.Config{
  55. AppName: "PixivFE",
  56. DisableStartupMessage: true,
  57. Views: engine,
  58. Prefork: false,
  59. JSONEncoder: json.Marshal,
  60. JSONDecoder: json.Unmarshal,
  61. ViewsLayout: "layout",
  62. EnableTrustedProxyCheck: true,
  63. TrustedProxies: []string{"0.0.0.0/0"},
  64. ProxyHeader: fiber.HeaderXForwardedFor,
  65. ErrorHandler: func(c *fiber.Ctx, err error) error {
  66. log.Println(err)
  67. // Status code defaults to 500
  68. code := fiber.StatusInternalServerError
  69. // // Retrieve the custom status code if it's a *fiber.Error
  70. // var e *fiber.Error
  71. // if errors.As(err, &e) {
  72. // code = e.Code
  73. // }
  74. // Send custom error page
  75. err = c.Status(code).Render("pages/error", fiber.Map{"Title": "Error", "Error": err})
  76. if err != nil {
  77. return c.Status(fiber.StatusInternalServerError).SendString(fmt.Sprintf("Internal Server Error: %s", err))
  78. }
  79. return nil
  80. },
  81. })
  82. server.Use(func(c *fiber.Ctx) error {
  83. pageURL := c.BaseURL() + c.OriginalURL()
  84. c.Bind(fiber.Map{
  85. "BaseURL": c.BaseURL(),
  86. "OriginalURL": c.OriginalURL(),
  87. "PageURL": pageURL,
  88. })
  89. return c.Next()
  90. })
  91. if config.GlobalServerConfig.RequestLimit > 0 {
  92. keyedSleepingSpot := kmutex.New()
  93. server.Use(limiter.New(limiter.Config{
  94. Next: CanRequestSkipLimiter,
  95. Expiration: 30 * time.Second,
  96. Max: config.GlobalServerConfig.RequestLimit,
  97. LimiterMiddleware: limiter.SlidingWindow{},
  98. LimitReached: func(c *fiber.Ctx) error {
  99. // limit response throughput by pacing, since not every bot reads X-RateLimit-*
  100. // on limit reached, they just have to wait
  101. // the design of this means that if they send multiple requests when reaching rate limit, they will wait even longer (since `retryAfter` is calculated before anything has slept)
  102. retryAfter_s := c.GetRespHeader(fiber.HeaderRetryAfter)
  103. retryAfter, err := strconv.ParseUint(retryAfter_s, 10, 64)
  104. if err != nil {
  105. log.Panicf("response header 'RetryAfter' should be a number: %v", err)
  106. }
  107. requestIP := c.IP()
  108. refcount := keyedSleepingSpot.Lock(requestIP)
  109. defer keyedSleepingSpot.Unlock(requestIP)
  110. if refcount >= 4 { // on too much concurrent requests
  111. // todo: maybe blackhole `requestIP` here
  112. log.Println("Limit Reached (Hard)!", requestIP)
  113. // close the connection immediately
  114. _ = c.Context().Conn().Close()
  115. return nil
  116. }
  117. // sleeping
  118. // here, sleeping is not the best solution.
  119. // todo: close this connection when this IP reaches hard limit
  120. dur := time.Duration(retryAfter) * time.Second
  121. log.Println("Limit Reached (Soft)! Sleeping for ", dur)
  122. ctx, cancel := context.WithTimeout(c.Context(), dur)
  123. defer cancel()
  124. <-ctx.Done()
  125. return c.Next()
  126. },
  127. }))
  128. }
  129. server.Use(logger.New(
  130. logger.Config{
  131. Format: "${time} +${latency} ${ip} ${method} ${path} ${status} ${error} \n",
  132. Next: CanRequestSkipLogger,
  133. CustomTags: map[string]logger.LogFunc{
  134. // make latency always print in seconds
  135. logger.TagLatency: func(output logger.Buffer, c *fiber.Ctx, data *logger.Data, extraParam string) (int, error) {
  136. latency := data.Stop.Sub(data.Start).Seconds()
  137. return output.WriteString(fmt.Sprintf("%.6f", latency))
  138. },
  139. },
  140. },
  141. ))
  142. server.Use(compress.New(compress.Config{
  143. Level: compress.LevelBestSpeed, // 1
  144. }))
  145. if !config.GlobalServerConfig.InDevelopment {
  146. server.Use(cache.New(
  147. cache.Config{
  148. Next: func(c *fiber.Ctx) bool {
  149. resp_code := c.Response().StatusCode()
  150. if resp_code < 200 || resp_code >= 300 {
  151. return true
  152. }
  153. // Disable cache for settings page
  154. return strings.Contains(c.Path(), "/settings") || c.Path() == "/"
  155. },
  156. Expiration: 5 * time.Minute,
  157. CacheControl: true,
  158. KeyGenerator: func(c *fiber.Ctx) string {
  159. return utils.CopyString(c.OriginalURL())
  160. },
  161. },
  162. ))
  163. }
  164. // Global HTTP headers
  165. server.Use(func(c *fiber.Ctx) error {
  166. c.Set("X-Frame-Options", "DENY")
  167. // use this if need iframe: `X-Frame-Options: SAMEORIGIN`
  168. c.Set("X-Content-Type-Options", "nosniff")
  169. c.Set("Referrer-Policy", "no-referrer")
  170. c.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload")
  171. c.Set("Content-Security-Policy", fmt.Sprintf("base-uri 'self'; default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' %s; media-src 'self' %s; connect-src 'self'; form-action 'self'; frame-ancestors 'none';", session.GetImageProxyOrigin(c)))
  172. // use this if need iframe: `frame-ancestors 'self'`
  173. c.Set("Permissions-Policy", "accelerometer=(), ambient-light-sensor=(), battery=(), camera=(), display-capture=(), document-domain=(), encrypted-media=(), execution-while-not-rendered=(), execution-while-out-of-viewport=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), navigation-override=(), payment=(), publickey-credentials-get=(), screen-wake-lock=(), sync-xhr=(), usb=(), web-share=(), xr-spatial-tracking=()")
  174. return c.Next()
  175. })
  176. server.Static("/favicon.ico", "./views/assets/favicon.ico")
  177. server.Static("/robots.txt", "./views/assets/robots.txt")
  178. server.Static("/assets/", "./views/assets")
  179. server.Static("/css/", "./views/css")
  180. server.Static("/js/", "./views/js")
  181. server.Use(recover.New(recover.Config{EnableStackTrace: config.GlobalServerConfig.InDevelopment}))
  182. // Routes
  183. server.Get("/", pages.IndexPage)
  184. server.Get("/about", pages.AboutPage)
  185. server.Get("/newest", pages.NewestPage)
  186. server.Get("/discovery", pages.DiscoveryPage)
  187. server.Get("/discovery/novel", pages.NovelDiscoveryPage)
  188. server.Get("/ranking", pages.RankingPage)
  189. server.Get("/rankingCalendar", pages.RankingCalendarPage)
  190. server.Post("/rankingCalendar", pages.RankingCalendarPicker)
  191. server.Get("/users/:id.atom.xml", pages.UserAtomFeed)
  192. server.Get("/users/:id/:category?.atom.xml", pages.UserAtomFeed)
  193. server.Get("/users/:id/:category?", pages.UserPage)
  194. server.Get("/artworks/:id/", pages.ArtworkPage).Name("artworks")
  195. server.Get("/artworks/:id/embed", pages.ArtworkEmbedPage)
  196. server.Get("/artworks-multi/:ids/", pages.ArtworkMultiPage)
  197. server.Get("/novel/:id/", pages.NovelPage)
  198. // Settings group
  199. settings := server.Group("/settings")
  200. settings.Get("/", pages.SettingsPage)
  201. settings.Post("/:type", pages.SettingsPost)
  202. // Personal group
  203. self := server.Group("/self")
  204. self.Get("/", pages.LoginUserPage)
  205. self.Get("/followingWorks", pages.FollowingWorksPage)
  206. self.Get("/bookmarks", pages.LoginBookmarkPage)
  207. self.Post("/addBookmark/:id", pages.AddBookmarkRoute)
  208. self.Post("/deleteBookmark/:id", pages.DeleteBookmarkRoute)
  209. self.Post("/like/:id", pages.LikeRoute)
  210. server.Get("/tags/:name", pages.TagPage)
  211. server.Post("/tags/:name", pages.TagPage)
  212. server.Post("/tags",
  213. func(c *fiber.Ctx) error {
  214. name := c.FormValue("name")
  215. return c.Redirect("/tags/"+name, http.StatusFound)
  216. })
  217. // Legacy illust URL
  218. server.Get("/member_illust.php", func(c *fiber.Ctx) error {
  219. return c.Redirect("/artworks/" + c.Query("illust_id"))
  220. })
  221. // Proxy routes
  222. proxy := server.Group("/proxy")
  223. proxy.Get("/i.pximg.net/*", pages.IPximgProxy)
  224. proxy.Get("/s.pximg.net/*", pages.SPximgProxy)
  225. proxy.Get("/ugoira.com/*", pages.UgoiraProxy)
  226. // run sass when in development mode
  227. if config.GlobalServerConfig.InDevelopment {
  228. go func() {
  229. cmd := exec.Command("sass", "--watch", "views/css")
  230. cmd.Stdout = os.Stderr // Sass quirk
  231. cmd.Stderr = os.Stderr
  232. cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true, Pdeathsig: syscall.SIGHUP}
  233. runtime.LockOSThread() // Go quirk https://github.com/golang/go/issues/27505
  234. err := cmd.Run()
  235. if err != nil {
  236. log.Println(fmt.Errorf("when running sass: %w", err))
  237. }
  238. }()
  239. }
  240. // Listen
  241. if config.GlobalServerConfig.UnixSocket != "" {
  242. ln, err := net.Listen("unix", config.GlobalServerConfig.UnixSocket)
  243. if err != nil {
  244. panic(err)
  245. }
  246. log.Printf("Listening on domain socket %v\n", config.GlobalServerConfig.UnixSocket)
  247. err = server.Listener(ln)
  248. if err != nil {
  249. panic(err)
  250. }
  251. } else {
  252. addr := config.GlobalServerConfig.Host + ":" + config.GlobalServerConfig.Port
  253. ln, err := net.Listen(server.Config().Network, addr)
  254. if err != nil {
  255. log.Panicf("failed to listen: %v", err)
  256. }
  257. addr = ln.Addr().String()
  258. log.Printf("Listening on http://%v/\n", addr)
  259. err = server.Listener(ln)
  260. if err != nil {
  261. panic(err)
  262. }
  263. }
  264. }