Skip to content

Commands and files

This page tells you how the daemon runs a command in a sandbox and how it reads and writes files there. It is for a contributor who must change internal/sandbox/run.go or internal/sandbox/files.go.

The daemon does not open a network connection to a sandbox. For each operation, the daemon tells the engine to start the helper in the container. The daemon and the helper then send data on the standard input and the standard output of that process. The page helper.md gives the full frame protocol. The page engine.md gives the Exec call of the engine.

A client can get the result of a command in two ways.

Manager.Run Manager.Exec
Answer One Result when the command ends A Process that gives one Event after the other
HTTP POST /v1/sandboxes/{id}/exec with "stream": false The same route with "stream": true
Output Kept in memory, with a limit for each stream Sent to the client while the command runs, with no limit
Connection The kept connection when possible, see kept-connection.md One engine exec of guest run for each command
Other callers The tools sandbox_exec in internal/tools/tools.go None in the daemon

Run first calls runKept. If runKept reports handled, Run returns that answer. If not, Run calls Exec and collects the events itself. This page describes the path through Exec. The other path gives the same Result.

The client sends a guest.RunSpec. The type is in internal/guest/proto.go.

Field JSON name Meaning
Cmd cmd A command line. The helper runs it with /bin/bash -c, or with /bin/sh -c when the image has no /bin/bash.
Argv argv A program and its arguments. The helper starts it directly, without a shell.
Cwd cwd The directory in which the command starts.
Env env Variables that the helper adds to its own environment for the command.
TimeoutMS timeout_ms The time limit of the command in milliseconds. Zero means no limit.
Stdin stdin When true, the helper keeps the standard input of the command open for data.

Manager.Exec refuses a spec that has both Cmd and Argv, or that has none of them. It also refuses a negative TimeoutMS. The error is an InvalidError, and the API sends status 400 with the code invalid_request.

The HTTP API uses timeout_seconds. The function seconds in internal/api/server.go changes it to milliseconds. A positive value is never less than one millisecond after the change, because zero means “no limit”.

sequenceDiagram
participant C as Client
participant M as Manager
participant E as Engine
participant H as Helper (run mode)
participant P as Command
C->>M: Run or Exec (spec)
M->>M: use(id): inUse + 1
M->>E: Exec [/.boxfork/guest, run]
E->>H: start the helper in the container
M->>H: FrameSpec (JSON spec)
H->>P: start in a new session
H-->>M: FrameStarted (process number)
M->>H: FrameStdin, then FrameStdinEOF
P-->>H: output
H-->>M: FrameStdout and FrameStderr
P-->>H: exit
H-->>M: FrameExit (JSON exit)
M->>E: close the stream: inUse - 1
M-->>C: Result, or the last event

The steps in the code are these:

  1. Manager.Exec does a check of the spec.
  2. Manager.use finds the container and adds one to inUse. See “The use counter” below.
  3. The engine starts /.boxfork/guest run in the container and returns an engine.ExecStream.
  4. released changes the Closer of the stream. A close of the stream now also ends the use.
  5. Exec writes the spec as one FrameSpec frame.
  6. Process.Next reads one frame and returns one Event: started, stdout, stderr or exit.
  7. After the exit event, Process.Next returns io.EOF.
  8. The caller closes the Process. The close ends the engine stream.

Process.Next ignores a frame type that it does not know. The comment in the code gives the reason: a newer helper can send new frame types.

The helper starts the command in a new session (Setsid). The command then has its own process group, and a signal to the group gets to each process that the command started. The function start in internal/guest/run.go does this.

Run sets spec.Stdin to true when the caller gives input, also when the input is empty. Run sends the input from a separate goroutine and then sends FrameStdinEOF. Process.Write cuts the input into frames of a maximum of 256 KiB. When spec.Stdin is false, the command reads from /dev/null and does not wait for input.

The HTTP API accepts the input as stdin (text) or as stdin_base64. It refuses a request that has both. The JSON body of a request has a maximum of 8 MiB (maxJSONBody). This is also the limit for the input of a command through the API.

