45 lines
1.4 KiB
Swift
45 lines
1.4 KiB
Swift
//
|
|
// PolicyRuntime.swift
|
|
// Tun
|
|
//
|
|
// Created by Codex on 2026/5/21.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
struct PolicyRuntime: @unchecked Sendable {
|
|
private let policyRuleSnapshot: PolicyRuleSnapshot
|
|
private let flowSessionManager: SDLFlowSessionManager
|
|
|
|
init(policyRuleSnapshot: PolicyRuleSnapshot, flowSessionManager: SDLFlowSessionManager) {
|
|
self.policyRuleSnapshot = policyRuleSnapshot
|
|
self.flowSessionManager = flowSessionManager
|
|
}
|
|
|
|
func allowsInbound(srcIdentityID: UInt32, ipPacket: IPPacket) -> Bool {
|
|
if let reverseFlowSession = ipPacket.flowSession()?.reverse(),
|
|
self.flowSessionManager.hasSession(reverseFlowSession) {
|
|
self.flowSessionManager.updateSession(reverseFlowSession)
|
|
return true
|
|
}
|
|
|
|
return self.allowsByRule(srcIdentityID: srcIdentityID, ipPacket: ipPacket)
|
|
}
|
|
|
|
private func allowsByRule(srcIdentityID: UInt32, ipPacket: IPPacket) -> Bool {
|
|
let ruleMap = self.policyRuleSnapshot.lookup(srcIdentityID)
|
|
let proto = ipPacket.header.proto
|
|
|
|
switch ipPacket.transportPacket {
|
|
case .tcp(let tcpPacket):
|
|
return ruleMap?.isAllow(proto: proto, port: tcpPacket.header.dstPort) ?? false
|
|
case .udp(let udpPacket):
|
|
return ruleMap?.isAllow(proto: proto, port: udpPacket.dstPort) ?? false
|
|
case .icmp:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
}
|