github.com/TeaOSLab/EdgeNode@v1.3.8/internal/firewalls/firewall_base.go (about)

     1  // Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
     2  
     3  package firewalls
     4  
     5  import (
     6  	"github.com/iwind/TeaGo/types"
     7  	"strings"
     8  	"sync"
     9  	"time"
    10  )
    11  
    12  type BaseFirewall struct {
    13  	locker        sync.Mutex
    14  	latestIPTimes []string // [ip@time, ....]
    15  }
    16  
    17  // 检查是否在最近添加过
    18  func (this *BaseFirewall) checkLatestIP(ip string) bool {
    19  	this.locker.Lock()
    20  	defer this.locker.Unlock()
    21  
    22  	var expiredIndex = -1
    23  	for index, ipTime := range this.latestIPTimes {
    24  		var pieces = strings.Split(ipTime, "@")
    25  		var oldIP = pieces[0]
    26  		var oldTimestamp = pieces[1]
    27  		if types.Int64(oldTimestamp) < time.Now().Unix()-3 /** 3秒外表示过期 **/ {
    28  			expiredIndex = index
    29  			continue
    30  		}
    31  		if oldIP == ip {
    32  			return true
    33  		}
    34  	}
    35  
    36  	if expiredIndex > -1 {
    37  		this.latestIPTimes = this.latestIPTimes[expiredIndex+1:]
    38  	}
    39  
    40  	this.latestIPTimes = append(this.latestIPTimes, ip+"@"+types.String(time.Now().Unix()))
    41  	const maxLen = 128
    42  	if len(this.latestIPTimes) > maxLen {
    43  		this.latestIPTimes = this.latestIPTimes[1:]
    44  	}
    45  
    46  	return false
    47  }