262 lines
5.3 KiB
Go
262 lines
5.3 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/hmac"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"image"
|
|
"image/color"
|
|
"image/png"
|
|
"log/slog"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"unicode"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
type tileRef struct {
|
|
table string
|
|
z, x, y string
|
|
}
|
|
|
|
func transparentPNG() []byte {
|
|
img := image.NewPaletted(image.Rect(0, 0, 256, 256), color.Palette{color.NRGBA{}})
|
|
var buf bytes.Buffer
|
|
enc := png.Encoder{CompressionLevel: png.BestCompression}
|
|
if err := enc.Encode(&buf, img); err != nil {
|
|
panic(err)
|
|
}
|
|
return buf.Bytes()
|
|
}
|
|
|
|
func clientIP(r *http.Request, trustProxy bool) string {
|
|
var ip net.IP
|
|
if trustProxy {
|
|
ip = net.ParseIP(strings.TrimSpace(r.Header.Get("X-Real-IP")))
|
|
}
|
|
if ip == nil {
|
|
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
|
if err != nil {
|
|
host = r.RemoteAddr
|
|
}
|
|
ip = net.ParseIP(host)
|
|
}
|
|
if ip == nil {
|
|
return ""
|
|
}
|
|
if v4 := ip.To4(); v4 != nil {
|
|
return v4.String()
|
|
}
|
|
return ip.Mask(net.CIDRMask(64, 128)).String()
|
|
}
|
|
|
|
func fingerprint(salt []byte, ip, ua string) string {
|
|
if len(ua) > uaMaxBytes {
|
|
ua = ua[:uaMaxBytes]
|
|
}
|
|
mac := hmac.New(sha256.New, salt)
|
|
_, _ = mac.Write([]byte(ip))
|
|
_, _ = mac.Write([]byte("\n"))
|
|
_, _ = mac.Write([]byte(ua))
|
|
sum := mac.Sum(nil)
|
|
return hex.EncodeToString(sum[:8])
|
|
}
|
|
|
|
func validSID(s string) bool {
|
|
if len(s) != 22 {
|
|
return false
|
|
}
|
|
for i := 0; i < len(s); i++ {
|
|
c := s[i]
|
|
switch {
|
|
case c >= 'A' && c <= 'Z':
|
|
case c >= 'a' && c <= 'z':
|
|
case c >= '0' && c <= '9':
|
|
case c == '-', c == '_':
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func newSID() (string, error) {
|
|
buf := make([]byte, 16)
|
|
if _, err := rand.Read(buf); err != nil {
|
|
return "", err
|
|
}
|
|
return base64.RawURLEncoding.EncodeToString(buf), nil
|
|
}
|
|
|
|
func validTable(s string) bool {
|
|
if !utf8.ValidString(s) {
|
|
return false
|
|
}
|
|
n := utf8.RuneCountInString(s)
|
|
if n < 1 || n > 64 {
|
|
return false
|
|
}
|
|
for _, r := range s {
|
|
if r == '_' || r == '-' || unicode.IsLetter(r) || unicode.IsDigit(r) {
|
|
continue
|
|
}
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func parseDigits(s string) (int64, bool) {
|
|
if len(s) < 1 || len(s) > 10 {
|
|
return 0, false
|
|
}
|
|
var n int64
|
|
for i := 0; i < len(s); i++ {
|
|
c := s[i]
|
|
if c < '0' || c > '9' {
|
|
return 0, false
|
|
}
|
|
n = n*10 + int64(c-'0')
|
|
}
|
|
return n, true
|
|
}
|
|
|
|
func parseTilePath(escaped string) (tileRef, bool) {
|
|
parts := strings.Split(escaped, "/")
|
|
if len(parts) != 6 || parts[0] != "" || parts[1] != "tiles" {
|
|
return tileRef{}, false
|
|
}
|
|
table, err := url.PathUnescape(parts[2])
|
|
if err != nil || !validTable(table) {
|
|
return tileRef{}, false
|
|
}
|
|
z, ok := parseDigits(parts[3])
|
|
if !ok || z > 30 {
|
|
return tileRef{}, false
|
|
}
|
|
if _, ok := parseDigits(parts[4]); !ok {
|
|
return tileRef{}, false
|
|
}
|
|
y, ok := parseY(parts[5])
|
|
if !ok {
|
|
return tileRef{}, false
|
|
}
|
|
return tileRef{table: table, z: parts[3], x: parts[4], y: y}, true
|
|
}
|
|
|
|
func parseY(seg string) (string, bool) {
|
|
if !strings.HasSuffix(seg, ".png") {
|
|
return "", false
|
|
}
|
|
num := strings.TrimSuffix(seg, ".png")
|
|
if _, ok := parseDigits(num); !ok {
|
|
return "", false
|
|
}
|
|
return num, true
|
|
}
|
|
|
|
// countedClient 判断请求是否来自 QGIS / QField。QGIS 的网络库总会在 User-Agent 里带上 "QGIS/版本号"。
|
|
func countedClient(ua string) bool {
|
|
return strings.Contains(ua, "QGIS/") || strings.Contains(strings.ToLower(ua), "qfield")
|
|
}
|
|
|
|
func requestIsHTTPS(r *http.Request, trustProxy bool) bool {
|
|
if r.TLS != nil {
|
|
return true
|
|
}
|
|
return trustProxy && strings.EqualFold(strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")), "https")
|
|
}
|
|
|
|
func (a *App) shouldCount(r *http.Request) bool {
|
|
if r.Method != http.MethodGet || !countedClient(r.UserAgent()) {
|
|
return false
|
|
}
|
|
return !a.cfg.HTTPSOnly || requestIsHTTPS(r, a.cfg.TrustProxy)
|
|
}
|
|
|
|
func prefix6(s string) string {
|
|
if len(s) <= 6 {
|
|
return s
|
|
}
|
|
return s[:6]
|
|
}
|
|
|
|
func (a *App) handleTile(w http.ResponseWriter, r *http.Request) {
|
|
tp, ok := parseTilePath(r.URL.EscapedPath())
|
|
if !ok {
|
|
a.notFound.Add(1)
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
|
|
hadSID := ""
|
|
if c, err := r.Cookie("sid"); err == nil && validSID(c.Value) {
|
|
hadSID = c.Value
|
|
}
|
|
issued := ""
|
|
if hadSID == "" {
|
|
id, err := newSID()
|
|
if err != nil {
|
|
slog.Error("生成会话失败", "err", err)
|
|
http.Error(w, "internal error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
issued = id
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: "sid",
|
|
Value: issued,
|
|
Path: "/tiles/",
|
|
MaxAge: cookieMaxAge,
|
|
HttpOnly: true,
|
|
})
|
|
a.newCookies.Add(1)
|
|
}
|
|
|
|
h := w.Header()
|
|
h.Set("Content-Type", "image/png")
|
|
h.Set("Content-Length", strconv.Itoa(len(a.png)))
|
|
h.Set("Cache-Control", "no-store")
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write(a.png)
|
|
|
|
counted := a.shouldCount(r)
|
|
if a.cfg.DebugLog {
|
|
shown := hadSID
|
|
if shown == "" {
|
|
shown = issued
|
|
}
|
|
slog.Info("瓦片",
|
|
"time", a.now().In(cst).Format(timeRFC3339),
|
|
"table", tp.table,
|
|
"z", tp.z,
|
|
"x", tp.x,
|
|
"y", tp.y,
|
|
"has_cookie", hadSID != "",
|
|
"sid", prefix6(shown),
|
|
"set_cookie", issued != "",
|
|
"counted", counted,
|
|
"ip", clientIP(r, a.cfg.TrustProxy),
|
|
"ua", r.UserAgent(),
|
|
)
|
|
}
|
|
|
|
if r.Method != http.MethodGet {
|
|
return
|
|
}
|
|
a.tiles.Add(1)
|
|
if !counted {
|
|
a.ignored.Add(1)
|
|
return
|
|
}
|
|
ip := clientIP(r, a.cfg.TrustProxy)
|
|
fp := fingerprint(a.salt, ip, r.UserAgent())
|
|
if a.rec.Record(a.now(), tp.table, hadSID, fp) {
|
|
a.pokeOnline()
|
|
}
|
|
}
|