Run keeps the output in two capped buffers, one for the standard output and one for the standard error. Each buffer keeps the first limit bytes. capped.add drops the bytes after the limit and sets truncated. Result.Truncated is true when one of the two buffers dropped bytes. Run continues to read frames after the limit. Thus the command does not stop, and its exit status still arrives.

capped.text replaces each byte sequence that is not valid UTF-8 with the character U+FFFD. A limit that cuts a character in two parts thus gives U+FFFD at the end of the text.

The caller gives the limit:

Caller Limit for each stream Name
The HTTP API 4 MiB Server.MaxOutput, set in Server.Handler
The tool sandbox_exec 2 MiB captureBytes in internal/tools/tools.go

Exec has no limit. The API sends each stdout and stderr event to the client as one JSON line, with the data in base64.

Three different time limits can stop a command.

Limit Who applies it Result
timeout_ms of the spec The helper. A timer sends SIGKILL to the process group. A normal answer with timed_out true, exit_code 137 and signal SIGKILL.
The timeout of the sandbox The sweep of the daemon. It kills the sandbox. See “When the sandbox goes away”.
The client stops the request The daemon. context.AfterFunc closes the stream. The helper reads the end of its input and sends SIGKILL to the process group.

The daemon has no timer of its own for timeout_ms. A command without timeout_ms runs until it ends or until one of the other two limits stops it. A command does not extend the timeout of its sandbox. manager.md describes the timeout of a sandbox.

The helper makes the guest.Exit value in command.wait.

Case exit_code signal timed_out error
The command ends Its exit status empty false empty
A signal stops the command 128 plus the number of the signal For example SIGTERM false empty
The timer of timeout_ms stops the command 137 SIGKILL true empty
The helper cannot start the command 127 empty false The reason
The wait for the command fails in a different way 1 empty false The reason

After the command ends, the helper reads output for a maximum of 300 ms more (drainGrace). A child process in the background that holds the output pipe open does not keep the command open longer than that.

Process.Signal sends a FrameSignal frame. guest.ParseSignal accepts TERM, SIGTERM, term or 15. No route of the HTTP API calls Process.Signal. Only the tests use it.

When the sandbox goes away while a command runs

Section titled “When the sandbox goes away while a command runs”

The engine ends the stream when the container goes. Process.Next then gets an error from guest.ReadFrame. Process.lost makes the message “the command’s connection to the sandbox was lost”. It adds the standard error of the helper when there is some.

Run then calls Manager.cutOff. cutOff looks at the record: if the record is gone or has dying set, the answer is ErrNotFound. Exec has no such step, because the API already sent status 200 before the first event.

What happens Client of Run Client of Exec (stream)
A client kills the sandbox HTTP 404, code sandbox_not_found A last line {"type":"error","message":"the command's connection to the sandbox was lost"}
The sandbox gets to its timeout The same as for a kill The same as for a kill
The container stops, but the record stays HTTP 500, code internal, with the message above The same error line
The sandbox is paused before the command starts HTTP 409, code sandbox_paused HTTP 409, code sandbox_paused
The sandbox is suspended before the command starts use wakes the sandbox, then the command runs The same
The client stops the request No answer: the client is gone No more lines

A pause does not close the stream of a command that already runs. The processes of the sandbox freeze, and the client waits until a resume or a kill. The timeout of a paused sandbox does not run.

When the engine reports that the container does not exist, Manager.engineErr calls forget and returns ErrNotFound. The record of the sandbox goes with it.

The code has no field with the name busy. The record has two fields for this purpose: inUse and lastUsed. Both are in the record type in internal/sandbox/manager.go. Manager.use in internal/sandbox/suspend.go changes them.

  • inUse is the number of commands and file operations that are in progress in the sandbox.
  • lastUsed is the time when a command or a file operation last started or ended.

use does these steps under m.mu:

  1. If there is no record, or the record is hidden, return ErrNotFound.
  2. If the sandbox is paused, return ErrPaused.
  3. If the sandbox is suspended, release the lock, call wake and start again from step 1.
  4. Add one to inUse and return the container and a done function.

