- Closes#712.
- Replace synchronous `write()` calls in
`BidirectionalRelay` with non-blocking I/O
and `DispatchSourceWrite` backpressure
handling. Under concurrent vsock proxy load,
a single blocked write on the shared serial
dispatch queue would freeze all relay
connections permanently, including unrelated
new connections.
- Set relay file descriptors to `O_NONBLOCK`
and handle `EAGAIN` by suspending reads and
installing a write source to drain pending data.
- Give each `BidirectionalRelay` its own serial queue
instead of sharing one from `UnixSocketRelayManager`,
eliminating cross-connection blocking.
- Resume suspended read sources before cancelling
in `stop()` — GCD does not deliver cancel handlers
on suspended dispatch sources, which caused file
descriptor and memory leaks on teardown under
backpressure.
- Guard-unwrap `buf.baseAddress` in
`drainPendingWrite`.
- Closes#744
- Adds the initial `FilePathOps` utility type
- Adds the `absolutePath` implementation
- Adds the `FilePathOpsTests` file and initial test cases
- Closes#745.
- Facilitates TOCTOU-safe recursion over directory contents.
- Replace FileDescriptor extensions with a static utility type to
prevent potential namespacing issues as this project and Swift evolve.
This issue doesn't affect any of our existing products. This is a
preemptive fix for downstream consumers of EXT4.format where, in some
platforms, leading `//` in the path could get resolved into a FileTree
that looks like this
```sh
/
└── /
└── usr
```
Replace the old platform-gated Signals helper in ContainerizationOS with
a Signal struct in Containerization. Signal provides named constants for
common signals (.kill, .term, etc.), platform-specific namespaces
(Signal.Linux for rtmin/stkflt/pwr, Signal.Darwin for emt/info), string
parsing, and ExpressibleByIntegerLiteral support.
LinuxContainer, LinuxProcess, and LinuxPod kill APIs now take Signal
instead of raw Int32.
Add `Stat` RPC to vminitd.
`Stat` RPC is used to stat file system objects in the VM. It accepts the
path to the object (resolved against VM root) and returns the stat
result.
Now that we can run this project on linux, lets add some unit tests for
the surfaces that don't..
This additionally changes delete to throw in most cases. I don't really
see how masking these errors is ideal.
This helps on binary size if we can successfully get all Foundation
imports out of our dep chain. It seems Foundation brings in a 30MiB ICU
blob, which bloats vmexec and vminitd.
Related to https://github.com/apple/containerization/issues/606
To make sure the project (and many linux specific libraries) builds on
linux lets add a linux step to build for both musl and glibc. Eventually
this will run unit tests as well. This change needs a bit more libc
agnostic-ifying work to make sure things work for both libcs.
- Will be used by the fix for apple/container#1253.
- We use a common keychain ID between the `container CLI and
`container-core-images`, but right now keychain entries created by the
CLI must be opted-in for `container-core-images`.
- Using an access group with a notarized application should give both
apps automatic access to the keychain.
Closes#256
If the target of the uds proxy goes through a symlink (/var/run) we had
the same bug we had with mounts previously where we'd follow this and if
the resolved path existed in the root of the VM we'd end up mounting
there. Fix this by plopping the sockets in a holding spot and then bind
mounting them in (which has the correct resolution logic).
Today we don't resolve symlinks relative to the rootfs of the container
as ContainerizationOS.Mount did not handle this. This means trying to
mount something at /var/run (which typically is a symlink to /run in
most cases) would resolve to /run in the root of the VM. This change
adds some logic to handle this.
```
➜ ./bin/cctl run --kernel bin/kernel.arm64 --mount /Users/dcantah/foo:/var/run/foo bash
root@sandbox-vm:/# ls var/run/foo/
howdy
```
There are some workloads that benefit from having a "true" init process
that reaps zombies. This change implements a minimal init as part of
vminitd and exposes an API to be able to use this init process in our
containers. signals will be forwarded, any child procs will be reaped
and the exit code of the actual workload will be propagated. The
LinuxContainer/LinuxPod API is a very simple bool to ask to use this as
our init process, and the init simply spawns whatever command you want
as a child underneath this.
```
➜ ./bin/cctl run --kernel bin/kernel.arm64 --init
/ # ps aux
PID USER TIME COMMAND
1 root 0:00 /.cz-init -- /bin/sh
2 root 0:00 /bin/sh
3 root 0:00 ps aux
```
- Downgrades a warning to the debug level in `BidirectionalRelay`
because the shutdown syscall isn't supported for certain socket types
- Rethrows an error if we can't start a socket relay
- Adds a public method to wait for the relay to complete when both
directions close
- Improves error handling
- Moves `UnixSocketRelayManager` into a separate file
- Renames `SocketRelay` to `UnixSocketRelay`
- Adds logs at the info level after converting other logs to the debug
level previously
Changes:
- Refactors a bidirectional relay into a new class
- Makes the unique identifier for a socket configuration public
Bug fixes:
- Fixes a bug where partial writes didn't advance the pointer
- Fixes a buffer memory leak
- Fixes error messages
- Fixes log messages
- Fixes log levels
- Add a `list` function that is needed for the `container registry list`
command
- Updates to `KeychainHelper` and `KeychainQuery` variable/parameter
names
- Updates to test cases
Add in a small bit to create an empty file if we're asking for a single
file bind mount. This also resolves a bug with us using the wrong target
path in one of the mount variants.
* Admit only valid OCI layout files when loading image.
- Adds `AdmissionMapper` protocol for validating archive
member paths and normalizing them to relative paths
under the extraction root directory.
- Renames `Reader.swift` to `ArchiveReader.swift` to
match type name.
- Rework `TempDir` to address `NSString.utf8String`
deprecation warning in Swift 6.2.3.
- Rework `ArchiveReader.extractContent()` to use an
`AdmissionMapper` to validate and remap archive
members before extracting.
- Adds `IdentityAdmissionWrapper` for naive extraction.
- Adds `NoSymlinkAdmissionWrapper` that only extracts
regular files and directories under the extraction root.
- Adds `OCIImageAdmissionWrapper` that only extracts
valid OCI image layout paths.
- Use `OCIImageAdmissionWrapper` for `cctl image load`
and print rejected paths.
* PR feedback.
* Adds public init() for TrustedAdmissionMapper.
* Replace AdmissionMapper with more secure extraction.
- Adds FileDescriptor.mkdirSecure() to prevent
root escapes on member pathnames, and to prevent
symlink traversal.
- Adds FileDescriptor.unlinkRecursive() to
facilitate overwrites when there are multiple
archive entries with the same member path.
- Adds FileDescriptor.validateSymlinkTargetInRoot()
to validate that extracted symlink targets do
not escape the root.
- Rewrite ArchiveReader.extractContents() to use
secure path functions.
* Remove unneeded symlink check, rename files.
* Simplify the lexical normalizer workaround.
* Reject member paths containing parent traversal components.
* Remove unused lexical normalization workaround.
* Fix leaking fds, extract absolute members as relative.
Add support for parent death signal (pdeathSignal) to ensure child
processes receive a signal when the parent process dies. This addresses
the FIXME comment in Runc.execute().
## Changes
- Add pdeathSignal field to exec_command_attrs C struct
- Implement prctl(PR_SET_PDEATHSIG) in child process handler (Linux
only)
- Expose pdeathSignal through Command.Attrs Swift API
- Wire up pdeathSignal in Runc.execute() to remove FIXME
## Implementation Details
The implementation uses Linux-specific prctl() to set the parent death
signal, ensuring proper cleanup when parent processes terminate. The
feature is conditionally compiled for Linux only, maintaining
compatibility with other platforms.
* on glibc, swift expects that the msg_controllen is type Int
* on glibc, socket shutdown options should be an Int32
Signed-off-by: Kathryn Baldauf <k_baldauf@apple.com>
- We're already setting the default `HOME` and `TERM`. Setting the
default `PATH` as well seems reasonable.
- This PR also fixes the bug in retrieving the `PATH` value (`PATH=` has
to be removed, and `=` should be allowed in folder names).
The mount flags are defined as `Int`s for musl but as `Int32`s for
glibc, despite the mount methods expecting `Int32` for both. This was
leading to build errors when building with glibc like:
```
| "async": .init(true, MS_SYNCHRONOUS),
| `- error: cannot convert value of type 'Int' to expected type 'Int32'
```
This PR allows for different Int sizes based on if we're building for
glibc or not to avoid this build error.
Signed-off-by: Kathryn Baldauf <k_baldauf@apple.com>
This class does not work for glibc due to missing flags and methods.
This PR removes the ability to load the `Epoll` class when using glibc
for now.
Signed-off-by: Kathryn Baldauf <k_baldauf@apple.com>
- Current implementation shuts down everything as soon as EOF is
detected on DispatchSourceRead for the relay. This is problematic for,
say an HTTP request where the client makes a request, and calls
`shutdown(fd, SHUT_WR)` to close the send side, but it expects to be
able to keep calling `recv()` to get the response.
- Changed cancel handlers so that the one that sees that both sources
have been cancelled then closes both the UDS and vsock fds.
- Updated vminitd VsockProxy to also do `shutdown(fd, SHUT_WR)` for read
hangup or EOF, and only close the underlying fds and unwire pollers on
full hangup, broken pipe, error, or when both sides half-close.
Fixes an issue first described in
https://github.com/apple/container/issues/740.
Previously the initial process of the container was using vminitd's
environment variables to find the target executable. This PR updates the
code to use the container's configured environment for the initial
process instead. The behavior of an exec in a container should be the
same as before.
Signed-off-by: Kathryn Baldauf <k_baldauf@apple.com>
Improves https://github.com/apple/containerization/pull/245. A potential
deadlock risk was not proven. This PR moves the closing operation inside
the lock to prevent leaking an unclosed handle in case of an error.
While individual accesses were properly mutex-protected, the logical
operations were not atomic, leading to a potential inconsistency in a
multi-threaded environment. Multiple separate `state.withLock` calls
created race windows. With the proposed changes, single atomic
operations check and update the state together.
While reviewing test coverage, I noticed a couple of minor issues:
- 0 is non-negative - allow for zero memory
- we should likely use lstat instead of stat for file info
- we should check for empty name parameter
---------
Signed-off-by: Eric Ernst <eric_ernst@apple.com>