mirror of
https://github.com/apple/container.git
synced 2026-09-28 01:46:25 -04:00
Container-to-host networking. (#1078)
- Closes #346. - This PR enables connecting host's localhost ports from containers. - It adds an option `--localhost <localhost>` to DNS create command, after which the packets heading ip address in container are redirected to localhost in host machine. Packet filter rule is added and deleted along with the creation and deletion of localhost domain.
This commit is contained in:
@@ -33,6 +33,7 @@ extension APIServer {
|
||||
)
|
||||
|
||||
static let listenAddress = "127.0.0.1"
|
||||
static let localhostDNSPort = 1053
|
||||
static let dnsPort = 2053
|
||||
|
||||
@Flag(name: .long, help: "Enable debug logging")
|
||||
@@ -97,13 +98,33 @@ extension APIServer {
|
||||
let hostsQueryValidator = StandardQueryValidator(handler: compositeResolver)
|
||||
let dnsServer: DNSServer = DNSServer(handler: hostsQueryValidator, log: log)
|
||||
log.info(
|
||||
"starting DNS host query resolver",
|
||||
"starting DNS resolver for container hostnames",
|
||||
metadata: [
|
||||
"host": "\(Self.listenAddress)",
|
||||
"port": "\(Self.dnsPort)",
|
||||
]
|
||||
)
|
||||
try await dnsServer.run(host: Self.listenAddress, port: Self.dnsPort)
|
||||
|
||||
}
|
||||
|
||||
// start up realhost DNS
|
||||
group.addTask {
|
||||
let localhostResolver = LocalhostDNSHandler(log: log)
|
||||
try localhostResolver.monitorResolvers()
|
||||
|
||||
let nxDomainResolver = NxDomainResolver()
|
||||
let compositeResolver = CompositeResolver(handlers: [localhostResolver, nxDomainResolver])
|
||||
let hostsQueryValidator = StandardQueryValidator(handler: compositeResolver)
|
||||
let dnsServer: DNSServer = DNSServer(handler: hostsQueryValidator, log: log)
|
||||
log.info(
|
||||
"starting DNS resolver for localhost",
|
||||
metadata: [
|
||||
"host": "\(Self.listenAddress)",
|
||||
"port": "\(Self.localhostDNSPort)",
|
||||
]
|
||||
)
|
||||
try await dnsServer.run(host: Self.listenAddress, port: Self.localhostDNSPort)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Copyright © 2026 Apple Inc. and the container project authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ContainerizationError
|
||||
import Foundation
|
||||
import Logging
|
||||
|
||||
public class DirectoryWatcher {
|
||||
public let directoryURL: URL
|
||||
|
||||
private let monitorQueue: DispatchQueue
|
||||
private var source: DispatchSourceFileSystemObject?
|
||||
|
||||
private let log: Logger
|
||||
|
||||
init(directoryURL: URL, log: Logger) {
|
||||
self.directoryURL = directoryURL
|
||||
self.monitorQueue = DispatchQueue(label: "monitor:\(directoryURL.path)")
|
||||
self.log = log
|
||||
}
|
||||
|
||||
public func startWatching(handler: @escaping ([URL]) throws -> Void) throws {
|
||||
guard source == nil else {
|
||||
throw ContainerizationError(.invalidState, message: "already watching on \(directoryURL.path)")
|
||||
}
|
||||
|
||||
do {
|
||||
let files = try FileManager.default.contentsOfDirectory(atPath: directoryURL.path)
|
||||
try handler(files.map { directoryURL.appending(path: $0) })
|
||||
} catch {
|
||||
throw ContainerizationError(.invalidState, message: "failed to start watching on \(directoryURL.path)")
|
||||
}
|
||||
|
||||
log.info("starting directory watcher for \(directoryURL.path)")
|
||||
|
||||
let descriptor = open(directoryURL.path, O_EVTONLY)
|
||||
|
||||
source = DispatchSource.makeFileSystemObjectSource(
|
||||
fileDescriptor: descriptor,
|
||||
eventMask: .write,
|
||||
queue: monitorQueue
|
||||
)
|
||||
|
||||
source?.setEventHandler { [weak self] in
|
||||
guard let self else { return }
|
||||
|
||||
do {
|
||||
let files = try FileManager.default.contentsOfDirectory(atPath: directoryURL.path)
|
||||
try? handler(files.map { directoryURL.appending(path: $0) })
|
||||
} catch {
|
||||
self.log.info("failed to run handler for \(directoryURL.path)")
|
||||
}
|
||||
}
|
||||
|
||||
source?.resume()
|
||||
}
|
||||
|
||||
deinit {
|
||||
guard let source else {
|
||||
return
|
||||
}
|
||||
|
||||
source.cancel()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Copyright © 2026 Apple Inc. and the container project authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ContainerAPIClient
|
||||
import ContainerPersistence
|
||||
import ContainerizationError
|
||||
import DNS
|
||||
import DNSServer
|
||||
import Foundation
|
||||
import Logging
|
||||
|
||||
class LocalhostDNSHandler: DNSHandler {
|
||||
private let ttl: UInt32
|
||||
private let watcher: DirectoryWatcher
|
||||
|
||||
private var dns: [String: IPv4]
|
||||
|
||||
public init(resolversURL: URL = HostDNSResolver.defaultConfigPath, ttl: UInt32 = 5, log: Logger) {
|
||||
self.ttl = ttl
|
||||
|
||||
self.watcher = DirectoryWatcher(directoryURL: resolversURL, log: log)
|
||||
self.dns = [:]
|
||||
}
|
||||
|
||||
public func monitorResolvers() throws {
|
||||
try self.watcher.startWatching { fileURLs in
|
||||
var dns: [String: IPv4] = [:]
|
||||
let regex = try Regex(HostDNSResolver.localhostOptionsRegex)
|
||||
|
||||
for file in fileURLs.filter({ $0.lastPathComponent.starts(with: HostDNSResolver.containerizationPrefix) }) {
|
||||
let content = try String(contentsOf: file, encoding: .utf8)
|
||||
|
||||
if let match = content.firstMatch(of: regex),
|
||||
let ipv4 = IPv4(String(match[1].substring ?? ""))
|
||||
{
|
||||
let name = String(file.lastPathComponent.dropFirst(HostDNSResolver.containerizationPrefix.count))
|
||||
dns[name + "."] = ipv4
|
||||
}
|
||||
}
|
||||
self.dns = dns
|
||||
}
|
||||
}
|
||||
|
||||
public func answer(query: Message) async throws -> Message? {
|
||||
let question = query.questions[0]
|
||||
var record: ResourceRecord?
|
||||
switch question.type {
|
||||
case ResourceRecordType.host:
|
||||
if let ip = dns[question.name] {
|
||||
record = HostRecord<IPv4>(name: question.name, ttl: ttl, ip: ip)
|
||||
}
|
||||
case ResourceRecordType.host6:
|
||||
return Message(
|
||||
id: query.id,
|
||||
type: .response,
|
||||
returnCode: .noError,
|
||||
questions: query.questions,
|
||||
answers: []
|
||||
)
|
||||
case ResourceRecordType.nameServer,
|
||||
ResourceRecordType.alias,
|
||||
ResourceRecordType.startOfAuthority,
|
||||
ResourceRecordType.pointer,
|
||||
ResourceRecordType.mailExchange,
|
||||
ResourceRecordType.text,
|
||||
ResourceRecordType.service,
|
||||
ResourceRecordType.incrementalZoneTransfer,
|
||||
ResourceRecordType.standardZoneTransfer,
|
||||
ResourceRecordType.all:
|
||||
return Message(
|
||||
id: query.id,
|
||||
type: .response,
|
||||
returnCode: .notImplemented,
|
||||
questions: query.questions,
|
||||
answers: []
|
||||
)
|
||||
default:
|
||||
return Message(
|
||||
id: query.id,
|
||||
type: .response,
|
||||
returnCode: .formatError,
|
||||
questions: query.questions,
|
||||
answers: []
|
||||
)
|
||||
}
|
||||
|
||||
guard let record else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return Message(
|
||||
id: query.id,
|
||||
type: .response,
|
||||
returnCode: .noError,
|
||||
questions: query.questions,
|
||||
answers: [record]
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user