done subtracts one from inUse and sets lastUsed. A sync.Once makes sure that it does this only one time. released connects done to the close of the engine stream. Thus a stream that stays open keeps the sandbox in use. Examples are a streamed command and a file that the client did not read to the end.

Only the idle check for suspend reads these two fields (Manager.idle). See suspend.md. The state file does not contain them. After a restart of the daemon, each sandbox counts as used at the time of the restart.

Each file operation is one engine exec of /.boxfork/guest fs <spec>. Manager.fsOp starts it. The helper code is runFS in internal/guest/fs.go.

The spec is a guest.FSSpec with the fields op, path, to and mode. guest.EncodeFSSpec writes it as JSON and then as URL-safe base64, as the one argument of the helper. The helper answers with one line of JSON, a guest.FSHeader. The function answer reads this line.

Operation Manager function HTTP route What the helper does
read ReadFile GET /v1/sandboxes/{id}/files?path= Sends the header with size and mode, then exactly size bytes.
write WriteFile PUT /v1/sandboxes/{id}/files?path=&mode= Reads the body as frames, writes a temporary file, then renames it to the path.
stat Stat GET /v1/sandboxes/{id}/files/stat?path= Returns one Entry. It does not follow a symlink at the end of the path.
list ListDir GET /v1/sandboxes/{id}/files/list?path= Returns one Entry for each item in the directory. It does not go into subdirectories.
mkdir Mkdir POST /v1/sandboxes/{id}/files/mkdir Makes the directory and each parent that is missing, with mode 0755.
remove Remove DELETE /v1/sandboxes/{id}/files?path= Removes a file, or a directory and all that is in it. It refuses /.
rename Rename POST /v1/sandboxes/{id}/files/rename Makes the parent directories of the target, then renames.

An Entry has the fields name, path, type, size, mode and mtime. The type is file, dir, symlink or other. The API shows the mode as four octal digits.

sequenceDiagram
participant C as Client
participant M as Manager.ReadFile
participant E as Engine
participant H as Helper (fs mode)
C->>M: GET files?path=/work/a.txt
M->>M: use(id): inUse + 1
M->>E: Exec [/.boxfork/guest, fs, spec]
E->>H: start the helper
H->>H: stat, then open without block
H-->>M: {"ok":true,"size":n,"mode":m} and a new line
H-->>M: n bytes of the file
M-->>C: 200, Content-Length n, X-Boxfork-Mode
C->>M: read the body to the end
M->>E: close the stream: inUse - 1

ReadFile returns a FileReader. Its Reader is an io.LimitReader of size bytes, thus the daemon reads no more than the header promised. The caller must close the FileReader. The close ends the engine stream and the use of the sandbox.

The helper reads only a regular file. For a directory it answers is_directory. For a pipe, a device or a socket it answers invalid_argument. The helper does the stat before it opens the file, and it opens the file with O_NONBLOCK. The reason is in the code: to open a pipe without this flag waits for a writer.

A file in /proc or /sys reports a size of zero and is not empty. For a file with size zero, the helper reads the content first and then sends the real size. It refuses such a file when the content is larger than 16 MiB (maxSizeless).

For a file with a size, the helper sends exactly that number of bytes, also when the file becomes longer in that time.

sequenceDiagram
participant C as Client
participant M as Manager.WriteFile
participant E as Engine
participant H as Helper (fs mode)
C->>M: PUT files?path=/work/a.txt (body)
M->>M: use(id): inUse + 1
M->>E: Exec [/.boxfork/guest, fs, spec]
E->>H: start the helper
H->>H: make the parent directories and a temporary file
loop for each part of the body, maximum 256 KiB
M->>H: FrameStdin
H->>H: write to the temporary file
end
M->>H: FrameStdinEOF
H->>H: set the mode, close, rename to the path
H-->>M: {"ok":true,"size":n} and a new line
M->>E: close the stream: inUse - 1
M-->>C: 200 {"path": ..., "size": n}

The helper writes to a temporary file with the name .boxfork-write-* in the directory of the target. It renames the temporary file to the target only after the FrameStdinEOF frame. Thus a reader in the sandbox sees the old file or the new file, and never a part of the new file.

