miaopanel
1// Package wafgw runs the request inspection gateway that sits between nginx
2// and a site's origin. nginx keeps TLS, L1 signature rules and rate limiting;
3// the gateway adds the part nginx cannot do without Lua/ModSecurity: decoding
4// and inspecting the query string, headers, cookies and request body of every
5// request before it reaches the application.
6package wafgw
7
8import (
9 "bytes"
10 "compress/gzip"
11 "compress/zlib"
12 "context"
13 "crypto/tls"
14 "encoding/json"
15 "fmt"
16 "io"
17 "log/slog"
18 "net"
19 "net/http"
20 "net/http/httputil"
21 "net/url"
22 "regexp"
23 "strconv"
24 "strings"
25 "sync"
26 "sync/atomic"
27 "time"
28
29 "github.com/miaopanel/miaopanel/internal/config"
30 "github.com/miaopanel/miaopanel/internal/store"
31 "github.com/miaopanel/miaopanel/internal/waf"
32 "github.com/miaopanel/miaopanel/internal/wafengine"
33)
34
35const (
36 // maxBufferedBody is the largest body the gateway buffers for inspection.
37 // Larger uploads are streamed after the first bytes were checked.
38 maxBufferedBody = 2 << 20
39 eventQueueSize = 2048
40
41 // Each buffered request can hold up to maxBufferedBody while it is being
42 // decoded and inspected. Bound the number of concurrent body buffers so a
43 // burst of uploads cannot multiply this allocation.
44 maxConcurrentInspections = 16
45)
46
47// Policy is an immutable snapshot of the WAF settings used per request.
48type Policy struct {
49 Enabled bool
50 Strict bool
51 Threshold int
52 BlockStatus int
53 Rate int
54 Burst int
55 Whitelist []string
56 Custom []wafengine.CustomRule
57 // Origins maps a site slug to its registered loopback origin. nginx sends
58 // X-MP-Origin, but that header must never decide where the gateway
59 // connects: trusting it turned the listener into a proxy for any internal
60 // address reachable from the panel.
61 Origins map[string]string
62}
63
64// Service owns the gateway listener and the policy refresh loop.
65type Service struct {
66 cfg *config.Config
67 db *store.Store
68 waf *waf.Service
69 log *slog.Logger
70 addr string
71
72 policy atomic.Pointer[Policy]
73 policyAt atomic.Int64
74 started atomic.Bool
75 dropEvents atomic.Int64
76
77 events chan store.WAFEvent
78 stop chan struct{}
79 once sync.Once
80
81 limiter *rateLimiter
82 inspectSlots chan struct{}
83 proxy *httputil.ReverseProxy
84 serve *http.Server
85}
86
87type ctxKey int
88
89const ctxTarget ctxKey = iota
90
91// New builds a gateway bound to the panel services.
92func New(cfg *config.Config, db *store.Store, wafSvc *waf.Service, log *slog.Logger) *Service {
93 s := &Service{
94 cfg: cfg, db: db, waf: wafSvc, log: log,
95 addr: cfg.WAFGatewayAddr,
96 events: make(chan store.WAFEvent, eventQueueSize),
97 stop: make(chan struct{}),
98 limiter: newRateLimiter(),
99 inspectSlots: make(chan struct{}, maxConcurrentInspections),
100 }
101 if s.addr == "" {
102 s.addr = "127.0.0.1:8899"
103 }
104 transport := &http.Transport{
105 // Loopback traffic must never be routed through an environment proxy.
106 Proxy: nil,
107 DialContext: (&net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
108 MaxIdleConns: 512,
109 MaxIdleConnsPerHost: 128,
110 IdleConnTimeout: 90 * time.Second,
111 TLSHandshakeTimeout: 10 * time.Second,
112 ExpectContinueTimeout: time.Second,
113 ResponseHeaderTimeout: 300 * time.Second,
114 // Match nginx's default proxy_ssl_verify off for application upstreams.
115 TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
116 }
117 s.proxy = &httputil.ReverseProxy{
118 Rewrite: func(pr *httputil.ProxyRequest) {
119 if target, ok := pr.In.Context().Value(ctxTarget).(*url.URL); ok && target != nil {
120 pr.SetURL(target)
121 }
122 pr.Out.Host = pr.In.Host
123 pr.SetXForwarded()
124 pr.Out.Header.Del("X-MP-Site")
125 pr.Out.Header.Del("X-MP-Origin")
126 pr.Out.Header.Del("X-MP-Upstream")
127 pr.Out.Header.Del("X-MP-Real-IP")
128 },
129 Transport: transport,
130 FlushInterval: 100 * time.Millisecond,
131 ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
132 s.log.Warn("waf gateway upstream error", "path", r.URL.Path, "error", err)
133 writeJSON(w, http.StatusBadGateway, map[string]any{
134 "code": 502, "msg": "上游服务不可用",
135 })
136 },
137 }
138 s.serve = &http.Server{
139 Addr: s.addr,
140 Handler: s,
141 ReadHeaderTimeout: 10 * time.Second,
142 IdleTimeout: 90 * time.Second,
143 MaxHeaderBytes: 1 << 20,
144 }
145 return s
146}
147
148// Start begins listening and refreshing the policy. It returns an error when
149// the loopback address cannot be bound so the panel can report it.
150func (s *Service) Start(ctx context.Context) error {
151 ln, err := net.Listen("tcp", s.addr)
152 if err != nil {
153 return fmt.Errorf("WAF 网关监听 %s 失败: %w", s.addr, err)
154 }
155 s.started.Store(true)
156 if err := s.Reload(ctx); err != nil {
157 s.log.Warn("WAF 网关策略加载失败", "error", err)
158 }
159 go s.refresh(ctx)
160 go s.eventLoop(ctx)
161 go func() {
162 if err := s.serve.Serve(ln); err != nil && err != http.ErrServerClosed {
163 s.log.Error("WAF 网关退出", "error", err)
164 s.started.Store(false)
165 }
166 }()
167 s.log.Info("WAF 网关已启动", "addr", s.addr)
168 return nil
169}
170
171// Close stops the listener and the background workers.
172func (s *Service) Close() {
173 s.once.Do(func() {
174 close(s.stop)
175 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
176 defer cancel()
177 _ = s.serve.Shutdown(ctx)
178 s.started.Store(false)
179 })
180}
181
182// Ready reports whether the listener is running.
183func (s *Service) Ready() bool { return s.started.Load() }
184
185// Addr returns the loopback address the gateway listens on.
186func (s *Service) Addr() string { return s.addr }
187
188// Reload rebuilds the policy snapshot from SQLite.
189func (s *Service) Reload(ctx context.Context) error {
190 st, err := s.waf.Settings(ctx)
191 if err != nil {
192 return err
193 }
194 rules, err := s.db.WAFRules(ctx)
195 if err != nil {
196 return err
197 }
198 p := &Policy{
199 Enabled: st.Gateway, Strict: st.GatewayStrict, Threshold: st.GatewayThreshold,
200 BlockStatus: st.BlockStatus, Rate: st.Rate, Burst: st.Burst,
201 Whitelist: st.Whitelist,
202 Origins: map[string]string{},
203 }
204 if sites, err := s.db.ListSites(ctx); err == nil {
205 for _, site := range sites {
206 if site.Options.GatewayPort > 0 {
207 p.Origins[site.Slug] = fmt.Sprintf("127.0.0.1:%d", site.Options.GatewayPort)
208 }
209 }
210 }
211 for _, rule := range rules {
212 if !rule.Enabled || rule.Action != "block" {
213 continue
214 }
215 p.Custom = append(p.Custom, wafengine.CustomRule{
216 Name: rule.Name, MatchOn: rule.MatchOn, Op: rule.Op,
217 Pattern: rule.Pattern, Enabled: true,
218 })
219 }
220 s.policy.Store(p)
221 s.policyAt.Store(time.Now().Unix())
222 return nil
223}
224
225func (s *Service) refresh(ctx context.Context) {
226 ticker := time.NewTicker(2 * time.Second)
227 defer ticker.Stop()
228 for {
229 select {
230 case <-ctx.Done():
231 return
232 case <-s.stop:
233 return
234 case <-ticker.C:
235 reloadCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
236 _ = s.Reload(reloadCtx)
237 cancel()
238 }
239 }
240}
241
242func (s *Service) eventLoop(ctx context.Context) {
243 for {
244 select {
245 case <-ctx.Done():
246 return
247 case <-s.stop:
248 return
249 case ev := <-s.events:
250 addCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
251 if err := s.db.WAFEventAdd(addCtx, &ev); err != nil {
252 s.log.Debug("waf gateway event", "error", err)
253 }
254 cancel()
255 }
256 }
257}
258
259func (s *Service) enqueue(ev store.WAFEvent) {
260 select {
261 case s.events <- ev:
262 default:
263 s.dropEvents.Add(1)
264 }
265}
266
267// ServeHTTP implements the inspection and forwarding pipeline.
268func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
269 if !isLoopback(r.RemoteAddr) {
270 http.Error(w, "forbidden", http.StatusForbidden)
271 return
272 }
273 // Health is only reachable directly; nginx always sets X-MP-Site, so an
274 // external request for this path is forwarded to the site like any other.
275 if r.URL.Path == "/__mp_waf/health" && r.Header.Get("X-MP-Site") == "" {
276 s.health(w)
277 return
278 }
279
280 slug := strings.TrimSpace(r.Header.Get("X-MP-Site"))
281 if slug == "" {
282 writeJSON(w, http.StatusBadRequest, map[string]any{"code": 400, "msg": "缺少站点标识"})
283 return
284 }
285 pol := s.policy.Load()
286 target, err := targetFor(r, pol, slug)
287 if err != nil {
288 writeJSON(w, http.StatusBadGateway, map[string]any{"code": 502, "msg": err.Error()})
289 return
290 }
291 ip := clientIP(r)
292 if pol == nil || !pol.Enabled {
293 s.forward(w, r, target)
294 return
295 }
296
297 if isStaticPath(r.URL.Path) {
298 // Static assets are not rate limited and normally do not need body
299 // inspection, but the query string is still checked by the engine.
300 } else if !ipWhitelisted(pol.Whitelist, ip) && !s.limiter.allow(ip+"|"+slug, pol.Rate, pol.Burst) {
301 s.block(w, r, pol, ip, slug, 429, wafengine.Result{
302 Score: 0,
303 Hits: []wafengine.Hit{{Module: "cc", Rule: "rate_limit", Score: 0, Location: "remote", Evidence: ip}},
304 }, "请求过于频繁")
305 return
306 }
307
308 // Only requests with a body need the expensive buffer/decode path. The
309 // semaphore applies backpressure instead of letting concurrent uploads
310 // reserve an unbounded amount of memory.
311 hasBody := r.Body != nil && r.Method != http.MethodGet && r.Method != http.MethodHead && r.ContentLength != 0
312 // A form or JSON body larger than the inspection window can hide its
313 // payload behind filler bytes, which used to pass untouched. Legitimate
314 // requests of that shape are rare, so treat them as an attack surface
315 // instead of forwarding unscanned bytes. Multipart uploads keep streaming.
316 if hasBody && r.ContentLength > int64(wafengine.MaxBodyScan) {
317 ct := strings.ToLower(r.Header.Get("Content-Type"))
318 if strings.Contains(ct, "application/x-www-form-urlencoded") || strings.Contains(ct, "application/json") {
319 s.block(w, r, pol, ip, slug, http.StatusRequestEntityTooLarge, wafengine.Result{
320 Hits: []wafengine.Hit{{Module: "body", Rule: "oversized_body", Location: "body", Evidence: "body exceeds inspection limit"}},
321 }, "请求体超过检测上限")
322 return
323 }
324 }
325 releaseInspect := func() {}
326 if hasBody {
327 select {
328 case s.inspectSlots <- struct{}{}:
329 released := false
330 releaseInspect = func() {
331 if !released {
332 released = true
333 <-s.inspectSlots
334 }
335 }
336 defer releaseInspect()
337 case <-r.Context().Done():
338 return
339 }
340 }
341 body, truncated, err := bufferBody(r)
342 if err != nil {
343 writeJSON(w, http.StatusBadRequest, map[string]any{"code": 400, "msg": "读取请求体失败"})
344 return
345 }
346 inspectBody := decodeContent(body, r.Header.Get("Content-Encoding"))
347 req := &wafengine.Request{
348 Method: r.Method, Path: r.URL.Path, RawQuery: r.URL.RawQuery,
349 ContentType: r.Header.Get("Content-Type"), RemoteIP: ip,
350 Header: r.Header,
351 Cookies: cookieMap(r),
352 Body: inspectBody,
353 }
354 if truncated {
355 if len(req.Body) > wafengine.MaxBodyScan {
356 req.Body = req.Body[:wafengine.MaxBodyScan]
357 }
358 }
359 res := wafengine.Inspect(req, wafengine.Config{
360 Strict: pol.Strict, Threshold: pol.Threshold,
361 Whitelist: pol.Whitelist, Custom: pol.Custom,
362 })
363 // Inspection is done; do not hold a slot while the origin streams a long
364 // upload or response.
365 releaseInspect()
366 if res.Blocked {
367 s.block(w, r, pol, ip, slug, pol.BlockStatus, res, "")
368 return
369 }
370 s.forward(w, r, target)
371}
372
373func (s *Service) block(w http.ResponseWriter, r *http.Request, pol *Policy, ip, slug string, status int, res wafengine.Result, reason string) {
374 rule, detail := summarize(res)
375 if reason == "" {
376 reason = "请求包含恶意特征"
377 }
378 ev := store.WAFEvent{
379 TS: time.Now().Unix(), Site: slug, IP: ip, Method: r.Method,
380 URI: truncate(r.URL.RequestURI(), 500), UA: truncate(r.UserAgent(), 300),
381 Status: status, Rule: rule, Module: moduleOf(res), Score: res.Score, Detail: detail,
382 }
383 if s.started.Load() {
384 s.enqueue(ev)
385 } else {
386 // Direct handler use (tests, or a failed listener) still records.
387 _ = s.db.WAFEventAdd(context.Background(), &ev)
388 }
389
390 w.Header().Set("X-MP-WAF", "blocked")
391 w.Header().Set("Cache-Control", "no-store")
392 if wantsJSON(r) {
393 writeJSON(w, status, map[string]any{
394 "code": status, "msg": reason,
395 "data": map[string]any{"request_id": ev.TS, "rule": rule, "score": res.Score},
396 })
397 return
398 }
399 w.Header().Set("Content-Type", "text/html; charset=utf-8")
400 w.WriteHeader(status)
401 _, _ = fmt.Fprintf(w, blockPage, status, rule, res.Score)
402}
403
404func (s *Service) forward(w http.ResponseWriter, r *http.Request, target *url.URL) {
405 ctx := context.WithValue(r.Context(), ctxTarget, target)
406 s.proxy.ServeHTTP(w, r.WithContext(ctx))
407}
408
409func (s *Service) health(w http.ResponseWriter) {
410 age := int64(0)
411 if at := s.policyAt.Load(); at > 0 {
412 age = time.Now().Unix() - at
413 }
414 writeJSON(w, http.StatusOK, map[string]any{
415 "ok": true, "addr": s.addr, "ready": s.started.Load(),
416 "policy_age": age, "dropped_events": s.dropEvents.Load(),
417 })
418}
419
420func targetFor(r *http.Request, pol *Policy, slug string) (*url.URL, error) {
421 // The registered origin always wins: nginx sets the header from the site
422 // row, and nothing derived from a request header may choose the target.
423 // Previously any local process could point X-MP-Origin at an arbitrary
424 // internal host and use the gateway as a proxy.
425 if pol != nil {
426 if origin := pol.Origins[slug]; origin != "" {
427 return &url.URL{Scheme: "http", Host: origin}, nil
428 }
429 }
430 if origin := strings.TrimSpace(r.Header.Get("X-MP-Origin")); origin != "" {
431 if !loopbackAuthority(origin) {
432 return nil, fmt.Errorf("origin 必须是本机回环地址")
433 }
434 return &url.URL{Scheme: "http", Host: origin}, nil
435 }
436 upstream := strings.TrimSpace(r.Header.Get("X-MP-Upstream"))
437 if upstream == "" {
438 return nil, fmt.Errorf("缺少上游地址")
439 }
440 u, err := url.Parse(upstream)
441 if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
442 return nil, fmt.Errorf("上游地址不合法")
443 }
444 if !loopbackAuthority(u.Host) {
445 return nil, fmt.Errorf("上游地址必须是本机回环地址")
446 }
447 return u, nil
448}
449
450// loopbackAuthority accepts "127.0.0.1:8080" and "[::1]:8080".
451func loopbackAuthority(a string) bool {
452 host, port, err := net.SplitHostPort(a)
453 if err != nil || port == "" {
454 return false
455 }
456 if _, err := strconv.Atoi(port); err != nil {
457 return false
458 }
459 ip := net.ParseIP(host)
460 return ip != nil && ip.IsLoopback()
461}
462
463// ipWhitelisted mirrors the nginx level exemption for the CC limiter: an
464// operator who trusted an address must not be throttled by the gateway.
465func ipWhitelisted(list []string, ip string) bool {
466 addr := net.ParseIP(strings.TrimSpace(ip))
467 if addr == nil {
468 return false
469 }
470 for _, item := range list {
471 item = strings.TrimSpace(item)
472 if item == "" {
473 continue
474 }
475 if strings.Contains(item, "/") {
476 if _, block, err := net.ParseCIDR(item); err == nil && block.Contains(addr) {
477 return true
478 }
479 continue
480 }
481 if v := net.ParseIP(item); v != nil && v.Equal(addr) {
482 return true
483 }
484 }
485 return false
486}
487
488func bufferBody(r *http.Request) ([]byte, bool, error) {
489 if r.Body == nil || r.Method == http.MethodGet || r.Method == http.MethodHead {
490 return nil, false, nil
491 }
492 if r.ContentLength > maxBufferedBody {
493 // Read the head for a cheap inspection, then let the proxy stream the
494 // rest without buffering a large upload in memory. Compressed bodies
495 // need a larger head because the payload only appears after inflation.
496 limit := int64(wafengine.MaxBodyScan)
497 if compressedEncoding(r.Header.Get("Content-Encoding")) {
498 limit = maxBufferedBody
499 }
500 head, err := io.ReadAll(io.LimitReader(r.Body, limit))
501 if err != nil {
502 return nil, false, err
503 }
504 r.Body = io.NopCloser(io.MultiReader(bytes.NewReader(head), r.Body))
505 return head, true, nil
506 }
507 orig := r.Body
508 buf, err := io.ReadAll(io.LimitReader(orig, maxBufferedBody+1))
509 if err != nil {
510 return nil, false, err
511 }
512 if len(buf) > maxBufferedBody {
513 r.Body = io.NopCloser(io.MultiReader(bytes.NewReader(buf), orig))
514 return buf[:wafengine.MaxBodyScan], true, nil
515 }
516 r.Body = io.NopCloser(bytes.NewReader(buf))
517 return buf, false, nil
518}
519
520func compressedEncoding(encoding string) bool {
521 enc := strings.ToLower(strings.TrimSpace(encoding))
522 if i := strings.IndexByte(enc, ','); i >= 0 {
523 enc = strings.TrimSpace(enc[:i])
524 }
525 return enc == "gzip" || enc == "deflate"
526}
527
528// decodeContent returns a plaintext copy for inspection. The original body is
529// still forwarded unchanged, so applications that accept gzip keep working.
530func decodeContent(body []byte, encoding string) []byte {
531 if len(body) == 0 {
532 return body
533 }
534 enc := strings.ToLower(strings.TrimSpace(encoding))
535 if i := strings.IndexByte(enc, ','); i >= 0 {
536 enc = strings.TrimSpace(enc[:i])
537 }
538 var reader io.Reader
539 switch enc {
540 case "gzip":
541 zr, err := gzip.NewReader(bytes.NewReader(body))
542 if err != nil {
543 return body
544 }
545 defer zr.Close()
546 reader = zr
547 case "deflate":
548 zr, err := zlib.NewReader(bytes.NewReader(body))
549 if err != nil {
550 return body
551 }
552 defer zr.Close()
553 reader = zr
554 default:
555 return body
556 }
557 out, err := io.ReadAll(io.LimitReader(reader, maxBufferedBody))
558 if err != nil || len(out) == 0 {
559 return body
560 }
561 return out
562}
563
564func summarize(res wafengine.Result) (string, string) {
565 if len(res.Hits) == 0 {
566 return "unknown", ""
567 }
568 parts := make([]string, 0, 3)
569 for i, h := range res.Hits {
570 if i >= 3 {
571 break
572 }
573 parts = append(parts, fmt.Sprintf("%s/%s(%d) %s", h.Module, h.Rule, h.Score, h.Evidence))
574 }
575 first := res.Hits[0]
576 return first.Module + "/" + first.Rule, truncate(strings.Join(parts, " | "), 500)
577}
578
579func moduleOf(res wafengine.Result) string {
580 if len(res.Hits) == 0 {
581 return ""
582 }
583 return res.Hits[0].Module
584}
585
586var reStatic = regexp.MustCompile(`(?i)\.(css|js|mjs|map|png|jpe?g|gif|svg|webp|ico|woff2?|ttf|otf|eot|mp4|webm|mp3|pdf|txt|xml|json)$`)
587
588func isStaticPath(p string) bool { return reStatic.MatchString(p) }
589
590func isLoopback(remote string) bool {
591 host, _, err := net.SplitHostPort(remote)
592 if err != nil {
593 host = remote
594 }
595 ip := net.ParseIP(host)
596 return ip != nil && ip.IsLoopback()
597}
598
599func clientIP(r *http.Request) string {
600 if v := strings.TrimSpace(r.Header.Get("X-Real-IP")); v != "" {
601 if ip := net.ParseIP(v); ip != nil {
602 return ip.String()
603 }
604 }
605 host, _, err := net.SplitHostPort(r.RemoteAddr)
606 if err != nil {
607 return r.RemoteAddr
608 }
609 return host
610}
611
612func cookieMap(r *http.Request) map[string]string {
613 out := map[string]string{}
614 for _, c := range r.Cookies() {
615 out[c.Name] = c.Value
616 }
617 return out
618}
619
620func wantsJSON(r *http.Request) bool {
621 return strings.Contains(r.Header.Get("Accept"), "application/json") ||
622 strings.EqualFold(r.Header.Get("X-Requested-With"), "XMLHttpRequest")
623}
624
625func writeJSON(w http.ResponseWriter, status int, v any) {
626 w.Header().Set("Content-Type", "application/json; charset=utf-8")
627 w.Header().Set("Cache-Control", "no-store")
628 w.WriteHeader(status)
629 _ = json.NewEncoder(w).Encode(v)
630}
631
632func truncate(s string, n int) string {
633 if len(s) <= n {
634 return s
635 }
636 return s[:n]
637}
638
639const blockPage = `<!doctype html>
640<html lang="zh-CN"><head><meta charset="utf-8"><title>请求被拦截</title>
641<style>body{font-family:system-ui,-apple-system,"Segoe UI",sans-serif;background:#0f1720;color:#e6edf3;display:flex;align-items:center;justify-content:center;height:100vh;margin:0}
642main{max-width:520px;text-align:center}h1{font-weight:600;margin:0 0 8px;font-size:22px}p{color:#8b949e;margin:6px 0}
643code{background:#1c2733;padding:2px 6px;border-radius:4px;color:#7dd3fc}</style></head>
644<body><main><h1>请求被 WAF 拦截</h1>
645<p>状态码 <code>%d</code> · 规则 <code>%s</code> · 评分 <code>%d</code></p>
646<p>如果这是正常业务请求,请联系站点管理员。</p></main></body></html>`
647
648// --- token bucket ----------------------------------------------------------
649
650type bucket struct {
651 tokens float64
652 last time.Time
653}
654
655type rateLimiter struct {
656 mu sync.Mutex
657 buckets map[string]*bucket
658 lastGC time.Time
659}
660
661func newRateLimiter() *rateLimiter {
662 return &rateLimiter{buckets: map[string]*bucket{}, lastGC: time.Now()}
663}
664
665func (l *rateLimiter) allow(key string, rate, burst int) bool {
666 if rate <= 0 {
667 rate = 50
668 }
669 if burst <= 0 {
670 burst = 200
671 }
672 now := time.Now()
673 l.mu.Lock()
674 defer l.mu.Unlock()
675 b := l.buckets[key]
676 if b == nil {
677 b = &bucket{tokens: float64(burst), last: now}
678 l.buckets[key] = b
679 }
680 b.tokens += now.Sub(b.last).Seconds() * float64(rate)
681 if b.tokens > float64(burst) {
682 b.tokens = float64(burst)
683 }
684 b.last = now
685 if now.Sub(l.lastGC) > 10*time.Minute {
686 for k, v := range l.buckets {
687 if now.Sub(v.last) > 10*time.Minute {
688 delete(l.buckets, k)
689 }
690 }
691 l.lastGC = now
692 }
693 if b.tokens < 1 {
694 return false
695 }
696 b.tokens--
697 return true
698}