punchnet-macos/Tun/Policy/PolicyRuntime.swift
2026-05-21 14:39:41 +08:00

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 flowSessionTable: FlowSessionTable
init(policyRuleSnapshot: PolicyRuleSnapshot, flowSessionTable: FlowSessionTable) {
self.policyRuleSnapshot = policyRuleSnapshot
self.flowSessionTable = flowSessionTable
}
func allowsInbound(srcIdentityID: UInt32, ipPacket: IPPacket) -> Bool {
if let reverseFlowSession = ipPacket.flowSession()?.reverse(),
self.flowSessionTable.hasSession(reverseFlowSession) {
self.flowSessionTable.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
}
}
}