feat: build wahrwelt A/D toolkit

This commit is contained in:
TakuyaYagam1 committed 2026-10-14 11:30:41 +03:00
1 parent 303438d206
commit 653924d8c6
564 files changed
+36310 -49998

No files matched your search

@@ -0,0 +1,66 @@
package exploits
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/c4t-but-s4d/neo/v2/internal/server/config"
)
func NewFarmClient(cfg config.FarmConfig) *FarmClient {
return &FarmClient{
url: strings.TrimRight(cfg.URL, "/"),
password: cfg.Password,
client: http.Client{
Timeout: 3 * time.Second,
},
}
}
type FarmClient struct {
url string
password string
client http.Client
}
const maxFarmConfigBytes = 1 << 20
func (fc *FarmClient) FillConfig(ctx context.Context, cfg *config.FarmConfig) error {
url := fmt.Sprintf("%s/api/get_config", fc.url)
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return fmt.Errorf("создание запроса к Farm: %w", err)
}
req.Header.Set("Authorization", fc.password)
req.Header.Set("X-Token", fc.password)
resp, err := fc.client.Do(req)
if err != nil {
return fmt.Errorf("выполнение запроса к Farm: %w", err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
logrus.Errorf("Не удалось закрыть ответ Farm: %v", err)
}
}()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("Farm вернул HTTP %d", resp.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, maxFarmConfigBytes+1))
if err != nil {
return fmt.Errorf("чтение конфигурации Farm: %w", err)
}
if len(body) > maxFarmConfigBytes {
return fmt.Errorf("конфигурация Farm превышает %d байт", maxFarmConfigBytes)
}
if err := cfg.ParseJSON(bytes.NewReader(body)); err != nil {
return fmt.Errorf("разбор ответа Farm: %w", err)
}
return nil
}
@@ -0,0 +1,21 @@
package exploits
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
type Metrics struct {
AliveClients prometheus.Gauge
}
func NewMetrics(namespace string) *Metrics {
return &Metrics{
AliveClients: promauto.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: "server",
Name: "alive_clients",
Help: "Number of alive clients",
}),
}
}
@@ -0,0 +1,236 @@
package exploits
import (
"context"
"fmt"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"github.com/google/uuid"
"google.golang.org/grpc/codes"
"github.com/c4t-but-s4d/neo/v2/internal/config"
"github.com/c4t-but-s4d/neo/v2/internal/server/common"
serverConfig "github.com/c4t-but-s4d/neo/v2/internal/server/config"
"github.com/c4t-but-s4d/neo/v2/pkg/gstream"
"github.com/c4t-but-s4d/neo/v2/pkg/hostbucket"
"github.com/c4t-but-s4d/neo/v2/pkg/pubsub"
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
)
func New(cfg *serverConfig.Config, storage *CachedStorage) *Server {
ems := &Server{
LoggingServer: common.NewLoggingServer("exploits"),
storage: storage,
buckets: hostbucket.New(cfg.FarmConfig.Teams),
visits: newVisitsMap(),
singleRunPubSub: pubsub.NewPubSub[*epb.SingleRunRequest](),
broadcastPubSub: pubsub.NewPubSub[*epb.BroadcastRequest](),
metrics: NewMetrics(cfg.MetricsNamespace),
}
ems.UpdateConfig(cfg)
return ems
}
type Server struct {
epb.UnimplementedServiceServer
common.LoggingServer
storage *CachedStorage
config *config.ExploitsConfig
cfgMutex sync.RWMutex
buckets *hostbucket.HostBucket
visits *visitsMap
metrics *Metrics
singleRunPubSub *pubsub.PubSub[*epb.SingleRunRequest]
broadcastPubSub *pubsub.PubSub[*epb.BroadcastRequest]
}
func (s *Server) Ping(ctx context.Context, r *epb.PingRequest) (*epb.PingResponse, error) {
s.LogRequest(ctx, r)
if r == nil {
return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "требуется запрос Ping")
}
switch p := r.Payload.(type) {
case *epb.PingRequest_ServerInfoRequest:
// Пропустить эту запись.
case *epb.PingRequest_HeartbeatRequest:
s.cfgMutex.RLock()
defer s.cfgMutex.RUnlock()
s.visits.Add(r.ClientId)
s.buckets.AddNode(r.ClientId, int(p.HeartbeatRequest.Weight))
case *epb.PingRequest_LeaveRequest:
s.visits.MarkInvalid(r.ClientId)
default:
return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "неизвестный тип данных: %T", p)
}
return &epb.PingResponse{
State: &epb.ServerState{
ClientTeamMap: s.buckets.Buckets(),
Exploits: s.storage.States(),
Config: config.ToProto(s.config),
},
}, nil
}
func (s *Server) Exploit(ctx context.Context, r *epb.ExploitRequest) (*epb.ExploitResponse, error) {
s.LogRequest(ctx, r)
if r == nil || !validExploitID(r.ExploitId) {
return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "неверный идентификатор эксплойта")
}
state, ok := s.storage.GetState(r.ExploitId)
if !ok {
return nil, s.WrapErrorf(ctx, codes.NotFound, "эксплойт %q не найден", r.ExploitId)
}
return &epb.ExploitResponse{
State: state,
}, nil
}
func (s *Server) UpdateExploit(ctx context.Context, r *epb.UpdateExploitRequest) (*epb.UpdateExploitResponse, error) {
s.LogRequest(ctx, r)
if r == nil || r.State == nil || r.State.Config == nil || r.State.File == nil ||
!validExploitID(r.State.ExploitId) || !validFileUUID(r.State.File.Uuid) {
return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "неверное состояние эксплойта")
}
if r.State.Config.IsArchive && (r.State.Config.Entrypoint == "" ||
strings.ContainsAny(r.State.Config.Entrypoint, "\\\x00") || !filepath.IsLocal(r.State.Config.Entrypoint)) {
return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "неверный путь точки входа в архиве")
}
newState, err := s.storage.UpdateExploitVersion(r.State)
if err != nil {
return nil, s.WrapErrorf(ctx, codes.Internal, "Не удалось обновить версию эксплойта: %v", err)
}
return &epb.UpdateExploitResponse{State: newState}, nil
}
func validExploitID(id string) bool {
return id != "" && len(id) <= 128 && id != "." && id != ".." &&
!strings.ContainsAny(id, "/\\\x00") && filepath.IsLocal(id)
}
func validFileUUID(id string) bool {
parsed, err := uuid.Parse(id)
return err == nil && parsed.String() == id
}
func (s *Server) BroadcastCommand(ctx context.Context, r *epb.BroadcastRequest) (*epb.BroadcastResponse, error) {
s.LogRequest(ctx, r)
s.broadcastPubSub.Publish(r)
return &epb.BroadcastResponse{}, nil
}
func (s *Server) BroadcastSubscribe(r *epb.BroadcastSubscribeRequest, stream epb.Service_BroadcastSubscribeServer) error {
s.LogRequest(stream.Context(), r)
wstream := gstream.Wrap[
epb.BroadcastRequest,
epb.BroadcastSubscribeResponse,
](
stream,
func(t *epb.BroadcastRequest) *epb.BroadcastSubscribeResponse {
return &epb.BroadcastSubscribeResponse{Command: t.Command}
},
)
sub := s.broadcastPubSub.Subscribe(wstream.Send)
defer s.broadcastPubSub.Unsubscribe(sub)
sub.Run(stream.Context())
return nil
}
func (s *Server) SingleRun(ctx context.Context, r *epb.SingleRunRequest) (*epb.SingleRunResponse, error) {
s.LogRequest(ctx, r)
s.singleRunPubSub.Publish(r)
return &epb.SingleRunResponse{}, nil
}
func (s *Server) SingleRunSubscribe(r *epb.SingleRunSubscribeRequest, stream epb.Service_SingleRunSubscribeServer) error {
s.LogRequest(stream.Context(), r)
wstream := gstream.Wrap[
epb.SingleRunRequest,
epb.SingleRunSubscribeResponse,
](
stream,
func(t *epb.SingleRunRequest) *epb.SingleRunSubscribeResponse {
return &epb.SingleRunSubscribeResponse{ExploitId: t.ExploitId}
},
)
sub := s.singleRunPubSub.Subscribe(wstream.Send)
defer s.singleRunPubSub.Unsubscribe(sub)
sub.Run(stream.Context())
return nil
}
func (s *Server) HeartBeat(ctx context.Context) {
ticker := time.NewTicker(s.config.PingEvery)
defer ticker.Stop()
for {
select {
case <-ticker.C:
s.Logger.Info("Проверка клиентов")
s.checkClients()
case <-ctx.Done():
return
}
}
}
func (s *Server) UpdateMetrics(ctx context.Context) {
ticker := time.NewTicker(time.Second * 5)
defer ticker.Stop()
for {
select {
case <-ticker.C:
s.Logger.Info("Обновление метрик")
s.updateMetrics()
case <-ctx.Done():
return
}
}
}
func (s *Server) UpdateConfig(cfg *serverConfig.Config) {
env := make([]string, 0, len(cfg.Environ))
for k, v := range cfg.Environ {
env = append(env, fmt.Sprintf("%s=%s", k, v))
}
s.cfgMutex.Lock()
defer s.cfgMutex.Unlock()
s.config = &config.ExploitsConfig{
PingEvery: cfg.PingEvery,
SubmitEvery: cfg.SubmitEvery,
FarmURL: cfg.FarmConfig.URL,
FarmPassword: cfg.FarmConfig.Password,
FlagRegexp: regexp.MustCompile(cfg.FarmConfig.FlagRegexp),
Environ: env,
}
s.buckets.UpdateTeams(cfg.FarmConfig.Teams)
}
func (s *Server) checkClients() {
alive, dead := s.visits.Invalidate(time.Now(), s.config.PingEvery)
s.Logger.Infof("Проверка связи: недоступные клиенты %v, доступные клиенты %v", dead, alive)
for _, c := range dead {
s.buckets.DeleteNode(c)
}
}
func (s *Server) updateMetrics() {
s.metrics.AliveClients.Set(float64(s.visits.Size()))
}
@@ -0,0 +1,165 @@
package exploits
import (
"context"
"fmt"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/testing/protocmp"
"github.com/c4t-but-s4d/neo/v2/internal/server/config"
"github.com/c4t-but-s4d/neo/v2/pkg/hostbucket"
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
fspb "github.com/c4t-but-s4d/neo/v2/proto/go/fileserver"
)
func testServer(t *testing.T) (*Server, func()) {
t.Helper()
db, cleanupDB := testDB()
st, err := NewStorage(db)
require.NoError(t, err)
require.NoError(t, err)
cfg := &config.Config{
BaseDir: t.TempDir(),
MetricsNamespace: fmt.Sprintf("tests_%s", uuid.NewString()[:8]),
}
es := New(cfg, st)
return es, cleanupDB
}
func TestServer_UpdateExploit(t *testing.T) {
es, clean := testServer(t)
defer clean()
fileID := uuid.NewString()
cfg := &epb.ExploitConfiguration{
Entrypoint: "bin",
IsArchive: false,
}
r := &epb.UpdateExploitRequest{
State: &epb.ExploitState{
ExploitId: "1",
File: &fspb.FileInfo{Uuid: fileID},
Config: cfg,
},
}
resp, err := es.UpdateExploit(context.Background(), r)
require.NoError(t, err)
want := &epb.ExploitState{
ExploitId: "1",
Version: 1,
File: r.State.File,
Config: cfg,
}
if diff := cmp.Diff(want, resp.State, protocmp.Transform()); diff != "" {
t.Errorf("UpdateExploit() mismatch (-want +got):\n%s", diff)
}
}
func TestServer_Exploit(t *testing.T) {
es, clean := testServer(t)
defer clean()
fileID := uuid.NewString()
cfg := &epb.ExploitConfiguration{
Entrypoint: "bin",
IsArchive: false,
}
state := &epb.ExploitState{
ExploitId: "1",
File: &fspb.FileInfo{Uuid: fileID},
Config: cfg,
}
req := &epb.UpdateExploitRequest{State: state}
ctx := context.Background()
_, err := es.UpdateExploit(ctx, req)
require.NoError(t, err)
resp, err := es.Exploit(ctx, &epb.ExploitRequest{ExploitId: state.ExploitId})
require.NoError(t, err)
wantState := &epb.ExploitState{
ExploitId: "1",
Version: 1,
File: state.File,
Config: cfg,
}
if diff := cmp.Diff(wantState, resp.State, protocmp.Transform()); diff != "" {
t.Errorf("Exploit() state mismatch (-want +got):\n%s", diff)
}
}
func TestServer_Ping(t *testing.T) {
es, clean := testServer(t)
defer clean()
fileID := uuid.NewString()
es.buckets = hostbucket.New(map[string]string{"id1": "ip1", "id2": "ip2"})
es.config.FarmURL = "test"
ctx := context.Background()
cfg := &epb.ExploitConfiguration{
Entrypoint: "bin",
IsArchive: false,
}
state := &epb.ExploitState{
ExploitId: "1",
File: &fspb.FileInfo{Uuid: fileID},
Config: cfg,
}
r := &epb.UpdateExploitRequest{State: state}
updateResp, err := es.UpdateExploit(ctx, r)
require.NoError(t, err)
const clientID = "id1"
req := &epb.PingRequest{
ClientId: clientID,
Payload: &epb.PingRequest_HeartbeatRequest{
HeartbeatRequest: &epb.PingRequest_Heartbeat{},
},
}
resp, err := es.Ping(ctx, req)
require.NoError(t, err)
want := []*epb.ExploitState{updateResp.State}
if diff := cmp.Diff(want, resp.State.Exploits, protocmp.Transform()); diff != "" {
t.Errorf("Ping() states mismatch (-want +got):\n%s", diff)
}
if diff := cmp.Diff(es.buckets.Buckets(), resp.State.ClientTeamMap, protocmp.Transform()); diff != "" {
t.Errorf("Ping() bucket mismatch (-want +got):\n%s", diff)
}
require.NotEmpty(t, es.buckets.Buckets()[clientID].Teams)
require.Equal(t, es.config.FarmURL, resp.State.Config.FarmUrl)
require.True(t, es.visits.visits["id1"].Before(time.Now()))
}
func TestServer_BroadcastCommand(t *testing.T) {
es, clean := testServer(t)
defer clean()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var received *epb.BroadcastRequest
signal := make(chan struct{})
handler := func(msg *epb.BroadcastRequest) error {
received = msg
close(signal)
return nil
}
testSub := es.broadcastPubSub.Subscribe(handler)
defer es.broadcastPubSub.Unsubscribe(testSub)
go testSub.Run(ctx)
r := &epb.BroadcastRequest{Command: "echo 123"}
_, err := es.BroadcastCommand(ctx, r)
require.NoError(t, err)
select {
case <-signal:
break
case <-time.After(time.Millisecond * 100):
t.Errorf("Handler was not called in time")
}
require.Equal(t, r, received)
}
@@ -0,0 +1,133 @@
package exploits
import (
"fmt"
"strings"
"sync"
"github.com/samber/lo"
"github.com/sirupsen/logrus"
bolt "go.etcd.io/bbolt"
"google.golang.org/protobuf/proto"
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
)
const (
stateBucketKey = "states"
)
func NewBoltStorage(path string) (*CachedStorage, error) {
db, err := bolt.Open(path, 0755, nil)
if err != nil {
return nil, fmt.Errorf("открытие базы Bolt %s: %w", path, err)
}
return NewStorage(db)
}
func NewStorage(db *bolt.DB) (*CachedStorage, error) {
cs := &CachedStorage{
stateCache: nil,
bdb: db,
}
if err := cs.initDB(); err != nil {
return nil, err
}
cs.initCache()
return cs, nil
}
type CachedStorage struct {
stateCache map[string]*epb.ExploitState
m sync.RWMutex
bdb *bolt.DB
}
func (cs *CachedStorage) States() []*epb.ExploitState {
cs.m.RLock()
defer cs.m.RUnlock()
return lo.Values(cs.stateCache)
}
func (cs *CachedStorage) GetState(exploitID string) (*epb.ExploitState, bool) {
cs.m.RLock()
defer cs.m.RUnlock()
val, ok := cs.stateCache[exploitID]
return val, ok
}
func (cs *CachedStorage) UpdateExploitVersion(newState *epb.ExploitState) (*epb.ExploitState, error) {
cs.m.Lock()
defer cs.m.Unlock()
if state, ok := cs.stateCache[newState.ExploitId]; ok {
newState.Version = state.Version + 1
} else {
newState.Version = 1
}
key := []byte(fmt.Sprintf("%s:%d", newState.ExploitId, newState.Version))
stateBytes, err := proto.Marshal(newState)
if err != nil {
return nil, fmt.Errorf("сериализация состояния: %w", err)
}
if err := cs.bdb.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(stateBucketKey))
if err := b.Put(key, stateBytes); err != nil {
return fmt.Errorf("сохранение состояния в базе: %w", err)
}
return nil
}); err != nil {
return nil, fmt.Errorf("обновление состояния в базе: %w", err)
}
cs.stateCache[newState.ExploitId] = newState
return newState, nil
}
func (cs *CachedStorage) initCache() {
cs.m.Lock()
defer cs.m.Unlock()
if cs.stateCache == nil {
cs.stateCache = make(map[string]*epb.ExploitState)
if err := cs.readDB(); err != nil {
logrus.Errorf("Не удалось прочитать данные эксплойта из базы: %v", err)
}
}
}
func (cs *CachedStorage) readDB() error {
if err := cs.bdb.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(stateBucketKey))
if err := b.ForEach(func(k, v []byte) error {
key := string(k)
eID := strings.Split(key, ":")[0]
es := new(epb.ExploitState)
if err := proto.Unmarshal(v, es); err != nil {
return fmt.Errorf("разбор состояния эксплойта: %w", err)
}
if v, ok := cs.stateCache[eID]; !ok || es.Version > v.Version {
cs.stateCache[eID] = es
}
return nil
}); err != nil {
return fmt.Errorf("чтение состояний эксплойтов: %w", err)
}
return nil
}); err != nil {
return fmt.Errorf("чтение состояния из базы: %w", err)
}
return nil
}
func (cs *CachedStorage) initDB() error {
if err := cs.bdb.Update(func(tx *bolt.Tx) error {
if _, err := tx.CreateBucketIfNotExists([]byte(stateBucketKey)); err != nil {
return fmt.Errorf("создание раздела состояний: %w", err)
}
return nil
}); err != nil {
return fmt.Errorf("инициализация базы: %w", err)
}
return nil
}
@@ -0,0 +1,148 @@
package exploits
import (
"fmt"
"os"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
bolt "go.etcd.io/bbolt"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/testing/protocmp"
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
fspb "github.com/c4t-but-s4d/neo/v2/proto/go/fileserver"
)
func testDB() (*bolt.DB, func()) {
tmpFile, err := os.CreateTemp("", "db")
if err != nil {
panic(err)
}
db, err := bolt.Open(tmpFile.Name(), 0755, nil)
if err != nil {
panic(err)
}
return db, func() {
defer func(name string) {
err := os.Remove(name)
if err != nil {
logrus.Errorf("Error removing file: %v", err)
}
}(tmpFile.Name())
if err := db.Close(); err != nil {
panic(err)
}
}
}
func TestCachedStorage_States(t *testing.T) {
db, cleanup := testDB()
defer cleanup()
cs, err := NewStorage(db)
require.NoError(t, err)
for i := 0; i < 5; i++ {
state := &epb.ExploitState{
ExploitId: fmt.Sprintf("%d", i),
File: &fspb.FileInfo{Uuid: "1"},
Config: &epb.ExploitConfiguration{
Entrypoint: "./kek",
IsArchive: false,
},
}
_, err := cs.UpdateExploitVersion(state)
require.NoError(t, err)
}
require.Len(t, cs.States(), 5)
}
func TestCachedStorage_UpdateStates(t *testing.T) {
db, cleanup := testDB()
defer cleanup()
cs, err := NewStorage(db)
require.NoError(t, err)
state := &epb.ExploitState{
ExploitId: "1",
File: &fspb.FileInfo{Uuid: "1"},
Config: &epb.ExploitConfiguration{
Entrypoint: "./kek",
IsArchive: false,
},
}
_, err = cs.UpdateExploitVersion(state)
require.NoError(t, err)
require.EqualValues(t, 1, state.Version)
s, _ := cs.GetState(state.ExploitId)
if diff := cmp.Diff(state, s, protocmp.Transform()); diff != "" {
t.Errorf("UpdateExploitVersion(): unexpected state diff: (-want +got):\n%s", diff)
}
state = &epb.ExploitState{
ExploitId: "1",
File: &fspb.FileInfo{Uuid: "2"},
Config: &epb.ExploitConfiguration{
Entrypoint: "./kek2",
IsArchive: true,
},
}
_, err = cs.UpdateExploitVersion(state)
require.NoError(t, err)
require.Len(t, cs.States(), 1)
require.EqualValues(t, 2, state.Version)
s, _ = cs.GetState(state.ExploitId)
if diff := cmp.Diff(state, s, protocmp.Transform()); diff != "" {
t.Errorf("UpdateExploitVersion(): unexpected state diff: (-want +got):\n%s", diff)
}
}
func TestCachedStorage_UpdateExploitVersionDB(t *testing.T) {
db, cleanup := testDB()
defer cleanup()
cs, err := NewStorage(db)
require.NoError(t, err)
state := &epb.ExploitState{
ExploitId: "1",
File: &fspb.FileInfo{Uuid: "1"},
Config: &epb.ExploitConfiguration{
Entrypoint: "./kek",
IsArchive: false,
},
}
_, err = cs.UpdateExploitVersion(state)
require.NoError(t, err)
require.NoError(t, cs.readDB())
require.Len(t, cs.States(), 1)
}
// Проверка чтения кешированного хранилища из базы.
func TestCachedStorage_readDB(t *testing.T) {
db, cleanup := testDB()
defer cleanup()
state := &epb.ExploitState{
ExploitId: "1",
Version: 1,
Config: &epb.ExploitConfiguration{
Entrypoint: "./kek",
IsArchive: false,
},
}
cs, err := NewStorage(db)
require.NoError(t, err)
require.NoError(t, cs.bdb.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(stateBucketKey))
stateBytes, err := proto.Marshal(state)
require.NoError(t, err)
stateKey := []byte(fmt.Sprintf("%s:%d", state.ExploitId, state.Version))
if err := b.Put(stateKey, stateBytes); err != nil {
return fmt.Errorf("setting state in db: %w", err)
}
return nil
}))
require.NoError(t, cs.readDB())
if diff := cmp.Diff(state, cs.stateCache["1"], protocmp.Transform()); diff != "" {
t.Errorf("readDB(): unexpected diff for exploit with id = 1")
}
}
@@ -0,0 +1,56 @@
package exploits
import (
"sync"
"time"
)
const beatThreshold = 3
func newVisitsMap() *visitsMap {
return &visitsMap{
visits: make(map[string]time.Time),
}
}
type visitsMap struct {
visits map[string]time.Time
m sync.Mutex
}
func (vm *visitsMap) Add(cid string) {
vm.m.Lock()
defer vm.m.Unlock()
vm.visits[cid] = time.Now()
}
// MarkInvalid сбрасывает время клиента, чтобы следующий вызов Invalidate удалил его.
func (vm *visitsMap) MarkInvalid(cid string) {
vm.m.Lock()
defer vm.m.Unlock()
if _, ok := vm.visits[cid]; !ok {
return
}
vm.visits[cid] = time.Unix(0, 0)
}
func (vm *visitsMap) Invalidate(now time.Time, pingEvery time.Duration) (alive, dead []string) {
vm.m.Lock()
defer vm.m.Unlock()
for k, v := range vm.visits {
if v.Add(pingEvery * beatThreshold).Before(now) {
delete(vm.visits, k)
dead = append(dead, k)
} else {
alive = append(alive, k)
}
}
return alive, dead
}
func (vm *visitsMap) Size() int {
vm.m.Lock()
defer vm.m.Unlock()
return len(vm.visits)
}
@@ -0,0 +1,102 @@
package exploits
import (
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/c4t-but-s4d/neo/v2/pkg/testutils"
)
func TestVisitsMap_Invalidate(t *testing.T) {
generate := func(m map[string]time.Time) *visitsMap {
vm := newVisitsMap()
vm.visits = m
return vm
}
for _, tc := range []struct {
vm *visitsMap
dur string
now time.Time
want []string
}{
{
vm: generate(map[string]time.Time{"1": time.Unix(10, 0), "2": time.Unix(30, 0)}),
dur: "5s",
now: time.Unix(35, 0),
want: []string{"1"},
},
{
vm: generate(map[string]time.Time{"1": time.Unix(10, 0), "2": time.Unix(30, 0)}),
dur: "50s",
now: time.Unix(35, 0),
want: []string{},
},
{
vm: generate(map[string]time.Time{"1": time.Unix(10, 0), "2": time.Unix(30, 0)}),
dur: "1s",
now: time.Unix(35, 0),
want: []string{"1", "2"},
},
{
vm: generate(map[string]time.Time{"1": time.Unix(10, 0), "2": time.Unix(30, 0)}),
dur: "5s",
now: time.Unix(15, 0),
want: []string{},
},
} {
d, _ := time.ParseDuration(tc.dur)
_, invalid := tc.vm.Invalidate(tc.now, d)
if diff := cmp.Diff(tc.want, invalid, cmpopts.SortSlices(testutils.LessString), cmpopts.EquateEmpty()); diff != "" {
t.Errorf("Invalidate() ids mismatch (-want +got):\n%s", diff)
}
}
}
func Test_visitsMap_MarkForDeletion(t *testing.T) {
generate := func(m map[string]time.Time) *visitsMap {
vm := newVisitsMap()
vm.visits = m
return vm
}
for _, tc := range []struct {
vm *visitsMap
dur string
now time.Time
mark []string
want []string
}{
{
vm: generate(map[string]time.Time{"1": time.Unix(900, 0), "2": time.Unix(995, 0)}),
dur: "5s",
now: time.Unix(1000, 0),
mark: []string{"2"},
want: []string{"1", "2"},
},
{
vm: generate(map[string]time.Time{"1": time.Unix(900, 0), "2": time.Unix(995, 0)}),
dur: "100s",
now: time.Unix(1000, 0),
mark: []string{"1"},
want: []string{"1"},
},
{
vm: generate(map[string]time.Time{"1": time.Unix(900, 0), "2": time.Unix(995, 0)}),
dur: "100s",
now: time.Unix(1000, 0),
mark: []string{"1", "2"},
want: []string{"1", "2"},
},
} {
d, _ := time.ParseDuration(tc.dur)
for _, cid := range tc.mark {
tc.vm.MarkInvalid(cid)
}
_, invalid := tc.vm.Invalidate(tc.now, d)
if diff := cmp.Diff(tc.want, invalid, cmpopts.SortSlices(testutils.LessString), cmpopts.EquateEmpty()); diff != "" {
t.Errorf("MarkInvalid() ids mismatch (-want +got):\n%s", diff)
}
}
}