54 lines
1.7 KiB
Swift
54 lines
1.7 KiB
Swift
//
|
|
// IdentityStore.swift
|
|
// punchnet
|
|
//
|
|
// Created by 安礼成 on 2026/2/5.
|
|
//
|
|
import Foundation
|
|
import NIO
|
|
|
|
actor IdentityStore {
|
|
typealias IdentityID = UInt32
|
|
|
|
nonisolated private let alloctor = ByteBufferAllocator()
|
|
|
|
private let publisher: SnapshotPublisher<IdentitySnapshot>
|
|
private var identityMap: [IdentityID: IdentityRuleMap] = [:]
|
|
|
|
init(publisher: SnapshotPublisher<IdentitySnapshot>) {
|
|
self.publisher = publisher
|
|
}
|
|
|
|
func apply(policyResponse: SDLPolicyResponse) {
|
|
let id = policyResponse.srcIdentityID
|
|
let version = policyResponse.version
|
|
|
|
guard self.identityMap[id] == nil || ((self.identityMap[id]?.version ?? 0) < version) else {
|
|
return
|
|
}
|
|
|
|
// 判断一下是否接受完成
|
|
var buffer = alloctor.buffer(bytes: policyResponse.rules)
|
|
var ruleMap: [UInt8: [UInt16: Bool]] = [:]
|
|
while true {
|
|
guard let proto = buffer.readInteger(endianness: .big, as: UInt8.self),
|
|
let port = buffer.readInteger(endianness: .big, as: UInt16.self) else {
|
|
break
|
|
}
|
|
ruleMap[proto, default: [:]][port] = true
|
|
}
|
|
self.identityMap[id] = IdentityRuleMap(version: version, ruleMap: ruleMap)
|
|
|
|
SDLLogger.shared.log("[IdentitySession] get compile Snapshot rules nums: \(self.identityMap[id]?.ruleMap.count), success: \(self.identityMap[id]?.isAllow(proto: 1, port: 80))")
|
|
|
|
// 发布新的快照信息
|
|
let snapshot = compileSnapshot()
|
|
publisher.publish(snapshot)
|
|
}
|
|
|
|
private func compileSnapshot() -> IdentitySnapshot {
|
|
return IdentitySnapshot(identityMap: identityMap)
|
|
}
|
|
|
|
}
|