main.go 10 KB

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