If the stream ends before FrameStdinEOF, the helper deletes the temporary file. WriteFile uses this: when it cannot read the body of the request, it returns and closes the stream without the end frame. WriteFile reads the body with Read and not with io.ReadFull. The comment gives the reason: an upload that stops early must stay an error.

The mode of the new file comes from these rules, in fsWrite:

  1. If the request gives a mode that is not zero, the helper uses its permission bits.
  2. If not, and the file exists, the helper keeps the permission bits of the file.
  3. If not, the mode is 0644.

When the helper finds an error before it reads the body, it first reads and drops all body frames (drainFrames). The daemon is then able to send the full body and to read the error after it. The cost is that the client sends the full body before it gets the error.

The helper makes each path absolute with filepath.Abs. A relative path is thus relative to the directory in which the engine starts the helper. The helper does not keep a path inside a base directory. A client can read and write each path that the user of the helper can read and write. This includes a mounted volume. See volumes.md.

fsOp starts the helper with an empty User in the engine.ExecSpec. The helper then runs as the user that the engine uses for the container, which the image sets. A file or a directory that the helper makes belongs to that user. In fs mode the helper never changes the owner of a file. A write replaces the target with a new file, thus the target gets the user of the helper as its owner.

The commands of Run and Exec also run as that user, because the helper is their parent process.

Limit Value Name and file
The payload of one frame 4 MiB guest.MaxFrame, internal/guest/proto.go
One input frame or one body frame from the daemon 256 KiB The literal 256<<10 in Process.Write and WriteFile
The output of Run through the API, for each stream 4 MiB Server.MaxOutput, internal/api/server.go
A JSON request body 8 MiB maxJSONBody, internal/api/server.go
One upload 4 GiB Server.MaxUpload, internal/api/server.go
The answer line of the helper 32 MiB maxAnswer, internal/sandbox/files.go
A file that reports size zero 16 MiB maxSizeless, internal/guest/fs.go
Standard error of the helper that the daemon keeps 16 KiB maxStderr, internal/engine/docker.go

boxfork serve has no flag for MaxOutput or MaxUpload. The values are the defaults in Server.Handler.

The helper sends {"ok":false,"code":...,"message":...} and the daemon makes an FSError from it. fsStatus in internal/api/server.go gives the HTTP status.

Code Cause HTTP status
not_found The path does not exist. 404
permission_denied The user of the helper has no permission. 403
is_directory A read or a write of a directory. 400
not_directory A part of the path is not a directory. 400
invalid_argument A bad spec, a read of a file that is not regular, a remove of /, or a rename without a target. 400
io_error Each other error of the operating system. 500
too_large The answer line is longer than maxAnswer. The daemon makes this code, not the helper. 422

Other errors are not an FSError:

  • An empty path gives an InvalidError from fsOp, and status 400.
  • An upload larger than MaxUpload gives an http.MaxBytesError, and status 413 with the code too_large.
  • A stream that ends before the answer line gives the message “the file operation’s connection to the sandbox was lost”. The status is 500.
  • An answer line that is not JSON, or that has a negative size, gives “bad answer from the sandbox helper”. The status is 500.

File operations do not call cutOff. When a client kills the sandbox in the middle of a file operation, the client of that operation gets status 500, not 404.

  • Each successful call of use has exactly one call of its done function, on each path, also on each error path.
  • The daemon reads a bounded quantity of data from the helper before it makes a decision. What sends the data runs in the sandbox, and the code in the sandbox can replace it.
  • Run returns ErrNotFound, and not a connection error, when the sandbox went away while the command ran.
  • Run gives the same Result on the kept connection and on its own connection. TestACommandIsAnsweredTheSameEitherWay holds this.
  • The helper sends FrameExit as the last frame of a command.
  • A write shows the full new file or the old file. It never shows a part.
  • An upload that stops early leaves no file and no temporary file.
  • A canceled request stops its command and all processes that the command started.
  • The state file contains no environment variables and no input of a command.
