app/router.go

v1.5.8
skunky-art/app/router.go history · blame · raw

241 lines · 6838 bytes · executable

  1package app
  2
  3import (
  4	"io"
  5	"net/http"
  6	url "net/url"
  7	"skunkyart/static"
  8	"strconv"
  9	"strings"
 10	"time"
 11)
 12
 13// Cache-Control values by route. Signed wixmp media never changes under its
 14// URL; avatars, emotes and static assets change rarely; pages and API JSON
 15// follow the API cache's default TTL so a reverse proxy can hold them too.
 16// Error responses drop the header (see ReturnHTTPError and friends) so a
 17// failure is never remembered.
 18const (
 19	cacheControlMedia  = "public, max-age=31536000, immutable"
 20	cacheControlAssets = "public, max-age=86400"
 21	cacheControlPage   = "public, max-age=300"
 22)
 23
 24// Router registers the single catch-all handler that dispatches every path, then
 25// serves until the process exits. It does not return on success.
 26func Router() {
 27	http.HandleFunc("/", Handler())
 28	println("SkunkyArt is listening on", CFG.Listen)
 29
 30	// Explicit timeouts: the bare http.ListenAndServe has none, so a slow client
 31	// can hold a connection (and its handler) open indefinitely. WriteTimeout is
 32	// generous because media proxying streams large files through a handler.
 33	srv := &http.Server{
 34		Addr:              CFG.Listen,
 35		ReadHeaderTimeout: 10 * time.Second,
 36		ReadTimeout:       30 * time.Second,
 37		WriteTimeout:      120 * time.Second,
 38		IdleTimeout:       120 * time.Second,
 39	}
 40	tryWithExitStatus(srv.ListenAndServe(), 1)
 41}
 42
 43// parsePath splits a request path below CFG.URI into its segments.
 44func parsePath(path string) map[int]string {
 45	if l := len(CFG.URI); len(path) > l {
 46		path = path[l-1:]
 47	} else {
 48		path = "/"
 49	}
 50
 51	parsedpath := make(map[int]string)
 52	for x := 0; true; x++ {
 53		slash := strings.Index(path, "/") + 1
 54		content := path[:slash]
 55		path = path[slash:]
 56		if slash == 0 {
 57			parsedpath[x] = path
 58			break
 59		}
 60		parsedpath[x] = content[:slash-1]
 61	}
 62	return parsedpath
 63}
 64
 65// joinPath rejoins the path segments from index from onward.
 66func joinPath(path map[int]string, from int) string {
 67	var out strings.Builder
 68	for x, l := from, len(path)-1; x <= l; x++ {
 69		out.WriteString(path[x])
 70		if x != l {
 71			out.WriteString("/")
 72		}
 73	}
 74	return out.String()
 75}
 76
 77// openStatic reads an embedded static file.
 78func openStatic(name string) []byte {
 79	file, err := static.Templates.Open(name)
 80	if err != nil {
 81		try(err)
 82		return nil
 83	}
 84	defer func() { try(file.Close()) }()
 85
 86	fileReaded, err := io.ReadAll(file)
 87	if err != nil {
 88		try(err)
 89		return nil
 90	}
 91	return fileReaded
 92}
 93
 94// Handler returns the single catch-all handler that dispatches every path.
 95func Handler() http.HandlerFunc {
 96	// the function that drives everything
 97	return func(w http.ResponseWriter, r *http.Request) {
 98		path := parsePath(r.URL.Path)
 99		skunky := newSkunkyart(w, r, path[1])
100		skunky.API.main = &skunky
101		setPageHeaders(w)
102
103		if daLimiter != nil && limited(skunky.Endpoint) && !daLimiter.allow(clientAddr(r)) {
104			w.Header().Set("Retry-After", "60")
105			skunky.ReturnHTTPError(http.StatusTooManyRequests)
106			return
107		}
108		dispatch(&skunky, w, path)
109	}
110}
111
112// newSkunkyart builds the per-request state.
113func newSkunkyart(w http.ResponseWriter, r *http.Request, endpoint string) skunkyart {
114	// Per-request, not a package global: requests arrive concurrently on
115	// different hosts and ports (bots hitting a proxy's alternate ports, for
116	// one), and a shared global lets one request's host leak into another's
117	// rendered URLs. Those URLs then point at a different origin, which this
118	// handler's own default-src 'self' CSP blocks.
119	host := "http://" + r.Host
120	if h := r.Header["X-Forwarded-Proto"]; len(h) != 0 && h[0] == "https" {
121		host = "https://" + r.Host
122	}
123
124	var skunky = skunkyart{Version: Release.Version, Host: host}
125	skunky._pth = r.URL.Path
126
127	skunky.Args = r.URL.Query()
128	arg := skunky.Args.Get
129	p, _ := strconv.Atoi(arg("p"))
130
131	skunky.Endpoint = endpoint
132	skunky.Writer = w
133	skunky.BasePath = CFG.URI
134	skunky.Lang = ResolveLang(r.Header.Get("Accept-Language"))
135	skunky.QueryRaw = arg("q")
136	skunky.Query = url.QueryEscape(skunky.QueryRaw)
137	skunky.Page = p
138
139	if t := arg("type"); len(t) > 0 {
140		skunky.Type = rune(t[0])
141	}
142
143	if arg("atom") == "true" {
144		skunky.Atom = true
145	}
146	return skunky
147}
148
149func setPageHeaders(w http.ResponseWriter) {
150	if CFG.Proxy {
151		w.Header().Add("Content-Security-Policy", "default-src 'self'; script-src 'none'; style-src 'self' 'unsafe-inline'")
152	} else {
153		w.Header().Add("Content-Security-Policy", "default-src 'self'; img-src 'self' *.wixmp.com; script-src 'none'; style-src 'self' 'unsafe-inline'")
154	}
155
156	w.Header().Add("X-Frame-Options", "DENY")
157	w.Header().Set("Cache-Control", cacheControlPage)
158}
159
160// dispatch routes a request to the page, media, asset, or API handler for its endpoint.
161func dispatch(skunky *skunkyart, w http.ResponseWriter, path map[int]string) {
162	switch skunky.Endpoint {
163	// main
164	case "":
165		skunky.ExecuteTemplate("index.htm", "html", skunky)
166	case "about":
167		skunky.Templates.About = About
168		skunky.ExecuteTemplate("about.htm", "html", skunky)
169	case "post":
170		skunky.Deviation(path[2], path[3])
171	case "search":
172		skunky.Search()
173	case "dd":
174		skunky.DD()
175	case "group_user":
176		skunky.GRUser()
177	case "media":
178		serveMedia(skunky, w, path)
179	case "stylesheet", "favicon.ico", "robots.txt":
180		serveAsset(skunky.Endpoint, w)
181	case "api":
182		w.Header().Add("Content-Type", "application/json")
183		serveAPI(skunky, path)
184
185	// 404
186	default:
187		skunky.ReturnHTTPError(404)
188	}
189}
190
191func serveMedia(skunky *skunkyart, w http.ResponseWriter, path map[int]string) {
192	switch path[2] {
193	case "file":
194		if a := skunky.Args.Get("filename"); a != "" {
195			skunky.SetFilename(a)
196		}
197		w.Header().Set("Cache-Control", cacheControlMedia)
198		skunky.DownloadAndSendMedia(path[3], joinPath(path, 4))
199	case "emojitar":
200		w.Header().Set("Cache-Control", cacheControlAssets)
201		skunky.Emojitar(path[3])
202	default:
203		skunky.ReturnHTTPError(404)
204	}
205}
206
207func serveAsset(endpoint string, w http.ResponseWriter) {
208	w.Header().Set("Cache-Control", cacheControlAssets)
209	switch endpoint {
210	case "stylesheet":
211		w.Header().Add("Content-Type", "text/css")
212		_, _ = w.Write(openStatic("css/skunky.css"))
213		// "auto" is the stylesheet as written: dark, with a light palette
214		// behind prefers-color-scheme. Forcing a theme means re-declaring
215		// that palette unconditionally, which outranks the media query
216		// because it comes later with equal specificity.
217		if css := forcedThemeCSS(); css != "" {
218			_, _ = w.Write([]byte(css))
219		}
220	case "favicon.ico":
221		_, _ = w.Write(openStatic("images/logo.png"))
222	case "robots.txt":
223		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
224		wr(w, robotsTXT(CFG.URI))
225	}
226}
227
228func serveAPI(skunky *skunkyart, path map[int]string) {
229	switch path[2] {
230	case "instance":
231		skunky.API.Info()
232	case "random":
233		skunky.API.Random()
234	case "search":
235		skunky.API.Search()
236	case "post":
237		skunky.API.Post(path[3], path[4])
238	default:
239		skunky.API.Error("Not Found", 404)
240	}
241}