Failure What the code does
The engine cannot start the helper Exec or fsOp calls done and returns the error from engineErr.
The engine says that the container does not exist engineErr calls forget. The answer is ErrNotFound.
The write of the spec frame fails Exec closes the process and returns the error from Process.lost.
The helper sends a started or an exit frame that is not JSON Process.Next returns “bad frame from the sandbox helper”.
The helper cannot start the command The helper sends FrameExit with exit_code 127 and error. The HTTP status is 200.
The helper is gone when WriteFile sends a frame WriteFile reads the answer line. If the helper gave a reason, the client gets that reason.
A directory has too many items for one answer line answer returns too_large. The client cannot list that directory in one call.
The client stops a download The close of the FileReader closes the stream and ends the use.
  1. Read helper.md before you change a frame or a spec field.
  2. If you add a field to guest.RunSpec, give it a JSON name with omitempty.
  3. Make sure that a helper of an earlier build ignores the new field without an error.
  4. Read the field in start in internal/guest/run.go. Both run mode and serve mode use start.
  5. Add the field to execBody and to the exec handler in internal/api/server.go.
  6. If you change Run, make the same change in cmdConn.run in internal/sandbox/kept.go.
  7. Add a case to TestACommandIsAnsweredTheSameEitherWay for the new behavior.
  8. If you add a file operation, add a case to runFS and a function to files.go.
  9. Use simple when the new operation has no body. It closes the stream and ends the use.
  10. If the new operation keeps the stream open, call released and close the stream on each path.
  11. If the helper can send more data, put a limit on what the daemon reads.
  12. Add the error code to fsStatus if you add a code.
  13. Run make test.
  14. Run python3 -I scripts/ste_check.py --warnings on each page that you changed.

Caution: Do not change the meaning of a frame type that exists. A sandbox that a client created before an upgrade keeps its old helper, and the new daemon must still be able to talk to it.

The test engine runs the helper code in the test process. Thus a command in these tests is a real process on the test machine.

File Most important tests
internal/sandbox/manager_test.go TestCreateRunKill, TestStreamingExec, TestRunStdinTruncationAndCancel, TestFiles
internal/sandbox/kept_test.go TestACommandIsAnsweredTheSameEitherWay, TestACommandCutOffByItsSandboxBeingKilledIsToldThereIsNoSuchSandbox, TestACommandCutOffWhileItsSandboxLivesSaysItsConnectionWasLost
internal/sandbox/suspend_test.go TestAFileBeingReadKeepsItsSandbox, TestACommandDuringASuspension
internal/guest/guest_test.go TestRunCapturesOutputAndExitCode, TestRunTimeoutKillsTheCommand, TestRunSignalFrameReachesTheWholeGroup, TestRunLosingTheControlStreamKillsTheCommand, TestRunDoesNotWaitForBackgroundChildren, TestFSWriteModes, TestFSErrors, TestFSReadRefusesWhatIsNotARegularFile
internal/api/server_test.go TestExec, TestExecStream, TestHangingUpStopsTheCommand, TestFiles, TestATinyTimeoutIsNotNoTimeout
internal/api/hangup_test.go TestExecStdinThatIsNotText, TestADownloadCarriesTheFilesMode

The proof script scripts/proof/conn.sh does checks of commands on a real engine: input, exit status, timed_out, truncated and exit code 127.

  • The proof scripts ran on Docker with gVisor on arm64, in a nested virtual machine, and on Podman. Nothing ran on x86_64.
  • No test and no proof script ran a command or a file operation in a sandbox with an NVIDIA GPU.
  • No test measures an upload near the 4 GiB limit or an answer line near the 32 MiB limit on a real engine.
  • The helper applies timeout_ms inside the sandbox. Code in the sandbox that stops the helper also stops that timer. The daemon does not have a second timer.
  • The API accepts a mode up to 7777, and fsWrite keeps only the permission bits 0777. No test covers the higher bits.
  • No test covers a pause that occurs while a command runs.
  • This page did not examine the limit that an engine or a kernel puts on the length of the fs argument. A very long path can be longer than that limit.