bin/mcp-fs

filter: Statementstmt 51.5% 606 / 1175 Branchbran 26.2% 207 / 788 Conditioncond 15.4% 86 / 556 MC/DCmcdc 2.6% 8 / 301 Subroutinesub 61.4% 70 / 114 Podpod n/a totaltotal 33.3% 977 / 2934 CC 499 SCAR 72.3
CC
499
Cov
36%
fs_sandbox
8130.4
__ANON__
650.0
__ANON__
210.0
CRAP 1384.0
« lib/AnyEvent/MCP/Worker/IMAP.pm ↑ Summary blib/lib/AnyEvent/MCP/Permissions/Ask.pm »
1 #!/opt/bin/perl
2  
3 =head1 NAME
4  
5 mcp-fs - filesystem and command tools with optional sandboxing
6  
7 =head1 SYNOPSIS
8  
9 mcp-fs --stdio /path/to/workdir
10 mcp-fs --name project --bind 127.0.0.1:31741 /path/to/workdir
11 mcp-fs --stdio --host kaos --rsh rsh /root/src
12  
13 =head1 DESCRIPTION
14  
15 C<mcp-fs> gives an MCP client tools to read, search and change files, and
16 run commands. An assistant can use these tools to work on your projects
17 without you writing a Perl server.
18  
19 Start it with one or more project directories, called workdirs. The client
20 connects to the server, lists its tools and makes requests. A request can
21 select one of these workdirs; with only one, the selection can be omitted.
22 Tools operate on files on disk. To work with unsaved Vim buffers, use
23 L<mcp-vim>.
24  
25 Before starting an operation, the server checks permission rules and, when
26 needed, asks you for approval. Operations normally run in a bubblewrap
27 sandbox with the approved access. Workdirs provide the default filesystem
28 scope; operations needing access elsewhere require the corresponding
29 sandbox grants.
30  
31 You can connect an MCP client directly over HTTP or stdin/stdout, or run
32 the server through C<mcp-multibroker>. See L<AnyEvent::MCP::Intro> for a
33 walkthrough from installation to a first filesystem request.
34  
35 With C<--host>, the same tools operate on a remote host over SSH (or the
36 command selected by C<--rsh>). Only Perl 5.8.4 and the tools used by the
37 requested operations are needed remotely; neither mcp-fs nor its CPAN
38 modules must be installed there. Each server instance uses one host, with
39 any number of workdirs on that host.
40  
41 =head1 FIRST USE
42  
43 Configure your MCP client to launch the server with an existing project:
44  
45 mcp-fs --stdio --name project /home/alice/src/project
46  
47 The client starts the process and speaks MCP over stdin/stdout. Do not run
48 another copy in a terminal. For HTTP clients, run without C<--stdio> and
49 use C<--print-url> with the same C<--name> and C<--bind> settings; see
50 L<AnyEvent::MCP::Intro/YOUR FIRST FILESYSTEM SERVER>.
51  
52 To inspect the tools available with your installed utilities without
53 starting a listener, run C<mcp-fs --tool-help /home/alice/src/project>.
54  
55 Once connected, ask the assistant:
56  
57 Show the configured workdirs and list my project's top-level files.
58 Read its README if present. Do not change files or run commands.
59  
60 C<workdirs> shows the available paths without a worker. Listing requests
61 C<inspect> permission, and reading a file requests C<read>. Allow each once
62 to try them. Approval is specific to the requested action and sandbox grants.
63 If no dialog appears, inspect the tool error and server stderr: the helper
64 needs a YAD display or usable terminal. See L</PERMISSIONS>.
65  
66 For a separate sandbox check without MCP, change to your project directory
67 and run:
68  
69 mcp-fs --exec-cmd workdir-read -- ls
70  
71 This uses the current directory as the workdir. It tests the sandbox,
72 not client connectivity or permission prompting.
73  
74 =head2 Remote workdirs
75  
76 To use an existing directory on another machine:
77  
78 mcp-fs --stdio --host server.example.org /srv/project
79 mcp-fs --stdio -h kaos -e rsh /root/src /srv/projects
80  
81 Workdir arguments are ordinary absolute paths on that host, without a
82 C<host:> prefix. Omitting C<--host> retains local operation, regardless of
83 C<--rsh>. The remote shell is started locally, outside the operation
84 sandbox. Its connection does not require the remote operation's C<network>
85 grant. Combine unrelated hosts through C<mcp-multibroker>.
86  
87 Remote request cancellation and timeouts terminate the local remote-shell
88 process, but may leave the remote worker running. After a connection failure,
89 the outcome of a modifying operation may be unknown; inspect the remote
90 filesystem before retrying it. Reliable remote process termination is not
91 yet implemented.
92  
93 =head1 TOOLS
94  
95 The filesystem tools are:
96  
97 =over
98  
99 =item C<workdirs>
100  
101 Report configured workdirs and available sandbox grants, without starting a worker.
102  
103 =item C<list>, C<find>
104  
105 Enumerate directory entries.
106  
107 =item C<stat>
108  
109 Return lstat metadata without following symlinks.
110  
111 =item C<file-read>
112  
113 Read byte ranges and return Base64 data.
114  
115 =item C<read-lines>
116  
117 Read LF-delimited lines with selectable UTF-8, Latin-1 or Base64 representation.
118  
119 =item C<grep>
120  
121 Search files using a literal pattern or PCRE.
122  
123 =item C<file-write>
124  
125 Write Base64 bytes at an offset without implicit truncation.
126  
127 =item C<path-op>
128  
129 Perform pathname mutations.
130  
131 =item C<file-patch>
132  
133 Apply a unified diff to a single file.
134  
135 =item C<exec>
136  
137 Run an argv array, not a shell command string. To use shell syntax,
138 explicitly invoke a shell in that array.
139  
140 =back
141  
142 For C<exec>, C<stdin_encoding> selects C<utf-8> (default), C<latin1>
143 or C<base64>. The 4 MiB limit applies to the resulting stdin bytes.
144 The C<argv> elements are Unicode MCP strings encoded as UTF-8 for the
145 operating system; they cannot represent arbitrary non-UTF-8 argv bytes.
146 Stdout and stderr are decoded as UTF-8, with a raw capture limit of
147 1 MiB per stream; use the byte-range tools for binary file contents.
148 Its optional C<sandbox_grants> B<replaces> the default C<workdir-read>
149 grant rather than adding to it. Explicitly passing an empty array
150 therefore asks for no grants. Command exit codes are normal tool results,
151 not transport errors. On timeout, output collection stops and
152 C<truncated> is true; C<exit> and C<signal> still describe the reaped child.
153  
154 Perl is required for normal server operation; missing optional GNU utilities
155 can cause their tools to be omitted. The command requested by C<exec>
156 is resolved when the worker runs; it need not be present when the server
157 starts. Inspect C<tools/list> rather than assuming every tool is present.
158  
159 =head2 Command output
160  
161 C<exec>, C<vcs-diff>, C<vcs-status> and C<vcs-log> share three presentation options:
162  
163 =over
164  
165 =item grep => $pattern
166  
167 Optional PCRE line filter for stdout. It runs in a separate timed GNU grep
168 worker after command output has been captured. It is not passed to the
169 original command or a shell. Stderr remains unfiltered.
170  
171 =item max_lines => $integer
172  
173 Maximum returned stdout lines after filtering, default 2000, maximum 100000.
174  
175 =item max_bytes => $integer
176  
177 Maximum returned UTF-8 bytes per stream, default 65536, maximum 1048576.
178 Clipping does not leave an incomplete UTF-8 character. Stderr has its own
179 budget, so a large stdout does not hide diagnostics.
180  
181 =back
182  
183 The command runs once and is drained to completion, subject to its timeout.
184 Raw capture is bounded to 1 MiB per stream, independently of the returned
185 output limits. C<capture_truncated> means bytes were omitted before filtering
186 or collection ended on timeout: matches in that omitted output are unknown.
187 C<stdout_truncated>, C<stderr_truncated> and the combined C<truncated> flag
188 also account for returned-output limits.
189  
190 Changing presentation options does not change the command's permission
191 subject. C<exit>, C<signal> and C<timed_out> always describe the original
192 command, including a diff exit code indicating differences. A filter error
193 makes the tool result an error and adds C<filter_error>, while retaining that
194 command status. The command may already have completed; do not rerun it
195 merely because its output filter failed.
196  
197 =head2 Version control
198  
199 C<vcs-diff>, C<vcs-status> and C<vcs-log> take a required C<backend>: C<git>, C<svn>,
200 C<cvs> or C<hg>, a workdir, an optional C<cwd> (default C<.>), and an optional
201 C<files> array. C<cwd> selects a directory within the workdir; it does not
202 change the granted mount boundary. Files are relative to C<cwd> and must
203 stay within the selected workdir. The worker checks its resolved directory
204 after chdir and before starting the client, rejecting symlink escapes.
205 Backend selection is explicit. With no files, the command examines the
206 working copy at C<cwd>. Files must be inside the selected workdir;
207 they are passed as literal filenames, not options, revisions or shell code.
208 Git diff shows unstaged changes; SVN, CVS and Mercurial diff compare the
209 working copy with its base. No commit, update, fetch or push is performed.
210 C<vcs-log> reads revision history. CVS reports revisions separately per file
211 (including their commit IDs), unlike Git's repository-wide commits.
212 Use output limits to bound potentially long histories.
213  
214 These tools have separate C<vcs-diff>, C<vcs-status> and C<vcs-log> permission actions.
215 They request C<workdir-read> for the selected working copy. CVS additionally
216 requests C<ssh-agent>, which includes network access. SVN log may contact the
217 repository and also requests C<ssh-agent> to support svn+ssh; SVN diff/status,
218 Git and Mercurial operations run without network or home access.
219 A saved approval can cover the fixed operation regardless of filenames or
220 output filters, for that workdir and backend, or all supported backends.
221 Configured VCS clients and their configuration are trusted, including any
222 helpers they invoke; these tools do not sandbox the client's own semantics.
223 The ordinary sandbox grants still bound its host access. In unsandboxed
224 mode, the normal full-authority approval requirement applies.
225  
226 Clients are resolved at startup. C<executable.git>, C<executable.svn>,
227 C<executable.cvs> and C<executable.hg> in trusted program/instance settings
228 can override them. A missing client produces a tool error for that backend.
229  
230 =head1 REQUIREMENTS
231  
232 Bubblewrap is required by default, but can be disabled explicitly.
233 Perl 5.8.4 or later must run in the worker environment at startup (except
234 for C<--exec-cmd>). GNU find, grep, patch and sed are optional; tools
235 requiring an unavailable utility are omitted. Use C<tools/list> to see
236 which tools are available.
237  
238 Remote startup resolves workdirs, HOME, required mounts, executable
239 locations and VCS markers once; C<workdirs> thereafter uses this snapshot.
240 Optional C<mount-try> paths are instead passed to bubblewrap for every
241 invocation. Restart mcp-fs to refresh the workdir configuration and tools.
242  
243 =head1 CONNECTIONS
244  
245 HTTP is the default and does not print its URL on startup. C<--print-url>
246 prints the credential-bearing URL; the same token works in a bearer header.
247 C<--stdio> or
248 C<PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL=stdio> selects stdin/stdout.
249 See L<AnyEvent::MCP/GLOBAL CONFIGURATION> for named HTTP settings.
250  
251 =head1 OPTIONS
252  
253 Shared switches are documented in
254 L<AnyEvent::MCP::Server::Simple/COMMON COMMAND-LINE OPTIONS>.
255 The following switches are specific to C<mcp-fs>.
256  
257 =over
258  
259 =item --exec-cmd SANDBOX-GRANT,...
260  
261 Run command with specified sandbox grants, using current directory as
262 workdir; no MCP listener or permission rules. Supply command and arguments
263 after optional C<--> delimiter. Without command, run C<$SHELL> or C</bin/sh>.
264 C<--sandbox none> runs with normal host-user privileges.
265 Example: C<mcp-fs --exec-cmd workdir-read -- ls>.
266 C<--exec-cmd> is local-only; it cannot be combined with C<--host>.
267  
268 =item --ask MODE
269  
270 Permission prompts: C<helper> (default), C<tty>, C<yad>, C<mcp>, C<auto>,
271 or C<none>.
272 Local helper keeps decisions local; tty/yad force interface without fallback.
273 C<mcp> asks client; C<auto> prefers client elicitation when advertised,
274 otherwise local helper. C<none> denies unmatched permission requests without
275 prompting. Overrides C<PERL_ANYEVENT_MCP_PERMISSION_ASK>.
276  
277 =item -h, --host HOST
278  
279 Run filesystem operations on HOST instead of the local machine. Empty or
280 omitted HOST selects local operation. All workdirs belong to this one host.
281 Remote workdir paths must be absolute. Host identity qualifies permission
282 scopes, not workdir IDs, which use logical pathnames without following symlinks.
283  
284 =item -e, --rsh COMMAND
285  
286 Remote shell command, default C<ssh>. Like rsync's C<-e>, COMMAND may include
287 arguments. Only used with C<--host>; C<rsh> is also supported.
288 The command is split into arguments locally without a local shell. The
289 remote shell invokes a short Perl loader. The launcher source is transferred
290 over stdin, followed by length-prefixed binary startup frames; subsequent
291 worker input remains on the same stream.
292  
293 =item --sandbox MODE
294  
295 Worker sandbox mode: C<bwrap> (default), C<auto>, C<none>.
296 C<bwrap> requires working bubblewrap. C<auto> uses bubblewrap if installed,
297 otherwise runs unsandboxed; failing bubblewrap does not silently fall back.
298 C<none> runs with full host-user privileges. Unsandboxed workers require
299 approval for maximum authority (world-write, network, shared-tmp, host-proc)
300 even for reads; narrower grants cannot authorize them. Startup warns.
301  
302 =item --exec-prefix COMMAND
303  
304 Run workers and their executable probe through COMMAND, split into argv with
305 shell-style quoting. No additional shell is used locally. For example,
306 C<--exec-prefix 'doas -n'> can read protected files on a machine using doas
307 instead of sudo. Remote execution uses the existing SSH command shell and
308 places the prefix before the remote Perl launcher. A failed prefix never
309 falls back to the original credentials.
310  
311 =item --sudo[=USER]
312  
313 Shortcut for C<--exec-prefix 'sudo -n'>, optionally adding C<-u USER>.
314 Overrides C<--exec-prefix>. For example, C<--sudo> with
315 C<--host user@host> works when SSH must log in as an unprivileged account
316 but passwordless sudo is permitted. C<--sudo=mail> runs as the mail user.
317 Sudo must work noninteractively; no password or terminal is supplied.
318  
319 =item --host-dac
320  
321 Keep the host user namespace and retain C<CAP_DAC_OVERRIDE> inside
322 bubblewrap. For example, a root worker can inspect a 0700 directory owned
323 by another user within a granted workdir. Other capabilities are dropped;
324 the existing mount and MCP permission restrictions still apply. Requires
325 privileged bubblewrap; C<--sandbox none> is incompatible.
326  
327 =item --bwrap PATH
328  
329 Use specified bubblewrap executable. Default: C<bwrap> found in C<PATH>.
330 Relevant with C<--sandbox bwrap> or C<--sandbox auto>.
331  
332 =back
333  
334 =head2 Shared-option behavior
335  
336 =over
337  
338 =item --name NAME
339  
340 Also selects permission profile C<fs-NAME> and its rule file,
341 C<rules/fs-NAME.ini>. Default instance name: C<default>.
342  
343 =item --print-url[=USER]
344  
345 Does not require a WORKDIR argument.
346  
347 =item --tool-help
348  
349 Requires normal WORKDIR arguments, since available tools depend on the
350 selected workdirs and installed utilities.
351  
352 =item --auto-allow TOOL[,ACTION[,CAPABILITY]]
353  
354 For example, combining C<--auto-allow '*,inspect,workdir-read'> with
355 C<--auto-allow '*,read,workdir-read'> approves only those two actions
356 within read-only workdir authority. C<--auto-allow '*,*,workdir-write'>
357 approves any action requiring at most workdir-write authority,
358 including reads.
359  
360 =back
361  
362 Rules reside in C<$XDG_CONFIG_HOME/anyevent-mcp/rules/fs-NAME.ini>,
363 or the corresponding C<$HOME/.config> path. The rules filename shares the
364 service-instance name but has an C<fs> namespace. The default instance uses
365 C<rules/fs-default.ini>. The rules path is printed on stderr when starting
366 HTTP; normal startup leaves stdout untouched.
367 Local and remote instances with the same C<--name> intentionally share
368 the same rule profile. Permission requests include a host dimension: C<local>
369 for local execution, or C<remote HOST> using C<--host> independently of
370 C<--rsh>. New persistent rules default to this host, but may match all hosts.
371 The workdir matcher is simply the logical path, independent of host. Existing
372 rules lacking C<match.host> continue to apply across local and remote hosts;
373 only newly saved host-specific rules restrict this.
374 Use different instance names or C<match.host> to separate approvals for
375 different hosts. Unscoped rules apply across hosts sharing the profile.
376  
377 =head1 TRUSTED CONFIGURATION
378  
379 In C<~/.config/anyevent-mcp/global.ini> (or the corresponding
380 C<XDG_CONFIG_HOME> location), C<[program NAME]> supplies defaults based
381 on the executable basename, while C<[instance NAME]> overrides them for
382 C<--name NAME>. A symlinked executable therefore has its own program defaults.
383  
384 [program mcp-fs]
385 mount-try.opt = ro:/opt
386 mount-try.perl = ro:/opt/perl
387 prepend-path = /opt/bin:/opt/sbin
388 mount.shared = rw:/srv/shared
389 env.cvs = CVS_RSH=/my/cvs/rsh
390 executable.perl = /opt/bin/perl
391  
392 [instance myproject]
393 mount.opt =
394 prepend-path =
395 mount.extra = ro:/srv/project-tools
396  
397 To override settings for one invocation, use the common C<-s> / C<--set>
398 option rather than editing the file:
399  
400 mcp-fs --stdio -s executable.perl=/opt/perl/bin/perl \
401 -s prepend-path=/opt/perl/bin /srv/project
402  
403 Command-line settings take precedence over program and instance settings;
404 repeated keys use their last value. See L<AnyEvent::MCP::Server::Simple/COMMON COMMAND-LINE OPTIONS>.
405  
406 Automatic permission rules can also be configured:
407  
408 [program mcp-fs]
409 auto-rule.10 = allow *,read,workdir-read
410 auto-rule.20 = allow *,write,workdir-write
411 auto-rule.30 = deny *,exec,*
412  
413 The supported configuration entries are:
414  
415 =over
416  
417 =item C<auto-rule.SUFFIX>
418  
419 Automatic permission rules apply to every named mcp-fs instance;
420 CLI auto-rules are evaluated first.
421  
422 =item C<mount.SUFFIX>
423  
424 A required sandbox mount. The named path must exist at startup.
425  
426 =item C<mount-try.SUFFIX>
427  
428 An optional sandbox mount, using bubblewrap's C<--ro-bind-try> or
429 C<--bind-try>. An absent path is skipped by bubblewrap at each invocation,
430 without a startup existence check.
431  
432 Both mount kinds are applied in alphabetical key order after the private
433 sandbox mounts. The suffix is an arbitrary stable name; an empty instance
434 value suppresses an inherited entry. Paths must be absolute. A colon after
435 C<ro:> or C<rw:> starts the literal pathname; no separate quoting or escaping
436 syntax is used.
437  
438 =item C<env.SUFFIX>
439  
440 Specify C<NAME=value> to set a literal value, or C<NAME> to inherit that
441 variable from the server environment if present. Values may contain spaces
442 and equals signs; there is no shell expansion. Entries are applied in
443 alphabetical key order after the default environment. An empty instance
444 entry suppresses the corresponding program entry. C<SSH_AUTH_SOCK> is managed
445 exclusively by the C<ssh-agent> grant, even when listed in these settings.
446 Environment settings do not expose paths; custom executables outside the
447 runtime/workdir mounts need configured mounts.
448  
449 =item C<prepend-path>
450  
451 Add colon-separated directories before the bubblewrapped worker's fixed
452 C<PATH> of C</usr/bin:/usr/sbin:/bin:/sbin:/usr/local/bin:/usr/local/sbin>.
453 Trailing colons are ignored, so both C</opt/bin> and C</opt/bin:> work.
454 The server's C<PATH> is not inherited. An empty instance value restores the
455 fixed default rather than the program value. C<--sandbox=none> continues to
456 use the host environment. Directories outside the normal runtime mounts
457 still need a configured mount to be accessible.
458  
459 =item C<executable.find>, C<executable.grep>, C<executable.patch>,
460 C<executable.perl>, C<executable.sed>, C<executable.bwrap>
461  
462 Override automatic executable discovery. Explicit choices must resolve to
463 executable files and are trusted instead of version-probed, except for
464 C<executable.perl>, which must satisfy the Perl minimum version.
465 C<executable.perl> defaults to C<perl> in the worker's C<PATH>;
466 the other worker executables are discovered there too. C<--bwrap>
467 overrides C<executable.bwrap> and is located on the host.
468  
469 =back
470  
471 Configured mounts grant baseline access to every sandbox invocation
472 (when present for C<mount-try>), independently of tool permission grants.
473 With C<world-read>, only C<rw:> exceptions are applied over the read-only
474 host filesystem. With C<world-write>, these configured mounts are ignored.
475 Selecting C</> as a workdir makes C<workdir-read> and C<workdir-write>
476 equivalent in filesystem reach to C<world-read> and C<world-write>,
477 respectively, without changing saved permission identities. Host directory
478 mounts are applied parent-first, followed by protected private system mounts
479 and explicitly configured narrower exceptions.
480 Baseline execution paths include C</usr>, C</bin>, system libraries and
481 selected system configuration, but not C</opt>. Shared host temporary
482 directories require C<shared-tmp>, an explicit configured mount, or
483 C<world-write>. All other grants, including C<world-read>, use private
484 writable temporary directories. C<world-write> implies C<shared-tmp>.
485  
486 Defaults also include alternatives, font configuration, local timezone,
487 TLS certificate stores, NSS configuration and DNS configuration where
488 present. A synthetic passwd entry is created in the private root if the
489 host root is not exposed. A workdir covering C</etc> will instead show the
490 host passwd file, without ever modifying it. A root workdir exposes the
491 host passwd and group databases.
492  
493 The C<workdirs> result includes C<workdir_vcs>, a mapping from configured
494 workdir identities to arrays of backends with metadata markers directly
495 in that directory. Detection checks C<CVS>, C<.git>, C<.hg> and C<.svn>;
496 a Git metadata file is supported as well as a directory. Symlink markers
497 are reported without following them. This is a hint, not validation of a
498 repository. There is no recursive scan or parent search, multiple markers
499 are retained, and an empty array means no marker was found. Detection is
500 independent of the available clients in C<vcs_backends> and does not choose
501 the backend for a VCS command.
502  
503 =head1 SANDBOX GRANTS
504  
505 =over
506  
507 =item C<workdir-read>
508  
509 Read access to the selected workdir.
510  
511 =item C<workdir-write>
512  
513 Write access to the selected workdir; implies C<workdir-read>.
514  
515 =item C<all-workdirs-read>
516  
517 Read access to every configured workdir.
518  
519 =item C<all-workdirs-write>
520  
521 Write access to every configured workdir; implies read access.
522  
523 =item C<homedir-read>
524  
525 Read access to HOME.
526  
527 =item C<homedir-write>
528  
529 Write access to HOME; implies read access.
530  
531 =item C<world-read>
532  
533 Read access to the host filesystem.
534  
535 =item C<world-write>
536  
537 Write access to the host filesystem; implies C<world-read>.
538 Also implies C<shared-tmp>, so host C</tmp> and C</var/tmp> remain
539 writable and visible.
540  
541 =item C<network>
542  
543 Enable networking outside the sandbox's network namespace. Without this
544 grant, bubblewrap uses a separate network namespace. Loopback connections
545 between processes in that same sandbox work, but its C<127.0.0.1> is not
546 the host's C<127.0.0.1>. Connecting to a host-side loopback server requires
547 C<network>.
548  
549 =item C<shared-tmp>
550  
551 Use the host's writable C</tmp> and C</var/tmp> instead of private
552 writable temporary directories. Without this grant, temporary files
553 are isolated and disappear when their sandbox ends, even with
554 C<world-read>. Host temporary files are visible across invocations,
555 though the host may clean them up at any time. C<world-write>
556 automatically grants C<shared-tmp>.
557  
558 =item C<long-running>
559  
560 Allow C<exec> timeouts over 300 seconds.
561  
562 =item C<host-proc>
563  
564 Host-process access, available only without bubblewrap.
565  
566 =item C<ssh-agent>
567  
568 Implies C<network>. Exposes the server's C<SSH_AUTH_SOCK> at
569 C</run/anyevent-mcp/ssh-agent> and sets the child's variable to that path.
570 In remote mode it uses the remote shell's agent socket, when available
571 (for example through SSH agent forwarding), rather than mounting the local
572 socket path. SSH authentication used to reach the host is separate from
573 the worker's C<ssh-agent> and C<network> grants.
574  
575 Also exposes C<~/.ssh/known_hosts> read-only if present, without mounting
576 the rest of HOME. Private key files and SSH user configuration are not exposed.
577 An unset or empty C<SSH_AUTH_SOCK> exposes no socket, allowing rsh-based CVS;
578 a configured socket must be an absolute path naming an existing socket node.
579 Socket replacement requires a new invocation; an existing bind mount keeps
580 the old node. Agent access permits authentication, not retrieval of private keys.
581  
582 =back
583  
584 C<all-workdirs-read> combined with C<workdir-write> mounts all workdirs
585 read-only except the selected one, which is writable. C<all-workdirs-write>
586 makes all writable. Configured workdirs are mounted using resolved absolute
587 paths, but their permission-rule identities are verbatim command-line
588 arguments.
589  
590 =head2 Workdir selection
591  
592 Persistent permission rules default to the selected workdir, with an explicit
593 option to match any configured workdir, including future additions. This
594 controls reuse of the rule, not the workdirs accessible in one operation.
595 The multibroker alias is shown in permission prompts, without changing the rule file.
596 Tools accept C<workdir> as a persistent positive integer ID, a numeric
597 string containing that ID, or an exact configured or resolved workdir path.
598 C<workdirs> returns C<workdirs> and C<resolved_workdirs> objects keyed by ID,
599 not arrays indexed by argument position. IDs are shared across server
600 instances in C<$XDG_CONFIG_HOME/anyevent-mcp/fs-workdir-ids.json>, or under
601 C<$HOME/.config> when XDG_CONFIG_HOME is unset. IDs use the logical
602 absolute pathname, without resolving symlinks (relative local arguments
603 are made absolute against the server's working directory). The same logical
604 pathname on local and remote servers receives the same ID, even when it
605 resolves to different physical directories. Permission-rule identities
606 remain the verbatim arguments; each server interprets IDs in its own workdirs.
607  
608 The registry stores C<ID =E<gt> [workdir, last_use]> pairs, with C<last_use>
609 as a Unix timestamp. Starting
610 a server resolves its IDs once and reserves any new allocations under the
611 file lock. An AnyEvent timer runs immediately and every 5.25 days, rereading
612 the registry and overwriting those fixed assignments with fresh timestamps.
613 Other entries expire after seven days without refresh;
614 their IDs can be reused. Restart servers after manually changing the registry.
615 Numeric IDs therefore survive restarts and argument reordering while retained,
616 but are not permanent references to paths that have expired.
617  
618 Non-numeric strings are matched only against configured workdirs, never
619 interpreted as arbitrary filesystem paths. Unknown or ambiguous selectors
620 fail. With only one workdir, the field may be omitted.
621 Overlapping workdirs have unspecified mount order and access effects;
622 do not rely on overlapping workdir boundaries for isolation.
623  
624 =head1 LIMITATIONS
625  
626 With bubblewrap, regardless of granted sandbox grants, the sandbox mounts procfs at
627 C</proc>. Its process entries are restricted by the PID namespace, but
628 kernel-wide and hardware information (including C</proc/irq> and
629 C</proc/bus>) remains visible. This is a limitation of bubblewrap's
630 C<--proc> option, which does not support C<subset=pid>.
631  
632 =head1 PERMISSIONS
633  
634 L<AnyEvent::MCP::Server::Permissions> applies ordered allow, deny and ask
635 decisions to these action classes:
636  
637 =over
638  
639 =item C<inspect>
640  
641 C<stat>, C<list>, C<find>.
642  
643 =item C<read>
644  
645 C<file-read>, C<read-lines>, C<grep>.
646  
647 =item C<write>
648  
649 C<file-write>, C<file-patch>.
650  
651 =item C<manage>
652  
653 C<path-op>.
654  
655 =item C<exec>
656  
657 Command execution.
658  
659 =back
660  
661 C<file-write> may create files despite being in the write class; manage
662 refers specifically to pathname operations rather than an exclusive right
663 to create files.
664 Filesystem operations have no path-based persistent subjects: their rules
665 match C<action>, C<sandbox-grants>, and C<match.workdir> when selected-workdir
666 authority is required. All-workdirs-only requests have no workdir identity.
667 Rules without C<match.workdir> can apply to any selected workdir if their sandbox
668 grants cover the request; dialog-generated workdir rules select exact or any.
669 The independent C<match.host> dimension matches C<local>, a remote host,
670 or all hosts, independently of the remote transport.
671 Instances with the same name share a rule file, including broad unscoped rules.
672 Requested paths are shown in the approval dialog for information only.
673 Exec additionally offers persistent
674 command/argv scopes as C<match.subject>. When stdin is provided, exec attaches display-only
675 details to the permission request: Unicode text for UTF-8 input, or a
676 bounded escaped-byte preview for Latin-1/Base64 input. The YAD helper offers
677 a separate C<View stdin...> window; the preview shows input size and
678 truncation. This does not change authorization: persistent exec rules match
679 argv, not stdin, and later runs may supply different scripts or bytes.
680 Conversion takes place before approval and the worker receives the exact
681 resulting bytes.
682 C<file-patch> supplies C<View patch> details with the target and supplied diff.
683 Base64 patches are decoded for display: valid UTF-8 is shown as Unicode,
684 otherwise non-printable bytes and backslashes are escaped in a byte view.
685 The UI chooses whether to show a separate viewer or an inline preview.
686 Each tool checks permissions before starting its worker. Approval
687 defaults to the local helper selected by C<PERL_ANYEVENT_MCP_PERMISSION_HELPER>,
688 which tries YAD, then a terminal, then denies once. Client elicitation is
689 selected with C<--ask mcp>, C<--ask auto>, or the corresponding
690 C<PERL_ANYEVENT_MCP_PERMISSION_ASK> value.
691  
692 You can edit the rule file at any time. It is reread on permission checks,
693 so changes apply without restarting the server. Keep it owned by your user
694 and private (mode 0600). See L<AnyEvent::MCP::Server::Permissions> for the
695 rule syntax and ordering.
696  
697 Permission retries retain earlier one-time approvals within the same call.
698 For one worker accessing several paths, the required sandbox-grant set combines
699 the authority needed for all paths and is approved once. An insufficient reduction fails before
700 the worker starts.
701 Multi-path C<stat> requires all paths inside its selected workdir.
702 C<path-op> can attempt cross-workdir renames after approving the sandbox
703 grants required for both paths. The sandboxed C<rename(2)> may fail with
704 C<EXDEV> across mounts; no copy/delete fallback is attempted.
705 C<mkpath> requires a path inside the selected workdir.
706 C<path-op> performs requested operations in this fixed order:
707 C<unlink>, C<rmdir>, C<mkpath>, C<mkdir>, C<symlink>, C<truncate>,
708 C<chmod>, C<rename>. C<mkpath> includes each missing component in the
709 combined permission check before starting the worker.
710 The first failure stops subsequent operations; successful earlier mutations
711 remain in place. There is no rollback or all-or-nothing transaction.
712  
713 Exec defaults to a 30-second timeout and permits up to 300 seconds without
714 additional timeout authority. A larger explicit C<timeout>, up to 21600
715 seconds (six hours), also requires C<long-running>. This capability is added
716 to the requested permissions automatically. Cancellation still terminates
717 the worker, regardless of its allowed timeout.
718  
719 The C<host-proc> grant is unavailable with bubblewrap. Runtime mounts
720 provide sandbox machinery. Symlinks resolve within granted mounts.
721 Without bubblewrap, workers operate in the host mount and process namespaces.
722  
723 =head1 PATCHES
724  
725 C<file-patch> uses L<AnyEvent::MCP/PATCH UTILITIES> for normalization and
726 validation. GNU patch runs inside the granted sandbox with fuzz zero.
727 Successful output replaces the original by rename after checking its
728 identity, size, timestamps, metadata and link count. These stat checks
729 do not detect every concurrent edit; they are not a filesystem transaction.
730  
731 =cut
732  
733 9 ▶use common::sense;
Subroutine BEGIN: called CC=1 SCAR=0.0
734  
735 9 ▶use MIME::Base64 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
736 9 ▶use Getopt::Long ();
Subroutine BEGIN: called CC=1 SCAR=0.0
737 9 ▶use Cwd ();
Subroutine BEGIN: called CC=1 SCAR=0.0
738 9 ▶use File::Basename ();
Subroutine BEGIN: called CC=1 SCAR=0.0
739 9 ▶use File::Spec::Unix ();
Subroutine BEGIN: called CC=1 SCAR=0.0
740 9 ▶use Text::ParseWords ();
Subroutine BEGIN: called CC=1 SCAR=0.0
741 9 ▶use IPC::Open2 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
742 9 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
743 9 ▶use Fcntl qw(F_SETFD);
Subroutine BEGIN: called CC=1 SCAR=0.0
744 9 ▶use Scalar::Util qw(weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
745  
746 9 ▶use JSON::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
747 9 ▶use AnyEvent ();
Subroutine BEGIN: called CC=1 SCAR=0.0
748 9 ▶use AnyEvent::MCP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
749 9 ▶use AnyEvent::MCP::Config ();
Subroutine BEGIN: called CC=1 SCAR=0.0
750 9 ▶use AnyEvent::MCP::Workdirs ();
Subroutine BEGIN: called CC=1 SCAR=0.0
751 9 ▶use AnyEvent::MCP::Server::Permissions ();
Subroutine BEGIN: called CC=1 SCAR=0.0
752 9 ▶use AnyEvent::Handle ();
Subroutine BEGIN: called CC=1 SCAR=0.0
753 9 ▶use AnyEvent::Log ();
Subroutine BEGIN: called CC=1 SCAR=0.0
754 9 ▶use AnyEvent::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
755  
756 9 ▶use AnyEvent::MCP::Server::Simple;
Subroutine BEGIN: called CC=1 SCAR=0.0
757  
758 # resolve an executable name or path to an absolute executable file.
759 0 ▶sub find_executable {
Subroutine find_executable: not called CC=10 SCAR=47.0
760 0 my ($name) = @_;
761  
762 0 ▶ !ref $name and length $name and $name !~ /\0/
Branch: 1 branch
BranchTrueFalseTotal
not ref $name and length $name and not $name =~ /\0/u or return 0 0 0
Condition0%0/6
not ref $name and length $name and not $name =~ /\0/u
!ll&&!rl&&r
000
not ref $name and length $name
!ll&&!rl&&r
000
MC/DC0%0/3
not ref $name and length $name and not $name =~ /\0/u
not ref $name length $name not $name =~ /\0/u
Truth table0%0/4
not(A) and B and not(C)
A= not ref $nameB= length $nameC= not $name =~ /\0/u
ABCresult
0XX0
10X0
1100
1111
763 or return;
764  
765 my @path = $name =~ m{/}
766 ? ($name)
767 0 ▶ : map { (length $_ ? $_ : ".") . "/$name" } split /:/, $ENV{PATH};
Branch: 2 branches
BranchTrueFalseTotal
$name =~ m[/]u ? : 0 0 0
length $_ ? : 0 0 0
768 0 my $cwd = Cwd::getcwd;
769  
770 0 for my $path (@path) {
771 0 ▶ next unless -f $path and -x _;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $path and -x _ 0 0 0
Condition0%0/3
-f $path and -x _
!ll&&!rl&&r
000
MC/DC0%0/2
-f $path and -x _
-f $path -x _
Truth table0%0/3
A and B
A= -f $pathB= -x _
ABresult
0X0
100
111
772 0 ▶ return $path =~ m{\A/} ? $path : "$cwd/$path";
Branch: 1 branch
BranchTrueFalseTotal
$path =~ m[\A/]u ? : 0 0 0
773 }
774  
775 undef
776 0 }
777  
778 9 Getopt::Long::Configure qw(bundling no_ignore_case require_order);
779  
780 9 my $sandbox_mode = "bwrap";
781 9 my $usage = "Usage: $0 [OPTION]... WORKDIR [WORKDIR]...\n"
782 . " $0 --exec-cmd GRANT,... [--] [COMMAND [ARG]...]\n";
783  
784 9 my $server_options = mcp_getoptions
785 {
786 usage => $usage,
787 description => "Expose filesystem tools and command execution over MCP.\n"
788 . "Operations require permission and normally run inside bubblewrap.",
789 option_heading => "Filesystem options:",
790 options => [
791 ["-h, --host HOST", "Run on one remote host (default: local)"],
792 ["-e, --rsh COMMAND", "Remote shell command (default: ssh)"],
793 ["--sandbox MODE", "Use bwrap (default), auto, or none (unsandboxed)"],
794 ["--host-dac", "Allow root workers to read other users' protected files inside sandbox mounts"],
795 ["--exec-prefix COMMAND", "Prefix worker commands (e.g. sudo -n), locally or remotely"],
796 ["--sudo[=USER]", "Run workers through sudo -n, optionally as USER; overrides --exec-prefix"],
797 ["--bwrap PATH", "Path to the bubblewrap executable"],
798 ["--exec-cmd GRANT,...", "Run a command directly with the named grants"],
799 ],
800 examples => " $0 --stdio /home/alice/src/project\n"
801 . " $0 --name project --print-url\n"
802 . " $0 --sandbox bwrap /home/alice/src/project\n"
803 . " $0 --auto-allow '*,inspect,workdir-read' --auto-allow '*,read,workdir-read' /project\n"
804 . " $0 --auto-allow '*,*,workdir-write' /project",
805 },
806 "sandbox=s" => \$sandbox_mode,
807 "host|h=s" => \my $host,
808 "rsh|e=s" => \my $rsh,
809 "exec-cmd=s" => \my $exec_cmd,
810 "bwrap=s" => \my $bwrap,
811 "host-dac!" => \my $host_dac,
812 "exec-prefix=s" => \my $exec_prefix,
813 "sudo:s" => \my $sudo,
814 ;
815  
816 6 my $name = $server_options->{name};
817 6 my $stdio = delete $server_options->{stdio};
818  
819 6 ▶(defined $exec_cmd or @ARGV)
Branch: 1 branch
BranchTrueFalseTotal
defined $exec_cmd or @ARGV or die $usage 6 0 6
Condition33%1/3
defined $exec_cmd or @ARGV
l!l&&r!l&&!r
060
MC/DC0%0/2
defined $exec_cmd or @ARGV
defined $exec_cmd @ARGV
Truth table33%1/3
A or B
A= defined $exec_cmdB= @ARGV
ABresult
1X1
011
000
820 or die $usage;
821  
822 6 ▶$sandbox_mode =~ /\A(?:bwrap|auto|none)\z/
Branch: 1 branch
BranchTrueFalseTotal
$sandbox_mode =~ /\A(?:bwrap|auto|none)\z/u or die "--sandbox must be bwrap, auto, or none\n" 6 0 6
823 or die "--sandbox must be bwrap, auto, or none\n";
824 6 ▶$host_dac && $sandbox_mode eq "none" and die "--host-dac requires bubblewrap\n";
Branch: 1 branch
BranchTrueFalseTotal
$host_dac and $sandbox_mode eq "none" and die "--host-dac requires bubblewrap\n" 0 6 6
Condition33%1/3
$host_dac and $sandbox_mode eq "none"
!ll&&!rl&&r
600
MC/DC0%0/2
$host_dac and $sandbox_mode eq "none"
$host_dac $sandbox_mode eq "none"
Truth table33%1/3
A and B
A= $host_dacB= $sandbox_mode eq "none"
ABresult
0X0
100
111
825  
826 6 ▶$host //= "";
Condition50%1/2
$host //= ""
l!l
06
MC/DC0%0/1
$host //= ""
$host
Truth table50%1/2
A
A= $host
Aresult
11
00
827 6 ▶$host !~ m{[\s/\0]} && $host !~ /\A-/
Branch: 1 branch
BranchTrueFalseTotal
$host =~ m[[\s/\0]]u || $host =~ /\A-/u and die "invalid remote host\n" 0 6 6
Condition33%1/3
$host =~ m[[\s/\0]]u or $host =~ /\A-/u
l!l&&r!l&&!r
006
MC/DC0%0/2
$host =~ m[[\s/\0]]u or $host =~ /\A-/u
$host =~ m[[\s/\0]]u $host =~ /\A-/u
Truth table33%1/3
A or B
A= $host =~ m[[\s/\0]]uB= $host =~ /\A-/u
ABresult
1X1
011
000
828 or die "invalid remote host\n";
829 6 ▶$rsh //= "ssh";
Condition50%1/2
$rsh //= "ssh"
l!l
06
MC/DC0%0/1
$rsh //= "ssh"
$rsh
Truth table50%1/2
A
A= $rsh
Aresult
11
00
830 6 my @rsh = Text::ParseWords::shellwords ($rsh);
831 6 ▶@rsh or die "empty remote shell command\n";
Branch: 1 branch
BranchTrueFalseTotal
@rsh or die "empty remote shell command\n" 6 0 6
832 6 ▶my @exec_prefix = defined $sudo
Branch: 3 branches
BranchTrueFalseTotal
defined $sudo ? : 0 6 6
length $sudo ? : 0 0 0
defined $exec_prefix ? : 0 6 6
833 ? ("sudo", "-n", (length $sudo ? ("-u", $sudo) : ()), "--")
834 : defined $exec_prefix ? Text::ParseWords::shellwords ($exec_prefix) : ();
835 6 ▶defined $exec_prefix && !defined $sudo && !@exec_prefix
Branch: 1 branch
BranchTrueFalseTotal
defined $exec_prefix and not defined $sudo and not @exec_prefix and die "empty --exec-prefix\n" 0 6 6
Condition33%2/6
defined $exec_prefix and not defined $sudo and not @exec_prefix
!ll&&!rl&&r
600
defined $exec_prefix and not defined $sudo
!ll&&!rl&&r
600
MC/DC0%0/3
defined $exec_prefix and not defined $sudo and not @exec_prefix
defined $exec_prefix not defined $sudo not @exec_prefix
Truth table25%1/4
A and not(B) and not(C)
A= defined $exec_prefixB= not defined $sudoC= not @exec_prefix
ABCresult
0XX0
10X0
1100
1111
836 and die "empty --exec-prefix\n";
837 6 my $remote = length $host;
838 6 ▶!($remote && defined $exec_cmd)
Branch: 1 branch
BranchTrueFalseTotal
($remote and defined $exec_cmd) and die "--host cannot be combined with --exec-cmd\n" 0 6 6
Condition33%1/3
$remote and defined $exec_cmd
!ll&&!rl&&r
600
MC/DC0%0/2
$remote and defined $exec_cmd
$remote defined $exec_cmd
Truth table33%1/3
A and B
A= $remoteB= defined $exec_cmd
ABresult
0X0
100
111
839 or die "--host cannot be combined with --exec-cmd\n";
840  
841 6 my $program_name = AnyEvent::MCP::Config::program_name ();
842 6 my $config_file = AnyEvent::MCP::Config::_file ();
843 6 ▶my $config = -e $config_file ? AnyEvent::MCP::Config::global_config () : undef;
Branch: 1 branch
BranchTrueFalseTotal
-e $config_file ? : 6 0 6
844 my %settings = $config ? (
845 6 %{ $config->{section}{"program $program_name"} },
846 6 ▶ %{ $config->{section}{"instance $name"} },
Branch: 1 branch
BranchTrueFalseTotal
$config ? : 6 0 6
847 ) : ();
848  
849 # executable names from the UTF-8 config are text; process argv needs bytes.
850 my %executable = map {
851 6 (my $name = $_) =~ s/\Aexecutable\.//;
852 4 ($name => AnyEvent::MCP::utf8enc $settings{$_})
853 } grep /\Aexecutable\./, keys %settings;
854  
855 6 my $sandbox_path = "/usr/bin:/usr/sbin:/bin:/sbin:/usr/local/bin:/usr/local/sbin";
856 6 ▶(my $prepend = $settings{"prepend-path"} // "") =~ s/:+\z//;
Condition50%1/2
$settings{"prepend-path"} // ""
l!l
06
MC/DC0%0/1
$settings{"prepend-path"} // ""
$settings{"prepend-path"}
Truth table50%1/2
A
A= $settings{"prepend-path"}
Aresult
11
00
857 6 ▶$sandbox_path = "$prepend:$sandbox_path" if length $prepend;
Branch: 1 branch
BranchTrueFalseTotal
if length $prepend 0 6 6
858 6 $sandbox_path = AnyEvent::MCP::utf8enc $sandbox_path;
859  
860 6 my @mount;
861 6 for my $key (sort grep /\Amount(?:-try)?\./, keys %settings) {
862 0 my $value = $settings{$key};
863 0 ▶ next unless length $value;
Branch: 1 branch
BranchTrueFalseTotal
unless length $value 0 0 0
864 0 ▶ my ($mode, $path) = $value =~ /\A(ro|rw):(\/.*)\z/
Branch: 1 branch
BranchTrueFalseTotal
() = $value =~ m[\A(ro|rw):(/.*)\z]u or die "invalid $key mount '${value}'\n" 0 0 0
865 or die "invalid $key mount '$value'\n";
866 0 ▶ -e (AnyEvent::MCP::utf8enc $path) or die "invalid $key mount path '$path'\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $remote or $key =~ /\Amount-try\./u 0 0 0
Condition0%0/8
$remote || $key =~ /\Amount-try\./u || (-e &AnyEvent::MCP::utf8enc($path) || die("invalid $key mount path '${path}'\n"))
l!l&&r!l&&!r
000
$remote or $key =~ /\Amount-try\./u
l!l&&r!l&&!r
000
-e &AnyEvent::MCP::utf8enc($path) or die "invalid $key mount path '${path}'\n"
l!l
00
MC/DC0%0/3
$remote || $key =~ /\Amount-try\./u || (-e &AnyEvent::MCP::utf8enc($path) || die("invalid $key mount path '${path}'\n"))
$remote $key =~ /\Amount-try\./u -e &AnyEvent::MCP::utf8enc($path)
Truth table0%0/4
A or B || C
A= $remoteB= $key =~ /\Amount-try\./uC= -e &AnyEvent::MCP::utf8enc($path)
ABCresult
1XX1
01X1
0011
0000
867 unless $remote || $key =~ /\Amount-try\./;
868 0 push @mount, [$key, $mode, $path];
869 }
870  
871 6 my @environment;
872 6 for my $key (sort grep /\Aenv\./, keys %settings) {
873 0 my $value = $settings{$key};
874 0 ▶ next unless length $value;
Branch: 1 branch
BranchTrueFalseTotal
unless length $value 0 0 0
875 0 ▶ my ($name, $text) = $value =~ /\A([A-Za-z_][A-Za-z_0-9]*)(?:=(.*))?\z/s
Branch: 1 branch
BranchTrueFalseTotal
() = $value =~ /\A([A-Za-z_][A-Za-z_0-9]*)(?:=(.*))?\z/su or die "invalid $key environment entry '${value}'\n" 0 0 0
876 or die "invalid $key environment entry '$value'\n";
877 0 push @environment, [$name, $text];
878 }
879  
880 # SSH and rsh execute their command through a remote shell. Only this fixed
881 # launcher goes through that shell; all executable arguments are framed on stdin.
882 6 my $remote_launcher = q{#perl
883 use 5.008004;
884 use POSIX ();
885 use Fcntl qw(F_SETFD);
886 binmode STDIN;
887 my $read = sub {
888 my ($length) = @_;
889 my $data = "";
890 while (length $data < $length) {
891 my $got = sysread STDIN, my $part, $length - length $data;
892 defined $got or die "remote stdin: $!\n";
893 $got or die "short remote startup frame\n";
894 $data .= $part;
895 }
896 $data
897 };
898 my $length = unpack "N", $read->(4);
899 $length <= 1048576 or die "remote startup frame too large\n";
900 my ($home, @command) = unpack "(w/a*)*", $read->($length);
901 @command or die "empty remote command\n";
902 my $agent_index;
903 if (length $home) {
904 for my $i (1 .. $#command - 1) {
905 last if $command[$i] eq "--";
906 if ($command[$i - 1] eq "--ro-bind"
907 && $command[$i] eq "__MCP_REMOTE_AGENT__"
908 && $command[$i + 1] eq "/run/anyevent-mcp/ssh-agent") {
909 $agent_index = $i;
910 last;
911 }
912 }
913 }
914 if (defined $agent_index) {
915 my $source = $ENV{SSH_AUTH_SOCK};
916 if (length $source) {
917 $source =~ m{\A/} && -S $source
918 or die "remote SSH_AUTH_SOCK must name an absolute socket\n";
919 $command[$agent_index] = $source;
920 } else {
921 splice @command, $agent_index - 1, 3;
922 for (my $i = 0; $i < @command; ++$i) {
923 last if $command[$i] eq "--";
924 if ($command[$i] eq "--setenv" && $command[$i + 1] eq "SSH_AUTH_SOCK") {
925 splice @command, $i, 3;
926 last;
927 }
928 }
929 }
930 }
931 my $passwd_fd;
932 if (length $home) {
933 pipe (my $rd, my $wr) or die "passwd pipe: $!\n";
934 print {$wr} "sandbox:x:$<:" . POSIX::getgid () . ":Sandbox:$home:/bin/sh\n"
935 or die "passwd pipe: $!\n";
936 close $wr or die "passwd pipe: $!\n";
937 if (fileno ($rd) != 3) {
938 POSIX::dup2 (fileno ($rd), 3) == 3 or die "passwd dup2: $!\n";
939 close $rd;
940 open $rd, "<&=3" or die "passwd fd: $!\n";
941 }
942 defined fcntl ($rd, F_SETFD, 0) or die "passwd fcntl: $!\n";
943 $passwd_fd = $rd;
944 }
945 exec {$command[0]} @command;
946 die "remote exec $command[0]: $!\n";
947 };
948  
949 18 ▶sub shell_quote {
Subroutine shell_quote: called CC=1 SCAR=0.0
950 18 my ($text) = @_;
951 18 $text =~ s/'/'"'"'/g;
952 18 "'$text'"
953 }
954  
955 # Keep the remote command short (rsh limits its size). The tiny loader reads
956 # exactly the launcher source; unlike parsing a script from stdin, it cannot
957 # buffer bytes intended for the eventual exec'd worker.
958 6 my $remote_loader = sprintf q{binmode STDIN;
959 while (length $s < %1$d) {
960 sysread STDIN, $s, %1$d - length $s, length $s or die "read\n";
961 }
962 eval $s; die $@ if $@;
963 }, length $remote_launcher;
964 my $remote_command = "exec " . join " ", map shell_quote ($_),
965 6 ▶ @exec_prefix, ($executable{perl} || "perl"), "-e", $remote_loader;
Condition100%2/2
$executable{'perl'} || 'perl'
l!l
42
MC/DC100%1/1
$executable{'perl'} || 'perl'
$executable{'perl'}
Truth table100%2/2
A
A= $executable{'perl'}
Aresult
11
00
966  
967 # all fields here are already octets, including encoded filenames and argv.
968 0 ▶sub fs_remote_frame {
Subroutine fs_remote_frame: not called CC=2 SCAR=17.9
969 0 my @arg = @_;
970 0 utf8::downgrade $_ for @arg; # enforce octets, not an external encoding
971 0 pack "N/a*", pack "(w/a*)*", @arg
972 }
973  
974 6 my ($find, $grep, $patch, $perl, $sed);
975 6 my %vcs_program;
976  
977 6 ▶$bwrap //= $executable{bwrap} || "bwrap";
Condition50%2/4
$bwrap //= $executable{"bwrap"} || "bwrap"
l!l
06
$executable{'bwrap'} || 'bwrap'
l!l
06
MC/DC0%0/1
$bwrap //= $executable{"bwrap"} || "bwrap"
$bwrap
Truth table50%1/2
A
A= $bwrap
Aresult
11
00
978  
979 6 ▶if ($sandbox_mode ne "none" && !$remote) {
Branch: 2 branches
BranchTrueFalseTotal
if ($sandbox_mode ne 'none' and not $remote) { } 0 6 6
elsif ($sandbox_mode eq 'none') { } 6 0 6
Condition33%1/3
$sandbox_mode ne "none" and not $remote
!ll&&!rl&&r
600
MC/DC0%0/2
$sandbox_mode ne "none" and not $remote
$sandbox_mode ne "none" not $remote
Truth table33%1/3
A and not(B)
A= $sandbox_mode ne "none"B= not $remote
ABresult
0X0
100
111
980 0 my $name = $bwrap;
981 0 $bwrap = find_executable $name;
982 0 ▶ die "bubblewrap executable not found: $name\n"
Branch: 1 branch
BranchTrueFalseTotal
if not $bwrap and $sandbox_mode eq "bwrap" 0 0 0
Condition0%0/3
not $bwrap and $sandbox_mode eq "bwrap"
!ll&&!rl&&r
000
MC/DC0%0/2
not $bwrap and $sandbox_mode eq "bwrap"
not $bwrap $sandbox_mode eq "bwrap"
Truth table0%0/3
not(A) and B
A= not $bwrapB= $sandbox_mode eq "bwrap"
ABresult
0X0
100
111
983 if !$bwrap && $sandbox_mode eq "bwrap";
984 } elsif ($sandbox_mode eq "none") {
985 6 undef $bwrap;
986 }
987  
988 6 ▶if ($host_dac && !$remote) {
Branch: 1 branch
BranchTrueFalseTotal
if ($host_dac and not $remote) 0 6 6
Condition33%1/3
$host_dac and not $remote
!ll&&!rl&&r
600
MC/DC0%0/2
$host_dac and not $remote
$host_dac not $remote
Truth table33%1/3
A and not(B)
A= $host_dacB= not $remote
ABresult
0X0
100
111
989 0 ▶ $bwrap or die "--host-dac requires bubblewrap\n";
Branch: 1 branch
BranchTrueFalseTotal
$bwrap or die "--host-dac requires bubblewrap\n" 0 0 0
990 0 ▶ if (@exec_prefix) {
Branch: 1 branch
BranchTrueFalseTotal
if (@exec_prefix) { } 0 0 0
991 0 my @check = (@exec_prefix, $^X, "-e", 'exit $> ? 1 : 0');
992 0 system {$check[0]} @check;
993 0 ▶ $? == 0 or die "--host-dac requires a root worker\n";
Branch: 1 branch
BranchTrueFalseTotal
$? == 0 or die "--host-dac requires a root worker\n" 0 0 0
994 } else {
995 0 ▶ $> == 0 or die "--host-dac requires a root worker\n";
Branch: 1 branch
BranchTrueFalseTotal
$> == 0 or die "--host-dac requires a root worker\n" 0 0 0
996 }
997 }
998  
999 6 my @runtime_path = qw(
1000 /usr
1001 /bin
1002 /sbin
1003 /lib
1004 /lib64
1005 /etc/ld.so.cache
1006 /etc/alternatives
1007 /etc/fonts
1008 /etc/localtime
1009 /etc/ssl/openssl.cnf
1010 /etc/ssl/certs
1011 /etc/pki/tls/openssl.cnf
1012 /etc/pki/tls/certs
1013 /etc/pki/ca-trust
1014 /etc/nsswitch.conf
1015 /etc/hosts
1016 /etc/resolv.conf
1017 );
1018 6 ▶@runtime_path = grep -e, @runtime_path unless $remote;
Branch: 1 branch
BranchTrueFalseTotal
unless $remote 6 0 6
1019  
1020 6 my (@workdir, @workdir_identity);
1021 6 ▶if (defined $exec_cmd) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $exec_cmd) { } 0 6 6
1022 0 @workdir = Cwd::abs_path ".";
1023 0 ▶ @workdir or die "cannot resolve current directory\n";
Branch: 1 branch
BranchTrueFalseTotal
@workdir or die "cannot resolve current directory\n" 0 0 0
1024 0 ▶ utf8::decode $workdir[0] or die "workdir is not UTF-8\n";
Branch: 1 branch
BranchTrueFalseTotal
utf8::decode($workdir[0]) or die "workdir is not UTF-8\n" 0 0 0
1025 0 @workdir_identity = @workdir;
1026 } else {
1027 6 for my $path (@ARGV) {
1028 6 my $workdir;
1029 6 ▶ if ($remote) {
Branch: 1 branch
BranchTrueFalseTotal
if ($remote) { } 0 6 6
1030 0 ▶ $path =~ m{\A/} or die "remote workdirs must be absolute paths\n";
Branch: 1 branch
BranchTrueFalseTotal
$path =~ m[\A/]u or die "remote workdirs must be absolute paths\n" 0 0 0
1031 0 $workdir = $path;
1032 } else {
1033 6 $workdir = Cwd::abs_path $path;
1034 6 ▶ -d $workdir or die "invalid workdir '$path'\n";
Branch: 1 branch
BranchTrueFalseTotal
-d $workdir or die "invalid workdir '${path}'\n" 6 0 6
1035 }
1036 6 ▶ utf8::decode $workdir or die "workdir is not UTF-8\n";
Branch: 1 branch
BranchTrueFalseTotal
utf8::decode($workdir) or die "workdir is not UTF-8\n" 6 0 6
1037 6 my $identity = $path;
1038 6 ▶ utf8::decode $identity or die "workdir identity is not UTF-8\n";
Branch: 1 branch
BranchTrueFalseTotal
utf8::decode($identity) or die "workdir identity is not UTF-8\n" 6 0 6
1039 6 push @workdir, $workdir;
1040 6 push @workdir_identity, $identity;
1041 }
1042 }
1043  
1044 6 my $home = $ENV{HOME};
1045 6 ▶$home =~ m{\A/} and -d $home
Branch: 1 branch
BranchTrueFalseTotal
$home =~ m[\A/]u and -d $home or die "HOME must name an absolute existing directory\n" 6 0 6
Condition33%1/3
$home =~ m[\A/]u and -d $home
!ll&&!rl&&r
006
MC/DC0%0/2
$home =~ m[\A/]u and -d $home
$home =~ m[\A/]u -d $home
Truth table33%1/3
A and B
A= $home =~ m[\A/]uB= -d $home
ABresult
0X0
100
111
1046 or die "HOME must name an absolute existing directory\n";
1047 6 ▶$home = Cwd::abs_path $home
Condition50%1/2
$home // die("cannot resolve HOME\n")
l!l
60
MC/DC0%0/1
$home // die("cannot resolve HOME\n")
$home
Truth table50%1/2
A
A= $home
Aresult
11
00
1048 // die "cannot resolve HOME\n";
1049 6 ▶utf8::decode $home
Branch: 1 branch
BranchTrueFalseTotal
utf8::decode($home) or die "HOME is not a valid UTF-8 path\n" 6 0 6
1050 or die "HOME is not a valid UTF-8 path\n";
1051  
1052 6 my $config_home;
1053 6 ▶unless (defined $exec_cmd) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $exec_cmd) 6 0 6
1054 6 $config_home = $ENV{XDG_CONFIG_HOME};
1055 6 ▶ if (length $config_home) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $config_home) { } 6 0 6
1056 6 ▶ $config_home =~ m{\A/}
Branch: 1 branch
BranchTrueFalseTotal
$config_home =~ m[\A/]u or die "permission config directory must be absolute\n" 6 0 6
1057 or die "permission config directory must be absolute\n";
1058 6 ▶ utf8::decode $config_home
Branch: 1 branch
BranchTrueFalseTotal
utf8::decode($config_home) or die "permission config directory is not UTF-8\n" 6 0 6
1059 or die "permission config directory is not UTF-8\n";
1060 } else {
1061 0 $config_home = "$home/.config";
1062 }
1063 }
1064  
1065 6 my (%remote_program, @remote_vcs_marker, $remote_umask);
1066 6 ▶my @tmp_realpath = map { Cwd::abs_path $_ || $_ } qw(/tmp /var/tmp);
Condition33%1/3
$_ || $_
l!l&&r!l&&!r
1200
MC/DC0%0/2
$_ || $_
$_ $_
Truth table33%1/3
A || B
A= $_B= $_
ABresult
1X1
011
000
1067 6 ▶if ($remote) {
Branch: 1 branch
BranchTrueFalseTotal
if ($remote) 0 6 6
1068 # probe once per startup; the local MCP frontend keeps the result.
1069 # no remote package beyond core Perl, nor a remote installed mcp-fs.
1070 0 my $probe = q{#perl
1071 use 5.008004;
1072 use Cwd ();
1073 binmode STDOUT;
1074  
1075 my ($path, $mode, $bwrap_name, $nwork) = splice @ARGV, 0, 4;
1076 my @work = splice @ARGV, 0, $nwork;
1077 my $nmount = shift @ARGV;
1078 my @mount = splice @ARGV, 0, $nmount;
1079 my $nrun = shift @ARGV;
1080 my @runtime = splice @ARGV, 0, $nrun;
1081 $ENV{PATH} = $path;
1082  
1083 my $find_executable = sub {
1084 my ($name) = @_;
1085 my @path = $name =~ m{/} ? ($name)
1086 : map { (length $_ ? $_ : ".") . "/$name" } split /:/, $ENV{PATH}, -1;
1087 for (@path) {
1088 next unless -f $_ && -x _;
1089 return m{\A/} ? $_ : Cwd::getcwd () . "/$_";
1090 }
1091 ""
1092 };
1093  
1094 my $home = $ENV{HOME} || (getpwuid $<)[7];
1095 $home =~ m{\A/} && -d $home or die "remote HOME is not an absolute directory\n";
1096 $home = Cwd::abs_path $home or die "cannot resolve remote HOME\n";
1097 my @resolved = map {
1098 my $path = Cwd::abs_path $_;
1099 -d $path or die "invalid remote workdir '$_'\n";
1100 $path
1101 } @work;
1102 -e $_ or die "invalid remote mount '$_'\n" for @mount;
1103  
1104 my $bwrap = $mode eq "none" ? "" : $find_executable->($bwrap_name);
1105 $bwrap or die "remote bubblewrap executable not found: $bwrap_name\n"
1106 if $mode eq "bwrap";
1107  
1108 my %marker = (cvs => "CVS", git => ".git", hg => ".hg", svn => ".svn");
1109 my @markers = map {
1110 my $dir = $_;
1111 join ",", grep {
1112 lstat "$dir/$marker{$_}" && (-d _ || -l _ || ($_ eq "git" && -f _))
1113 } sort keys %marker
1114 } @resolved;
1115  
1116 my %test = (
1117 find => [[qw(--version)], qr/^find \(GNU findutils\)/m],
1118 grep => [[qw(--version)], qr/^grep \(GNU grep\)/m],
1119 patch => [[qw(--version)], qr/^GNU patch /m],
1120 sed => [[qw(--version)], qr/\(GNU sed\)/],
1121 );
1122 my @program;
1123 while (@ARGV) {
1124 my ($name, $wanted, $explicit) = splice @ARGV, 0, 3;
1125 my $found = $find_executable->($wanted);
1126 if ($found && !$explicit && $test{$name}) {
1127 my ($args, $match) = @{$test{$name}};
1128 my $ok = open my $fh, "-|", $found, @$args;
1129 if ($ok) {
1130 my $output = do { local $/; <$fh> };
1131 $ok = close $fh && $output =~ $match;
1132 }
1133 $found = "" unless $ok;
1134 }
1135 push @program, $found;
1136 }
1137  
1138 print pack "N/a*", pack "(w/a*)*",
1139 $home, $bwrap, scalar umask, $>, @resolved, @markers,
1140 (map { -e $_ ? $_ : "" } @runtime), @program,
1141 (map { Cwd::abs_path $_ || $_ } qw(/tmp /var/tmp));
1142 };
1143  
1144 0 my @names = qw(perl find grep patch sed git svn cvs hg);
1145 my @args = (
1146 $sandbox_path, $sandbox_mode, $bwrap, scalar @workdir,
1147 0 (map { AnyEvent::MCP::utf8enc $_ } @workdir),
1148 0 scalar (grep $_->[0] =~ /\Amount\./, @mount), (map { AnyEvent::MCP::utf8enc $_->[2] } grep $_->[0] =~ /\Amount\./, @mount),
1149 scalar @runtime_path, @runtime_path,
1150 0 ▶ (map { ($_, $executable{$_} || $_, length $settings{"executable.$_"} ? 1 : 0) } @names),
Branch: 1 branch
BranchTrueFalseTotal
length $settings{"executable.$_"} ? : 0 0 0
Condition0%0/3
$executable{$_} || $_
l!l&&r!l&&!r
000
MC/DC0%0/2
$executable{$_} || $_
$executable{$_} $_
Truth table0%0/3
A || B
A= $executable{$_}B= $_
ABresult
1X1
011
000
1151 );
1152 0 ▶ my @command = ($executable{perl} || "perl", "-e", $probe, @args);
Condition0%0/2
$executable{'perl'} || 'perl'
l!l
00
MC/DC0%0/1
$executable{'perl'} || 'perl'
$executable{'perl'}
Truth table0%0/2
A
A= $executable{'perl'}
Aresult
11
00
1153 0 my $pid = IPC::Open2::open2 (my $out, my $in, @rsh, $host, $remote_command);
1154 0 binmode $in;
1155 0 binmode $out;
1156 0 ▶ print {$in} $remote_launcher, fs_remote_frame ("", @command) or die "remote probe input: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
print {$in;} $remote_launcher, fs_remote_frame("", @command) or die "remote probe input: $!\n" 0 0 0
1157 0 ▶ close $in or die "remote probe input: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
close $in or die "remote probe input: $!\n" 0 0 0
1158 0 my $output = do { local $/; <$out> };
1159 0 close $out;
1160 0 waitpid $pid, 0;
1161 0 ▶ $? == 0 or die "remote probe failed (wait status $?)\n";
Branch: 1 branch
BranchTrueFalseTotal
$? == 0 or die "remote probe failed (wait status $?)\n" 0 0 0
1162 0 my $declared = unpack "N", substr $output, 0, 4;
1163 0 ▶ length ($output) >= 4 && length ($output) == $declared + 4
Branch: 1 branch
BranchTrueFalseTotal
length $output >= 4 and length $output == $declared + 4 or die 'invalid remote probe frame (received ' . length($output) . " bytes, declared $declared, first bytes " . unpack("H*", substr($output, 0, 16)) . ")\n" 0 0 0
Condition0%0/3
length $output >= 4 and length $output == $declared + 4
!ll&&!rl&&r
000
MC/DC0%0/2
length $output >= 4 and length $output == $declared + 4
length $output >= 4 length $output == $declared + 4
Truth table0%0/3
A and B
A= length $output >= 4B= length $output == $declared + 4
ABresult
0X0
100
111
1164 or die "invalid remote probe frame (received " . length ($output)
1165 . " bytes, declared $declared, first bytes " . unpack ("H*", substr ($output, 0, 16)) . ")\n";
1166 0 my @values = unpack "(w/a*)*", substr $output, 4;
1167 0 my $expected = 6 + 2 * @workdir + @runtime_path + @names;
1168 0 ▶ @values == $expected or die "invalid remote probe result\n";
Branch: 1 branch
BranchTrueFalseTotal
@values == $expected or die "invalid remote probe result\n" 0 0 0
1169 0 $home = shift @values;
1170 0 $bwrap = shift @values;
1171 0 $remote_umask = shift @values;
1172 0 my $worker_uid = shift @values;
1173 0 ▶ $host_dac && $worker_uid != 0
Branch: 1 branch
BranchTrueFalseTotal
$host_dac and $worker_uid != 0 and die "--host-dac needs root privileges on the remote host\n" 0 0 0
Condition0%0/3
$host_dac and $worker_uid != 0
!ll&&!rl&&r
000
MC/DC0%0/2
$host_dac and $worker_uid != 0
$host_dac $worker_uid != 0
Truth table0%0/3
A and B
A= $host_dacB= $worker_uid != 0
ABresult
0X0
100
111
1174 and die "--host-dac needs root privileges on the remote host\n";
1175 0 @workdir = splice @values, 0, @workdir;
1176 0 ▶ @remote_vcs_marker = map { [length $_ ? split /,/, $_ : ()] } splice @values, 0, @workdir;
Branch: 1 branch
BranchTrueFalseTotal
length $_ ? : 0 0 0
1177 0 @runtime_path = grep length, splice @values, 0, @runtime_path;
1178 0 @remote_program{@names} = splice @values, 0, @names;
1179 0 @tmp_realpath = splice @values, 0, 2;
1180 0 for ($home, @workdir, @runtime_path, @tmp_realpath) {
1181 0 ▶ utf8::decode $_ or die "remote path is not UTF-8\n";
Branch: 1 branch
BranchTrueFalseTotal
utf8::decode($_) or die "remote path is not UTF-8\n" 0 0 0
1182 }
1183 # remote executable names and the bwrap path are OS bytes, like local discovery.
1184 }
1185  
1186 6 ▶$host_dac && !$bwrap and die "--host-dac requires bubblewrap\n";
Branch: 1 branch
BranchTrueFalseTotal
$host_dac and not $bwrap and die "--host-dac requires bubblewrap\n" 0 6 6
Condition33%1/3
$host_dac and not $bwrap
!ll&&!rl&&r
600
MC/DC0%0/2
$host_dac and not $bwrap
$host_dac not $bwrap
Truth table33%1/3
A and not(B)
A= $host_dacB= not $bwrap
ABresult
0X0
100
111
1187 6 my ($workdir_ids, $workdir_refresh);
1188  
1189 6 ▶unless (defined $exec_cmd) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $exec_cmd) 6 0 6
1190 # IDs represent logical pathnames, not physical symlink destinations.
1191 6 $workdir_ids = AnyEvent::MCP::Workdirs->new (
1192 file => "$config_home/anyevent-mcp/fs-workdir-ids.json",
1193 paths => [map File::Spec::Unix->rel2abs ($_), @workdir_identity],
1194 );
1195  
1196 6 my $interval = .75 * $workdir_ids->{expiry};
1197 3 ▶ $workdir_refresh = AE::timer 0, $interval, sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1198 3 $workdir_ids->refresh;
1199 6 };
1200 }
1201  
1202 6 my %sandbox_grant = (
1203 "workdir-read" => [],
1204 "workdir-write" => ["workdir-read"],
1205 "all-workdirs-read" => ["workdir-read"],
1206 "all-workdirs-write" => [qw(all-workdirs-read workdir-write)],
1207 "homedir-read" => [],
1208 "homedir-write" => ["homedir-read"],
1209 "world-read" => [qw(all-workdirs-read homedir-read)],
1210 "world-write" => [qw(world-read all-workdirs-write homedir-write shared-tmp)],
1211 "network" => [],
1212 "ssh-agent" => ["network"],
1213 "long-running" => [],
1214 "shared-tmp" => [],
1215 "host-proc" => [],
1216 );
1217  
1218 6 ▶my %sandbox_grant_description = (
Branch: 1 branch
BranchTrueFalseTotal
$bwrap ? : 0 6 6
1219 "workdir-read" => "Read files in the selected workdir",
1220 "workdir-write" => "Change files in the selected workdir",
1221 "all-workdirs-read" => "Read files in all configured workdirs",
1222 "all-workdirs-write" => "Change files in all configured workdirs",
1223 "homedir-read" => "Read files in your home directory",
1224 "homedir-write" => "Change files in your home directory",
1225 "world-read" => "Read the host filesystem",
1226 "world-write" => "Change the host filesystem",
1227 "network" => "Use network connections",
1228 "ssh-agent" => "Use your SSH agent to authenticate, read known_hosts and use network connections",
1229 "long-running" => "Run commands longer than five minutes",
1230 "shared-tmp" => "Access host temporary directories",
1231 "host-proc" => $bwrap ? "Host process access (unavailable with bubblewrap)"
1232 : "Full access to host processes",
1233 );
1234  
1235 6 my @exec_default_sandbox_grants = ("workdir-read");
1236  
1237 6 ▶my $umask = $remote ? $remote_umask : umask;
Branch: 1 branch
BranchTrueFalseTotal
$remote ? : 0 6 6
1238  
1239 6 my $permissions;
1240 $permissions = AnyEvent::MCP::Server::Permissions->new (
1241 sandbox_grants => \%sandbox_grant,
1242 0 ▶ sandbox_grant_descriptions => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1243 0 my ($request) = @_;
1244  
1245 0 my %description = %sandbox_grant_description;
1246 0 ▶ if (defined $request->{selected_workdir}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $request->{"selected_workdir"}) 0 0 0
1247 my $name = JSON::XS->new->utf8 (0)->allow_nonref
1248 0 ->encode ($request->{selected_workdir});
1249 0 $description{"workdir-read"} = "Read files in selected workdir $name";
1250 0 $description{"workdir-write"} = "Change files in selected workdir $name";
1251 }
1252 0 \%description
1253 },
1254 6 ▶ sandbox_implementation => $bwrap ? "bubblewrap" : "NONE - UNSANDBOXED (full host-user privileges)",
Branch: 2 branches
BranchTrueFalseTotal
unless defined $exec_cmd 6 0 6
$bwrap ? : 0 6 6
1255 actions => {
1256 inspect => "Inspect resource metadata and enumerate names",
1257 read => "Read resource contents",
1258 write => "Modify resource contents",
1259 manage => "Rename, remove, and manage filesystem paths",
1260 exec => "Run arbitrary commands",
1261 "vcs-diff" => "Read working-copy differences using a VCS client",
1262 "vcs-status" => "Read working-copy status using a VCS client",
1263 "vcs-log" => "Read revision history using a VCS client",
1264 },
1265 name => $name,
1266 file => "$config_home/anyevent-mcp/rules/fs-$name.ini",
1267 ) unless defined $exec_cmd;
1268  
1269 6 mcp_permissions $permissions;
1270  
1271 # permissions group tools by their kind of access, not by MCP tool name.
1272 6 my %tool_action = (
1273 stat => "inspect", list => "inspect", find => "inspect",
1274 "file-read" => "read", "read-lines" => "read", grep => "read",
1275 "file-write" => "write", "file-patch" => "write",
1276 "path-op" => "manage", exec => "exec",
1277 );
1278  
1279 # normalize an API pathname lexically against its selected workdir.
1280 13 ▶sub fs_path {
Subroutine fs_path: called CC=9 SCAR=24.8
1281 13 my ($workdir, $path) = @_;
1282  
1283 13 ▶ !ref $path and length $path and $path !~ /\0/
Branch: 1 branch
BranchTrueFalseTotal
not ref $path and length $path and not $path =~ /\0/u or die "path must be a nonempty string without NUL\n" 13 0 13
Condition33%2/6
not ref $path and length $path and not $path =~ /\0/u
!ll&&!rl&&r
0013
not ref $path and length $path
!ll&&!rl&&r
0013
MC/DC0%0/3
not ref $path and length $path and not $path =~ /\0/u
not ref $path length $path not $path =~ /\0/u
Truth table25%1/4
not(A) and B and not(C)
A= not ref $pathB= length $pathC= not $path =~ /\0/u
ABCresult
0XX0
10X0
1100
1111
1284 or die "path must be a nonempty string without NUL\n";
1285 13 ▶ $path = "$workdir/$path" unless $path =~ m{\A/};
Branch: 1 branch
BranchTrueFalseTotal
unless $path =~ m[\A/]u 13 0 13
1286  
1287 13 my @part;
1288  
1289 13 for (split m{/+}, $path) {
1290 52 ▶ next if !length or $_ eq ".";
Branch: 1 branch
BranchTrueFalseTotal
if not length $_ or $_ eq "." 13 39 52
Condition66%2/3
not length $_ or $_ eq "."
l!l&&r!l&&!r
13039
MC/DC50%1/2
not length $_ or $_ eq "."
not length $_ $_ eq "."
Truth table66%2/3
not(A) or B
A= not length $_B= $_ eq "."
ABresult
1X1
011
000
1291 39 ▶ if ($_ eq "..") {
Branch: 1 branch
BranchTrueFalseTotal
if ($_ eq '..') { } 0 39 39
1292 0 pop @part;
1293 } else {
1294 39 push @part, $_;
1295 }
1296 }
1297  
1298 13 "/" . join "/", @part
1299 }
1300  
1301 # test pathname containment without resolving symlinks.
1302 15 ▶sub fs_inside {
Subroutine fs_inside: called CC=3 SCAR=13.1
1303 15 my ($path, $directory) = @_;
1304  
1305 15 ▶ $directory eq "/" or $path eq $directory or (index $path, "$directory/") == 0
Branch: 1 branch
BranchTrueFalseTotal
$directory eq "/" or $path eq $directory or index($path, "$directory/") == 0 0 15 15
Condition33%1/3
$directory eq "/" or $path eq $directory
l!l&&r!l&&!r
0015
MC/DC0%0/2
$directory eq "/" or $path eq $directory
$directory eq "/" $path eq $directory
Truth table33%1/3
A or B
A= $directory eq "/"B= $path eq $directory
ABresult
1X1
011
000
1306 }
1307  
1308 # classify relative to the selected workdir, not any configured workdir.
1309 13 ▶sub fs_path_capability {
Subroutine fs_path_capability: called CC=6 SCAR=32.9
1310 13 my ($workdir, $path, $mode) = @_;
1311  
1312 13 ▶ return "workdir-$mode"
Branch: 1 branch
BranchTrueFalseTotal
if fs_inside($path, $workdir) 13 0 13
1313 if fs_inside $path, $workdir;
1314 return "all-workdirs-$mode"
1315 0 ▶ if grep { fs_inside $path, $_ } @workdir;
Branch: 1 branch
BranchTrueFalseTotal
if grep {fs_inside($path, $_);} @workdir 0 0 0
1316 0 ▶ return "homedir-$mode" if fs_inside $path, $home;
Branch: 1 branch
BranchTrueFalseTotal
if fs_inside($path, $home) 0 0 0
1317 0 ▶ return "shared-tmp" if (fs_inside $path, "/tmp") or (fs_inside $path, "/var/tmp");
Branch: 1 branch
BranchTrueFalseTotal
if fs_inside($path, "/tmp") or fs_inside($path, "/var/tmp") 0 0 0
Condition0%0/3
fs_inside($path, "/tmp") or fs_inside($path, "/var/tmp")
l!l&&r!l&&!r
000
MC/DC0%0/2
fs_inside($path, "/tmp") or fs_inside($path, "/var/tmp")
fs_inside($path, "/tmp") fs_inside($path, "/var/tmp")
Truth table0%0/3
A or B
A= fs_inside($path, "/tmp")B= fs_inside($path, "/var/tmp")
ABresult
1X1
011
000
1318  
1319 0 "world-$mode"
1320 }
1321  
1322 # persist selected-workdir identities only where the requested authority
1323 # actually depends on that selection. Broad all-workdirs grants are unscoped.
1324 13 ▶sub fs_grant_workdir {
Subroutine fs_grant_workdir: called CC=5 SCAR=18.9
1325 13 my ($identity, $grants) = @_;
1326  
1327 13 my $have = $permissions->closure ($grants);
1328 13 ▶ return $identity if $have->{"workdir-write"} && !$have->{"all-workdirs-write"};
Branch: 1 branch
BranchTrueFalseTotal
if $have->{"workdir-write"} and not $have->{"all-workdirs-write"} 0 13 13
Condition33%1/3
$have->{"workdir-write"} and not $have->{"all-workdirs-write"}
!ll&&!rl&&r
0130
MC/DC0%0/2
$have->{"workdir-write"} and not $have->{"all-workdirs-write"}
$have->{"workdir-write"} not $have->{"all-workdirs-write"}
Truth table33%1/3
A and not(B)
A= $have->{"workdir-write"}B= not $have->{"all-workdirs-write"}
ABresult
0X0
100
111
1329 13 ▶ return $identity if $have->{"workdir-read"} && !$have->{"all-workdirs-read"};
Branch: 1 branch
BranchTrueFalseTotal
if $have->{"workdir-read"} and not $have->{"all-workdirs-read"} 0 13 13
Condition33%1/3
$have->{"workdir-read"} and not $have->{"all-workdirs-read"}
!ll&&!rl&&r
0130
MC/DC0%0/2
$have->{"workdir-read"} and not $have->{"all-workdirs-read"}
$have->{"workdir-read"} not $have->{"all-workdirs-read"}
Truth table33%1/3
A and not(B)
A= $have->{"workdir-read"}B= not $have->{"all-workdirs-read"}
ABresult
0X0
100
111
1330 undef
1331 13 }
1332  
1333 # permission prompts display the selected, verbatim configured workdir next
1334 # to workdir-specific grant choices. This is information, not a rule scope.
1335 13 ▶sub fs_require_permission {
Subroutine fs_require_permission: called CC=1 SCAR=0.0
1336 13 my ($req, $identity, $request) = @_;
1337  
1338 13 $request->{selected_workdir} = $identity;
1339 13 $req->require_permission ($request)
1340 }
1341  
1342 # direct execution has no filesystem, network or process isolation. Request
1343 # every grant the process effectively receives, regardless of client wishes.
1344 6 my @unsandboxed_grants = qw(world-write network shared-tmp host-proc);
1345 13 ▶sub fs_effective_grants {
Subroutine fs_effective_grants: called CC=2 SCAR=7.2
1346 13 ▶ return @_ if $bwrap;
Branch: 1 branch
BranchTrueFalseTotal
if $bwrap 0 13 13
1347 13 (@unsandboxed_grants, grep $_ eq "long-running", @_)
1348 }
1349  
1350 # one worker needs the combined sandbox authority for every path it will access.
1351 13 ▶sub fs_permission_dimensions {
Subroutine fs_permission_dimensions: called CC=5 SCAR=16.5
1352 13 my ($workdir, $subject, $choices) = @_;
1353 13 my %dimensions;
1354  
1355 13 ▶ my $host_id = $remote ? "remote $host" : "local";
Branch: 1 branch
BranchTrueFalseTotal
$remote ? : 0 13 13
1356 $dimensions{host} = {
1357 13 ▶ label => "Host", value => $host_id,
Branch: 1 branch
BranchTrueFalseTotal
$remote ? : 0 13 13
1358 choices => [
1359 { label => "This host: " . ($remote ? $host : "local"), match => $host_id },
1360 { label => "All hosts", match => "^" },
1361 ],
1362 };
1363  
1364 $dimensions{workdir} = {
1365 13 ▶ label => "Workdir", value => $workdir,
Branch: 1 branch
BranchTrueFalseTotal
if defined $workdir 0 13 13
1366 choices => [
1367 { label => "This workdir: $workdir", match => $workdir },
1368 { label => "Any configured workdir, including future ones", match => "^" },
1369 ],
1370 } if defined $workdir;
1371 $dimensions{subject} = {
1372 13 ▶ label => "Subject", value => $subject, choices => $choices,
Branch: 1 branch
BranchTrueFalseTotal
if defined $subject 2 11 13
1373 } if defined $subject;
1374  
1375 13 \%dimensions
1376 }
1377  
1378 11 ▶sub fs_require_paths {
Subroutine fs_require_paths: called CC=5 SCAR=16.2
1379 11 my ($req, $workdir, $identity, $paths, $mode, $reason, $details) = @_;
1380  
1381 11 my %seen;
1382 11 $paths = [grep !$seen{$_}++, @$paths];
1383 11 my %need = map { (fs_path_capability $workdir, $_, $mode) => 1 } @$paths;
1384 11 %need = map { $_ => 1 } fs_effective_grants (keys %need);
1385 11 my @grants = sort keys %need;
1386 my $grant = fs_require_permission ($req, $identity, {
1387 tool => $req->{tool},
1388 action => $tool_action{$req->{tool}},
1389 11 ▶ dimensions => fs_permission_dimensions (fs_grant_workdir ($identity, \@grants)),
Branch: 1 branch
BranchTrueFalseTotal
defined $details ? : 0 11 11
Condition100%2/2
$reason // qq[$req->{"tool"} ] . join(", ", @$paths)
l!l
92
MC/DC100%1/1
$reason // qq[$req->{"tool"} ] . join(", ", @$paths)
$reason
Truth table100%2/2
A
A= $reason
Aresult
11
00
1390 paths => $paths,
1391 sandbox_grants => \@grants,
1392 reason => $reason // "$req->{tool} " . join (", ", @$paths),
1393 (defined $details ? (details => $details) : ()),
1394 });
1395  
1396 11 my $have = $permissions->closure ($grant);
1397 11 for my $capability (sort keys %need) {
1398 44 ▶ $have->{$capability}
Branch: 1 branch
BranchTrueFalseTotal
$have->{$capability} or die qq[permission reduced below $capability for $req->{"tool"}\n] 44 0 44
1399 or die "permission reduced below $capability for $req->{tool}\n";
1400 }
1401  
1402 11 [sort keys %$have]
1403 }
1404  
1405 # test whether the granted capability set makes this pathname writable.
1406 0 ▶sub fs_writable {
Subroutine fs_writable: not called CC=10 SCAR=47.0
1407 0 my ($workdir, $path, $have) = @_;
1408  
1409 $have->{"world-write"}
1410 0 ▶ or ($have->{"all-workdirs-write"} and (grep { fs_inside $path, $_ } @workdir))
Condition0%0/12
$have->{"workdir-write"} and fs_inside($path, $workdir)
!ll&&!rl&&r
000
$have->{"homedir-write"} and fs_inside($path, $home)
!ll&&!rl&&r
000
$have->{"shared-tmp"} and fs_inside($path, "/tmp") || fs_inside($path, "/var/tmp")
!ll&&!rl&&r
000
fs_inside($path, "/tmp") or fs_inside($path, "/var/tmp")
l!l&&r!l&&!r
000
MC/DC0%0/2
$have->{"workdir-write"} and fs_inside($path, $workdir)
$have->{"workdir-write"} fs_inside($path, $workdir)
MC/DC0%0/2
$have->{"homedir-write"} and fs_inside($path, $home)
$have->{"homedir-write"} fs_inside($path, $home)
MC/DC0%0/3
$have->{"shared-tmp"} and fs_inside($path, "/tmp") || fs_inside($path, "/var/tmp")
$have->{"shared-tmp"} fs_inside($path, "/tmp") fs_inside($path, "/var/tmp")
Truth table0%0/3
A and B
A= $have->{"workdir-write"}B= fs_inside($path, $workdir)
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $have->{"homedir-write"}B= fs_inside($path, $home)
ABresult
0X0
100
111
Truth table0%0/4
A and B or C
A= $have->{"shared-tmp"}B= fs_inside($path, "/tmp")C= fs_inside($path, "/var/tmp")
ABCresult
0XX0
1000
11X1
1011
1411 or ($have->{"workdir-write"} and fs_inside $path, $workdir)
1412 or ($have->{"homedir-write"} and (fs_inside $path, $home))
1413 0 ▶ or ($have->{"shared-tmp"} and ((fs_inside $path, "/tmp") or (fs_inside $path, "/var/tmp")))
Branch: 1 branch
BranchTrueFalseTotal
$have->{"world-write"} or $have->{"all-workdirs-write"} and grep {fs_inside($path, $_);} @workdir or $have->{"workdir-write"} and fs_inside($path, $workdir) or $have->{"homedir-write"} and fs_inside($path, $home) or $have->{"shared-tmp"} and fs_inside($path, "/tmp") || fs_inside($path, "/var/tmp") 0 0 0
Condition0%0/15
$have->{'world-write'} || $have->{'all-workdirs-write'} && grep({fs_inside($path, $_);} @workdir) || $have->{'workdir-write'} && fs_inside($path, $workdir) || $have->{'homedir-write'} && fs_inside($path, $home) || $have->{'shared-tmp'} && (fs_inside($path, '/tmp') || fs_inside($path, '/var/tmp'))
l!l&&r!l&&!r
000
$have->{"world-write"} or $have->{"all-workdirs-write"} and grep {fs_inside($path, $_);} @workdir or $have->{"workdir-write"} and fs_inside($path, $workdir) or $have->{"homedir-write"} and fs_inside($path, $home)
l!l&&r!l&&!r
000
$have->{"world-write"} or $have->{"all-workdirs-write"} and grep {fs_inside($path, $_);} @workdir or $have->{"workdir-write"} and fs_inside($path, $workdir)
l!l&&r!l&&!r
000
$have->{"world-write"} or $have->{"all-workdirs-write"} and grep {fs_inside($path, $_);} @workdir
l!l&&r!l&&!r
000
$have->{"all-workdirs-write"} and grep {fs_inside($path, $_);} @workdir
!ll&&!rl&&r
000
MC/DC0%0/6
$have->{'world-write'} || $have->{'all-workdirs-write'} && grep({fs_inside($path, $_);} @workdir) || $have->{'workdir-write'} && fs_inside($path, $workdir) || $have->{'homedir-write'} && fs_inside($path, $home) || $have->{'shared-tmp'} && (fs_inside($path, '/tmp') || fs_inside($path, '/var/tmp'))
$have->{"world-write"} $have->{"all-workdirs-write"} grep {fs_inside($path, $_);} @workdir $have->{"workdir-write"} and fs_inside($path, $workdir) $have->{"homedir-write"} and fs_inside($path, $home) $have->{'shared-tmp'} && (fs_inside($path, '/tmp') || fs_inside($path, '/var/tmp'))
Truth table0%0/10
A or B and C or D or E || F
A= $have->{"world-write"}B= $have->{"all-workdirs-write"}C= grep {fs_inside($path, $_);} @workdirD= $have->{"workdir-write"} and fs_inside($path, $workdir)E= $have->{"homedir-write"} and fs_inside($path, $home)F= $have->{'shared-tmp'} && (fs_inside($path, '/tmp') || fs_inside($path, '/var/tmp'))
ABCDEFresult
1XXXXX1
011XXX1
00X1XX1
0101XX1
00X01X1
01001X1
00X0011
0100011
00X0000
0100000
1414 }
1415  
1416 # build the bubblewrap argv implementing the granted sandbox authority.
1417 13 ▶sub fs_sandbox {
Subroutine fs_sandbox: called CC=99 SCAR=90.0
1418 13 my ($workdir, $sandbox_grants) = @_;
1419  
1420 13 my $have = {};
1421 13 my @todo = @$sandbox_grants;
1422 13 ▶ while (@todo) {
Branch: 1 branch
BranchTrueFalseTotal
if (@todo) 272 13 285
1423 272 my $capability = pop @todo;
1424 272 ▶ exists $sandbox_grant{$capability} or die "Unknown permission capability '$capability'\n";
Branch: 1 branch
BranchTrueFalseTotal
exists $sandbox_grant{$capability} or die "Unknown permission capability '${capability}'\n" 272 0 272
1425 272 ▶ next if $have->{$capability}++;
Branch: 1 branch
BranchTrueFalseTotal
if $have->{$capability}++ 129 143 272
1426 143 push @todo, @{$sandbox_grant{$capability}};
1427 }
1428  
1429 13 ▶ unless ($bwrap) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($bwrap) 13 0 13
1430 13 ▶ unless (defined $exec_cmd) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $exec_cmd) 13 0 13
1431 $have->{$_} or die "unsandboxed execution needs $_ grant\n"
1432 13 ▶ for @unsandboxed_grants;
Branch: 1 branch
BranchTrueFalseTotal
$have->{$_} or die "unsandboxed execution needs $_ grant\n" 52 0 52
1433 }
1434 13 return ();
1435 }
1436  
1437 die "host-proc sandbox authority is unresolved and unavailable in v1\n"
1438 0 ▶ if $have->{"host-proc"};
Branch: 1 branch
BranchTrueFalseTotal
if $have->{"host-proc"} 0 0 0
1439  
1440 0 my $workdir_bytes = AnyEvent::MCP::utf8enc $workdir;
1441 0 my $home_bytes = AnyEvent::MCP::utf8enc $home;
1442 0 my $configured_root = grep $_->[2] eq "/", @mount;
1443 0 ▶ my $configured_root_write = grep $_->[2] eq "/" && $_->[1] eq "rw", @mount;
Condition0%0/3
$_->[2] eq '/' && $_->[1] eq 'rw'
!ll&&!rl&&r
000
MC/DC0%0/2
$_->[2] eq '/' && $_->[1] eq 'rw'
$_->[2] eq '/' $_->[1] eq 'rw'
Truth table0%0/3
A && B
A= $_->[2] eq '/'B= $_->[1] eq 'rw'
ABresult
0X0
100
111
1444 my $root_read = $configured_root || $have->{"world-read"}
1445 || ($have->{"workdir-read"} && $workdir eq "/")
1446 0 ▶ || ($have->{"all-workdirs-read"} && grep $_ eq "/", @workdir);
Condition0%0/15
$configured_root || $have->{'world-read'} || $have->{'workdir-read'} && $workdir eq '/' || $have->{'all-workdirs-read'} && grep(($_ eq '/'), @workdir)
l!l&&r!l&&!r
000
$configured_root or $have->{"world-read"} or $have->{"workdir-read"} and $workdir eq "/"
l!l&&r!l&&!r
000
$configured_root or $have->{"world-read"}
l!l&&r!l&&!r
000
$have->{"workdir-read"} and $workdir eq "/"
!ll&&!rl&&r
000
$have->{"all-workdirs-read"} and grep(($_ eq "/"), @workdir)
!ll&&!rl&&r
000
MC/DC0%0/6
$configured_root || $have->{'world-read'} || $have->{'workdir-read'} && $workdir eq '/' || $have->{'all-workdirs-read'} && grep(($_ eq '/'), @workdir)
$configured_root $have->{"world-read"} $have->{"workdir-read"} $workdir eq "/" $have->{"all-workdirs-read"} grep(($_ eq "/"), @workdir)
Truth table0%0/9
A or B or C and D || E and F
A= $configured_rootB= $have->{"world-read"}C= $have->{"workdir-read"}D= $workdir eq "/"E= $have->{"all-workdirs-read"}F= grep(($_ eq "/"), @workdir)
ABCDEFresult
1XXXXX1
01XXXX1
0011XX1
000X111
0010111
000X0X0
000X100
00100X0
0010100
1447 my $root_write = $configured_root_write || $have->{"world-write"}
1448 || ($have->{"workdir-write"} && $workdir eq "/")
1449 0 ▶ || ($have->{"all-workdirs-write"} && grep $_ eq "/", @workdir);
Condition0%0/15
$configured_root_write || $have->{'world-write'} || $have->{'workdir-write'} && $workdir eq '/' || $have->{'all-workdirs-write'} && grep(($_ eq '/'), @workdir)
l!l&&r!l&&!r
000
$configured_root_write or $have->{"world-write"} or $have->{"workdir-write"} and $workdir eq "/"
l!l&&r!l&&!r
000
$configured_root_write or $have->{"world-write"}
l!l&&r!l&&!r
000
$have->{"workdir-write"} and $workdir eq "/"
!ll&&!rl&&r
000
$have->{"all-workdirs-write"} and grep(($_ eq "/"), @workdir)
!ll&&!rl&&r
000
MC/DC0%0/6
$configured_root_write || $have->{'world-write'} || $have->{'workdir-write'} && $workdir eq '/' || $have->{'all-workdirs-write'} && grep(($_ eq '/'), @workdir)
$configured_root_write $have->{"world-write"} $have->{"workdir-write"} $workdir eq "/" $have->{"all-workdirs-write"} grep(($_ eq "/"), @workdir)
Truth table0%0/9
A or B or C and D || E and F
A= $configured_root_writeB= $have->{"world-write"}C= $have->{"workdir-write"}D= $workdir eq "/"E= $have->{"all-workdirs-write"}F= grep(($_ eq "/"), @workdir)
ABCDEFresult
1XXXXX1
01XXXX1
0011XX1
000X111
0010111
000X0X0
000X100
00100X0
0010100
1450 0 ▶ $root_read ||= $root_write;
Condition0%0/3
$root_read ||= $root_write
l!l&&r!l&&!r
000
MC/DC0%0/2
$root_read ||= $root_write
$root_read $root_write
Truth table0%0/3
A ||= B
A= $root_readB= $root_write
ABresult
1X1
011
000
1451  
1452  
1453 0 my @command = ($bwrap, qw(
1454 --die-with-parent
1455 --unshare-pid --unshare-ipc --unshare-uts --unshare-cgroup-try
1456 ));
1457 0 ▶ push @command, "--unshare-user", "--disable-userns" unless $host_dac;
Branch: 1 branch
BranchTrueFalseTotal
unless $host_dac 0 0 0
1458 0 push @command, "--cap-drop", "ALL";
1459 0 ▶ push @command, "--cap-add", "CAP_DAC_OVERRIDE" if $host_dac;
Branch: 1 branch
BranchTrueFalseTotal
if $host_dac 0 0 0
1460 0 ▶ push @command, "--new-session" unless defined $exec_cmd;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $exec_cmd 0 0 0
1461  
1462 0 ▶ push @command, "--unshare-net" unless $have->{network};
Branch: 1 branch
BranchTrueFalseTotal
unless $have->{"network"} 0 0 0
1463  
1464 # Prepare the private root before any host bind; never write to host passwd.
1465 0 ▶ push @command, "--file", 3, "/etc/passwd"
Branch: 1 branch
BranchTrueFalseTotal
unless $root_read or @exec_prefix and not $remote 0 0 0
Condition0%0/6
$root_read or @exec_prefix and not $remote
l!l&&r!l&&!r
000
@exec_prefix and not $remote
!ll&&!rl&&r
000
MC/DC0%0/3
$root_read or @exec_prefix and not $remote
$root_read @exec_prefix not $remote
Truth table0%0/4
A or B and not(C)
A= $root_readB= @exec_prefixC= not $remote
ABCresult
1XX1
0111
00X0
0100
1466 unless $root_read || (@exec_prefix && !$remote);
1467 0 ▶ push @command, "--ro-bind", "/etc/passwd", "/etc/passwd" if @exec_prefix && !$remote && !$root_read;
Branch: 1 branch
BranchTrueFalseTotal
if @exec_prefix and not $remote and not $root_read 0 0 0
Condition0%0/6
@exec_prefix and not $remote and not $root_read
!ll&&!rl&&r
000
@exec_prefix and not $remote
!ll&&!rl&&r
000
MC/DC0%0/3
@exec_prefix and not $remote and not $root_read
@exec_prefix not $remote not $root_read
Truth table0%0/4
A and not(B) and not(C)
A= @exec_prefixB= not $remoteC= not $root_read
ABCresult
0XX0
10X0
1100
1111
1468 0 ▶ push @command, $root_write ? "--bind-try" : "--ro-bind-try", "/", "/"
Branch: 2 branches
BranchTrueFalseTotal
if $root_read 0 0 0
$root_write ? : 0 0 0
1469 if $root_read;
1470  
1471 0 my @scope_mount;
1472  
1473 0 ▶ unless ($root_read) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($root_read) 0 0 0
1474 0 for my $path (@runtime_path) {
1475 0 ▶ my $mount = (fs_writable $workdir, $path, $have) ? "--bind-try" : "--ro-bind-try";
Branch: 1 branch
BranchTrueFalseTotal
fs_writable($workdir, $path, $have) ? : 0 0 0
1476 0 my $bytes = AnyEvent::MCP::utf8enc $path;
1477 0 push @scope_mount, [$mount, $bytes, $bytes];
1478 }
1479 }
1480  
1481 0 ▶ if ($have->{"homedir-read"}
Branch: 1 branch
BranchTrueFalseTotal
if ($have->{"homedir-read"} and !$root_read || $have->{"homedir-write"} && !$root_write) 0 0 0
Condition0%0/9
$have->{"homedir-read"} and !$root_read || $have->{"homedir-write"} && !$root_write
!ll&&!rl&&r
000
not $root_read or $have->{"homedir-write"} and not $root_write
l!l&&r!l&&!r
000
$have->{"homedir-write"} and not $root_write
!ll&&!rl&&r
000
MC/DC0%0/4
$have->{"homedir-read"} and !$root_read || $have->{"homedir-write"} && !$root_write
$have->{"homedir-read"} not $root_read $have->{"homedir-write"} not $root_write
Truth table0%0/5
A and not(B) or C and not(D)
A= $have->{"homedir-read"}B= not $root_readC= $have->{"homedir-write"}D= not $root_write
ABCDresult
0XXX0
100X0
10100
11XX1
10111
1482 and (!$root_read or ($have->{"homedir-write"} and !$root_write))) {
1483 0 ▶ my $mount = (fs_writable $workdir, $home, $have) ? "--bind-try" : "--ro-bind-try";
Branch: 1 branch
BranchTrueFalseTotal
fs_writable($workdir, $home, $have) ? : 0 0 0
1484 0 push @scope_mount, [$mount, $home_bytes, $home_bytes];
1485 }
1486  
1487 0 ▶ if ($have->{"all-workdirs-read"}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($have->{'all-workdirs-read'}) { } 0 0 0
elsif ($have->{'workdir-read'} and $workdir ne '/') { } 0 0 0
1488 0 for my $path (@workdir) {
1489 0 ▶ next if $path eq "/";
Branch: 1 branch
BranchTrueFalseTotal
if $path eq "/" 0 0 0
1490 my $mount = ($have->{"all-workdirs-write"}
1491 0 ▶ or ($path eq $workdir && $have->{"workdir-write"}))
Branch: 1 branch
BranchTrueFalseTotal
$have->{'all-workdirs-write'} || $path eq $workdir && $have->{'workdir-write'} ? : 0 0 0
Condition0%0/6
$have->{"all-workdirs-write"} or $path eq $workdir and $have->{"workdir-write"}
l!l&&r!l&&!r
000
$path eq $workdir and $have->{"workdir-write"}
!ll&&!rl&&r
000
MC/DC0%0/3
$have->{"all-workdirs-write"} or $path eq $workdir and $have->{"workdir-write"}
$have->{"all-workdirs-write"} $path eq $workdir $have->{"workdir-write"}
Truth table0%0/4
A or B and C
A= $have->{"all-workdirs-write"}B= $path eq $workdirC= $have->{"workdir-write"}
ABCresult
1XX1
0111
00X0
0100
1492 ? "--bind" : "--ro-bind";
1493 0 my $bytes = AnyEvent::MCP::utf8enc $path;
1494 0 push @scope_mount, [$mount, $bytes, $bytes];
1495 }
1496 ▶ } elsif ($have->{"workdir-read"} && $workdir ne "/") {
Condition0%0/3
$have->{"workdir-read"} and $workdir ne "/"
!ll&&!rl&&r
000
MC/DC0%0/2
$have->{"workdir-read"} and $workdir ne "/"
$have->{"workdir-read"} $workdir ne "/"
Truth table0%0/3
A and B
A= $have->{"workdir-read"}B= $workdir ne "/"
ABresult
0X0
100
111
1497 0 ▶ my $mount = $have->{"workdir-write"} ? "--bind" : "--ro-bind";
Branch: 1 branch
BranchTrueFalseTotal
$have->{'workdir-write'} ? : 0 0 0
1498 0 push @scope_mount, [$mount, $workdir_bytes, $workdir_bytes];
1499 }
1500  
1501 # Host binds go parent-first so broader mounts cannot hide narrower grants.
1502 # Skip a nested read that is already covered by an equally strong mount.
1503 0 my @visible;
1504 0 for my $entry (sort { length $a->[2] <=> length $b->[2] } @scope_mount) {
1505 0 my ($mode, undef, $path) = @$entry;
1506 0 my $write = $mode =~ /\A--bind/;
1507 0 ▶ next if $root_write || ($root_read && !$write);
Branch: 1 branch
BranchTrueFalseTotal
if $root_write or $root_read and not $write 0 0 0
Condition0%0/6
$root_write or $root_read and not $write
l!l&&r!l&&!r
000
$root_read and not $write
!ll&&!rl&&r
000
MC/DC0%0/3
$root_write or $root_read and not $write
$root_write $root_read not $write
Truth table0%0/4
A or B and not(C)
A= $root_writeB= $root_readC= not $write
ABCresult
1XX1
0111
00X0
0100
1508 next if grep {
1509 0 ▶ fs_inside ($path, $_->[2]) && (!$write || $_->[0] =~ /\A--bind/)
Branch: 1 branch
BranchTrueFalseTotal
if grep {fs_inside($path, $_->[2]) and !$write || $_->[0] =~ /\A--bind/u;} @visible 0 0 0
Condition0%0/6
fs_inside($path, $_->[2]) && (!$write || $_->[0] =~ /\A--bind/u)
!ll&&!rl&&r
000
not $write or $_->[0] =~ /\A--bind/u
l!l&&r!l&&!r
000
MC/DC0%0/3
fs_inside($path, $_->[2]) && (!$write || $_->[0] =~ /\A--bind/u)
fs_inside($path, $_->[2]) not $write $_->[0] =~ /\A--bind/u
Truth table0%0/4
A && not(B) or C
A= fs_inside($path, $_->[2])B= not $writeC= $_->[0] =~ /\A--bind/u
ABCresult
0XX0
1000
11X1
1011
1510 } @visible;
1511 0 push @command, @$entry;
1512 0 push @visible, $entry;
1513 }
1514  
1515 # Avoid remounting DNS files already visible through a granted parent,
1516 # which could itself expose symlinked destinations.
1517 0 for my $path (qw(/etc/resolv.conf /etc/hosts)) {
1518 0 ▶ next if $root_read || grep { fs_inside $path, $_->[2] } @visible;
Branch: 1 branch
BranchTrueFalseTotal
if $root_read or grep {fs_inside($path, $_->[2]);} @visible 0 0 0
Condition0%0/3
$root_read or grep {fs_inside($path, $_->[2]);} @visible
l!l&&r!l&&!r
000
MC/DC0%0/2
$root_read or grep {fs_inside($path, $_->[2]);} @visible
$root_read grep {fs_inside($path, $_->[2]);} @visible
Truth table0%0/3
A or B
A= $root_readB= grep {fs_inside($path, $_->[2]);} @visible
ABresult
1X1
011
000
1519 0 ▶ my $mount = fs_writable ($workdir, $path, $have) ? "--bind-try" : "--ro-bind-try";
Branch: 1 branch
BranchTrueFalseTotal
fs_writable($workdir, $path, $have) ? : 0 0 0
1520 0 push @command, $mount, $path, $path;
1521 }
1522  
1523 # Configured mounts are explicit exceptions. Apply an ancestor of a
1524 # private mount first; the narrow exception itself may follow afterward.
1525 0 my @configured_after;
1526 0 ▶ unless ($have->{"world-write"}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($have->{"world-write"}) 0 0 0
1527 0 for my $entry (@mount) {
1528 0 my ($key, $mode, $path) = @$entry;
1529 0 ▶ next if $path eq "/";
Branch: 1 branch
BranchTrueFalseTotal
if $path eq "/" 0 0 0
1530 0 ▶ next if $mode eq "ro" && ($root_read || fs_writable $workdir, $path, $have);
Branch: 1 branch
BranchTrueFalseTotal
if $mode eq "ro" and $root_read || fs_writable($workdir, $path, $have) 0 0 0
Condition0%0/6
$mode eq "ro" and $root_read || fs_writable($workdir, $path, $have)
!ll&&!rl&&r
000
$root_read or fs_writable($workdir, $path, $have)
l!l&&r!l&&!r
000
MC/DC0%0/3
$mode eq "ro" and $root_read || fs_writable($workdir, $path, $have)
$mode eq "ro" $root_read fs_writable($workdir, $path, $have)
Truth table0%0/4
A and B or C
A= $mode eq "ro"B= $root_readC= fs_writable($workdir, $path, $have)
ABCresult
0XX0
1000
11X1
1011
1531 0 my $bytes = AnyEvent::MCP::utf8enc $path;
1532 0 ▶ my @bind = (($mode eq "rw" ? "--bind" : "--ro-bind")
Branch: 2 branches
BranchTrueFalseTotal
$mode eq 'rw' ? : 0 0 0
$key =~ /\Amount-try\./u ? : 0 0 0
1533 . ($key =~ /\Amount-try\./ ? "-try" : ""), $bytes, $bytes);
1534 0 ▶ if (grep { $_ ne $path && fs_inside $_, $path } qw(/sys /run /dev /proc /tmp /var/tmp)) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$_ ne $path and fs_inside($_, $path);} '/sys', '/run', '/dev', '/proc', '/tmp', '/var/tmp') { } 0 0 0
Condition0%0/3
$_ ne $path && fs_inside($_, $path)
!ll&&!rl&&r
000
MC/DC0%0/2
$_ ne $path && fs_inside($_, $path)
$_ ne $path fs_inside($_, $path)
Truth table0%0/3
A && B
A= $_ ne $pathB= fs_inside($_, $path)
ABresult
0X0
100
111
1535 0 push @command, @bind;
1536 } else {
1537 0 push @configured_after, @bind;
1538 }
1539 }
1540 }
1541  
1542 # Private facilities override broad host mounts.
1543 0 push @command, qw(--tmpfs /sys --tmpfs /run --dev /dev);
1544 0 push @command, "--proc", "/proc";
1545  
1546 0 my @tmp = qw(/tmp /var/tmp);
1547 0 for my $i (0 .. $#tmp) {
1548 0 my $tmp = $tmp[$i];
1549 0 ▶ next if $root_write;
Branch: 1 branch
BranchTrueFalseTotal
if $root_write 0 0 0
1550 # Explicit access to the temporary directory itself takes precedence.
1551 next if (grep $_->[2] eq $tmp, @mount)
1552 || ($have->{"workdir-read"} && $workdir eq $tmp)
1553 0 ▶ || ($have->{"all-workdirs-read"} && grep $_ eq $tmp, @workdir);
Branch: 1 branch
BranchTrueFalseTotal
if grep(($_->[2] eq $tmp), @mount) or $have->{"workdir-read"} and $workdir eq $tmp or $have->{"all-workdirs-read"} and grep(($_ eq $tmp), @workdir) 0 0 0
Condition0%0/12
grep(($_->[2] eq $tmp), @mount) or $have->{"workdir-read"} and $workdir eq $tmp or $have->{"all-workdirs-read"} and grep(($_ eq $tmp), @workdir)
l!l&&r!l&&!r
000
grep(($_->[2] eq $tmp), @mount) or $have->{"workdir-read"} and $workdir eq $tmp
l!l&&r!l&&!r
000
$have->{"workdir-read"} and $workdir eq $tmp
!ll&&!rl&&r
000
$have->{"all-workdirs-read"} and grep(($_ eq $tmp), @workdir)
!ll&&!rl&&r
000
MC/DC0%0/5
grep(($_->[2] eq $tmp), @mount) or $have->{"workdir-read"} and $workdir eq $tmp or $have->{"all-workdirs-read"} and grep(($_ eq $tmp), @workdir)
grep(($_->[2] eq $tmp), @mount) $have->{"workdir-read"} $workdir eq $tmp $have->{"all-workdirs-read"} grep(($_ eq $tmp), @workdir)
Truth table0%0/8
A or B and C or D and E
A= grep(($_->[2] eq $tmp), @mount)B= $have->{"workdir-read"}C= $workdir eq $tmpD= $have->{"all-workdirs-read"}E= grep(($_ eq $tmp), @workdir)
ABCDEresult
1XXXX1
011XX1
00X111
010111
00X0X0
00X100
0100X0
010100
1554  
1555 # If the host symlink is visible, bwrap must mount on its real target,
1556 # not the symlink. The remote probe supplies remote, not local, paths.
1557 my $visible = $root_read
1558 0 || (grep { fs_inside $tmp, $_->[2] } @visible)
1559 0 ▶ || (grep { fs_inside $tmp, $_->[2] } @mount);
Condition0%0/6
$root_read || grep({fs_inside($tmp, $_->[2]);} @visible) || grep({fs_inside($tmp, $_->[2]);} @mount)
l!l&&r!l&&!r
000
$root_read or grep {fs_inside($tmp, $_->[2]);} @visible
l!l&&r!l&&!r
000
MC/DC0%0/3
$root_read || grep({fs_inside($tmp, $_->[2]);} @visible) || grep({fs_inside($tmp, $_->[2]);} @mount)
$root_read grep {fs_inside($tmp, $_->[2]);} @visible grep({fs_inside($tmp, $_->[2]);} @mount)
Truth table0%0/4
A or B || C
A= $root_readB= grep {fs_inside($tmp, $_->[2]);} @visibleC= grep({fs_inside($tmp, $_->[2]);} @mount)
ABCresult
1XX1
01X1
0011
0000
1560 0 ▶ my $destination = $visible ? AnyEvent::MCP::utf8enc $tmp_realpath[$i] : $tmp;
Branch: 1 branch
BranchTrueFalseTotal
$visible ? : 0 0 0
1561 0 ▶ if ($have->{"shared-tmp"}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($have->{'shared-tmp'}) { } 0 0 0
1562 0 push @command, "--bind-try", $tmp, $destination;
1563 } else {
1564 0 push @command, "--perms", "1777", "--tmpfs", $destination;
1565 }
1566 }
1567  
1568 # Narrow explicit exceptions are allowed to override the private baseline.
1569 0 push @command, @configured_after;
1570  
1571 0 my $agent_socket;
1572 0 ▶ if ($have->{"ssh-agent"}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($have->{"ssh-agent"}) 0 0 0
1573 0 ▶ if ($remote) {
Branch: 2 branches
BranchTrueFalseTotal
if ($remote) { } 0 0 0
elsif (length $ENV{'SSH_AUTH_SOCK'}) { } 0 0 0
1574 0 $agent_socket = "/run/anyevent-mcp/ssh-agent";
1575 0 push @command, "--ro-bind", "__MCP_REMOTE_AGENT__", $agent_socket;
1576 } elsif (length $ENV{SSH_AUTH_SOCK}) {
1577 $ENV{SSH_AUTH_SOCK} =~ m{\A/} && -S $ENV{SSH_AUTH_SOCK}
1578 0 ▶ or die "SSH_AUTH_SOCK must name an absolute existing socket\n";
Branch: 1 branch
BranchTrueFalseTotal
$ENV{"SSH_AUTH_SOCK"} =~ m[\A/]u and -S $ENV{"SSH_AUTH_SOCK"} or die "SSH_AUTH_SOCK must name an absolute existing socket\n" 0 0 0
Condition0%0/3
$ENV{"SSH_AUTH_SOCK"} =~ m[\A/]u and -S $ENV{"SSH_AUTH_SOCK"}
!ll&&!rl&&r
000
MC/DC0%0/2
$ENV{"SSH_AUTH_SOCK"} =~ m[\A/]u and -S $ENV{"SSH_AUTH_SOCK"}
$ENV{"SSH_AUTH_SOCK"} =~ m[\A/]u -S $ENV{"SSH_AUTH_SOCK"}
Truth table0%0/3
A and B
A= $ENV{"SSH_AUTH_SOCK"} =~ m[\A/]uB= -S $ENV{"SSH_AUTH_SOCK"}
ABresult
0X0
100
111
1579 0 my $source = $ENV{SSH_AUTH_SOCK};
1580 0 $agent_socket = "/run/anyevent-mcp/ssh-agent";
1581 0 push @command, "--ro-bind", $source, $agent_socket;
1582 }
1583 push @command, "--ro-bind-try", "$home_bytes/.ssh/known_hosts", "$home_bytes/.ssh/known_hosts"
1584 0 ▶ unless $have->{"homedir-read"} || $have->{"world-read"};
Branch: 1 branch
BranchTrueFalseTotal
unless $have->{"homedir-read"} or $have->{"world-read"} 0 0 0
Condition0%0/3
$have->{"homedir-read"} or $have->{"world-read"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$have->{"homedir-read"} or $have->{"world-read"}
$have->{"homedir-read"} $have->{"world-read"}
Truth table0%0/3
A or B
A= $have->{"homedir-read"}B= $have->{"world-read"}
ABresult
1X1
011
000
1585 }
1586  
1587 0 ▶ push @command, "--remount-ro", "/"
Branch: 1 branch
BranchTrueFalseTotal
unless $root_write 0 0 0
1588 unless $root_write;
1589  
1590 0 push @command,
1591 "--clearenv",
1592 "--setenv", "PATH", $sandbox_path,
1593 "--setenv", "LC_ALL", "C.UTF-8",
1594 "--setenv", "PERL_BADLANG", "0",
1595 "--setenv", "HOME", $home_bytes;
1596  
1597 0 for my $name (qw(TERM COLORTERM TERMINFO TERMINFO_DIRS NO_COLOR CLICOLOR CLICOLOR_FORCE LINES COLUMNS)) {
1598 0 ▶ push @command, "--setenv", $name, $ENV{$name} if defined $ENV{$name};
Branch: 1 branch
BranchTrueFalseTotal
if defined $ENV{$name} 0 0 0
1599 }
1600  
1601 0 for my $entry (@environment) {
1602 0 my ($name, $value) = @$entry;
1603 0 ▶ next if $name eq "SSH_AUTH_SOCK";
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "SSH_AUTH_SOCK" 0 0 0
1604 0 ▶ $value = defined $value ? AnyEvent::MCP::utf8enc $value : $ENV{$name};
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 0 0 0
1605 0 ▶ push @command, "--setenv", $name, $value if defined $value;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 0 0 0
1606 }
1607 0 ▶ push @command, "--setenv", "SSH_AUTH_SOCK", $agent_socket if defined $agent_socket;
Branch: 1 branch
BranchTrueFalseTotal
if defined $agent_socket 0 0 0
1608  
1609 push @command,
1610 0 ▶ "--chdir", defined $exec_cmd ? $workdir_bytes : $have->{"workdir-read"} ? $workdir_bytes : "/tmp",
Branch: 2 branches
BranchTrueFalseTotal
defined $exec_cmd ? : 0 0 0
$have->{'workdir-read'} ? : 0 0 0
1611 "--";
1612  
1613 @command
1614 0 }
1615  
1616 # pass a private synthetic user entry to bubblewrap without a host passwd mount.
1617 0 ▶sub fs_passwd_fd {
Subroutine fs_passwd_fd: not called CC=8 SCAR=42.8
1618 0 ▶ my ($read, $write) = AnyEvent::Util::portable_pipe
Branch: 1 branch
BranchTrueFalseTotal
() = &AnyEvent::Util::portable_pipe() or die "passwd pipe: $!\n" 0 0 0
1619 or die "passwd pipe: $!\n";
1620 0 ▶ print {$write} "sandbox:x:$<:" . POSIX::getgid () . ":Sandbox:" . (AnyEvent::MCP::utf8enc $home) . ":/bin/sh\n"
Branch: 1 branch
BranchTrueFalseTotal
print {$write;} "sandbox:x:$<:" . POSIX::getgid() . ':Sandbox:' . &AnyEvent::MCP::utf8enc($home) . ":/bin/sh\n" or die "passwd pipe: $!\n" 0 0 0
1621 or die "passwd pipe: $!\n";
1622 0 ▶ close $write or die "passwd pipe: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
close $write or die "passwd pipe: $!\n" 0 0 0
1623  
1624 0 ▶ if (fileno ($read) != 3) {
Branch: 1 branch
BranchTrueFalseTotal
if (fileno $read != 3) 0 0 0
1625 0 ▶ POSIX::dup2 (fileno ($read), 3) == 3 or die "passwd dup2: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
POSIX::dup2(fileno $read, 3) == 3 or die "passwd dup2: $!\n" 0 0 0
1626 0 close $read;
1627 0 ▶ open $read, "<&=3" or die "passwd fd: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open $read, "<&=3" or die "passwd fd: $!\n" 0 0 0
1628 }
1629  
1630 0 ▶ defined fcntl ($read, F_SETFD, 0) or die "passwd fcntl: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
defined fcntl($read, 2, 0) or die "passwd fcntl: $!\n" 0 0 0
1631 0 $read
1632 }
1633  
1634 6 ▶if (defined $exec_cmd) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $exec_cmd) 0 6 6
1635 0 ▶ my @sandbox_grants = length $exec_cmd ? split /,/, $exec_cmd, -1 : ();
Branch: 1 branch
BranchTrueFalseTotal
length $exec_cmd ? : 0 0 0
1636 my @command = (@exec_prefix, (fs_sandbox $workdir[0], \@sandbox_grants),
1637 0 ▶ (@ARGV ? @ARGV : ($ENV{SHELL} || "/bin/sh")));
Branch: 1 branch
BranchTrueFalseTotal
@ARGV ? : 0 0 0
Condition0%0/2
$ENV{"SHELL"} or "/bin/sh"
l!l
00
MC/DC0%0/1
$ENV{"SHELL"} or "/bin/sh"
$ENV{"SHELL"}
Truth table0%0/2
A
A= $ENV{"SHELL"}
Aresult
11
00
1638 0 ▶ my $passwd_fd = fs_passwd_fd () if $bwrap && !@exec_prefix;
Branch: 1 branch
BranchTrueFalseTotal
if $bwrap and not @exec_prefix 0 0 0
Condition0%0/3
$bwrap and not @exec_prefix
!ll&&!rl&&r
000
MC/DC0%0/2
$bwrap and not @exec_prefix
$bwrap not @exec_prefix
Truth table0%0/3
A and not(B)
A= $bwrapB= not @exec_prefix
ABresult
0X0
100
111
1639  
1640 0 exec {$command[0]} @command;
1641 0 die "exec $command[0]: $!\n";
1642 }
1643  
1644 # Perl is required in the worker namespace; discover the other tools there too.
1645 6 my $probe = q{#perl
1646 use 5.008004;
1647 use Cwd ();
1648  
1649 my %test = (
1650 find => [[qw(--version)], qr/^find \(GNU findutils\)/m],
1651 grep => [[qw(--version)], qr/^grep \(GNU grep\)/m],
1652 patch => [[qw(--version)], qr/^GNU patch /m],
1653 sed => [[qw(--version)], qr/\(GNU sed\)/],
1654 );
1655  
1656 sub find_executable {
1657 my ($name) = @_;
1658  
1659 return unless length $name && $name !~ /\0/;
1660 my @path = $name =~ m{/} ? ($name)
1661 : map { (length $_ ? $_ : ".") . "/$name" } split /:/, $ENV{PATH}, -1;
1662 for (@path) {
1663 next unless -f $_ && -x _;
1664 return m{\A/} ? $_ : Cwd::getcwd () . "/$_";
1665 }
1666 undef
1667 }
1668  
1669 while (@ARGV) {
1670 my ($name, $wanted, $explicit) = splice @ARGV, 0, 3;
1671 my $path = find_executable $wanted;
1672 if ($path && !$explicit && $test{$name}) {
1673 my ($args, $match) = @{$test{$name}};
1674 my $ok = open my $fh, "-|", $path, @$args;
1675 if ($ok) {
1676 my $output = do { local $/; <$fh> };
1677 $ok = close $fh && $output =~ $match;
1678 }
1679 undef $path unless $ok;
1680 }
1681 $path ||= "";
1682 print "$path\0";
1683 }
1684 };
1685  
1686 6 my @names = qw(perl find grep patch sed git svn cvs hg);
1687 6 ▶my $perl_name = $executable{perl} || "perl";
Condition100%2/2
$executable{'perl'} || 'perl'
l!l
42
MC/DC100%1/1
$executable{'perl'} || 'perl'
$executable{'perl'}
Truth table100%2/2
A
A= $executable{'perl'}
Aresult
11
00
1688 6 my %program = %remote_program;
1689 6 ▶unless ($remote) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($remote) 6 0 6
1690 my @command = (@exec_prefix, $bwrap ? (fs_sandbox $workdir[0], []) : (),
1691 $perl_name, "-e", $probe,
1692 6 ▶ map { ($_, $executable{$_} || $_, length $settings{"executable.$_"} ? 1 : 0) } @names);
Branch: 2 branches
BranchTrueFalseTotal
$bwrap ? : 0 6 6
length $settings{"executable.$_"} ? : 4 50 54
Condition66%2/3
$executable{$_} || $_
l!l&&r!l&&!r
4500
MC/DC0%0/2
$executable{$_} || $_
$executable{$_} $_
Truth table66%2/3
A || B
A= $executable{$_}B= $_
ABresult
1X1
011
000
1693 6 my $pid = open my $fh, "-|";
1694 6 ▶ defined $pid or die "Perl probe fork: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $pid or die "Perl probe fork: $!\n" 6 0 6
1695  
1696 6 ▶ unless ($pid) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($pid) 2 4 6
1697 2 ▶ my $passwd_fd = fs_passwd_fd () if $bwrap && !@exec_prefix;
Branch: 1 branch
BranchTrueFalseTotal
if $bwrap and not @exec_prefix 0 2 2
Condition33%1/3
$bwrap and not @exec_prefix
!ll&&!rl&&r
200
MC/DC0%0/2
$bwrap and not @exec_prefix
$bwrap not @exec_prefix
Truth table33%1/3
A and not(B)
A= $bwrapB= not @exec_prefix
ABresult
0X0
100
111
1698 2 exec {$command[0]} @command;
1699 0 warn "exec $command[0]: $!\n";
1700 0 POSIX::_exit 126;
1701 }
1702  
1703 4 my $output = do { local $/; <$fh> };
1704 4 ▶ close $fh or die "Perl '$perl_name' cannot run in the worker environment\n";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or die "Perl '${perl_name}' cannot run in the worker environment\n" 4 0 4
1705 4 my @paths = split /\0/, $output, -1;
1706 4 ▶ @paths == @names + 1 && pop @paths eq ""
Branch: 1 branch
BranchTrueFalseTotal
@paths == @names + 1 and pop @paths eq "" or die "invalid Perl executable probe response\n" 4 0 4
Condition33%1/3
@paths == @names + 1 and pop @paths eq ""
!ll&&!rl&&r
004
MC/DC0%0/2
@paths == @names + 1 and pop @paths eq ""
@paths == @names + 1 pop @paths eq ""
Truth table33%1/3
A and B
A= @paths == @names + 1B= pop @paths eq ""
ABresult
0X0
100
111
1707 or die "invalid Perl executable probe response\n";
1708 4 @program{@names} = @paths;
1709 }
1710 4 ▶$program{perl} or die "Perl interpreter not found inside the sandbox\n";
Branch: 1 branch
BranchTrueFalseTotal
$program{"perl"} or die "Perl interpreter not found inside the sandbox\n" 4 0 4
1711 4 ($find, $grep, $patch, $perl, $sed) = @program{qw(find grep patch perl sed)};
1712 warn "$_: not detected or wrong version\n"
1713 4 for grep !$program{$_}, qw(find grep patch sed);
1714 4 %vcs_program = map { ($_ => $program{$_}) } qw(git svn cvs hg);
1715  
1716 4 ▶AE::log warn => "bubblewrap unavailable, running without sandbox"
Branch: 1 branch
BranchTrueFalseTotal
if $sandbox_mode eq "auto" and not $bwrap 0 4 4
Condition33%1/3
$sandbox_mode eq "auto" and not $bwrap
!ll&&!rl&&r
400
MC/DC0%0/2
$sandbox_mode eq "auto" and not $bwrap
$sandbox_mode eq "auto" not $bwrap
Truth table33%1/3
A and not(B)
A= $sandbox_mode eq "auto"B= not $bwrap
ABresult
0X0
100
111
1717 if $sandbox_mode eq "auto" && !$bwrap;
1718  
1719 4 AnyEvent::detect; # proc_spawn creates child watchers after they might have died
1720  
1721 # spawn stdin/stdout and stderr handles; proc_destroy closes them and terminates the child.
1722 # the independent child watcher remains alive until the child is reaped.
1723 5 ▶sub proc_spawn {
Subroutine proc_spawn: called CC=18 SCAR=34.5
1724 5 my ($program, @argv) = @_;
1725  
1726 5 my $remote_input;
1727 5 ▶ if ($remote) {
Branch: 2 branches
BranchTrueFalseTotal
if ($remote) { } 0 5 5
elsif (@exec_prefix) { } 0 5 5
1728 0 ▶ $remote_input = $remote_launcher . fs_remote_frame ($bwrap ? AnyEvent::MCP::utf8enc $home : "", $program, @argv);
Branch: 1 branch
BranchTrueFalseTotal
$bwrap ? : 0 0 0
1729 0 ($program, @argv) = (@rsh, $host, $remote_command);
1730 } elsif (@exec_prefix) {
1731 0 ($program, @argv) = (@exec_prefix, $program, @argv);
1732 }
1733  
1734 5 ▶ my ($parent, $child) = AnyEvent::Util::portable_socketpair
Branch: 1 branch
BranchTrueFalseTotal
() = &AnyEvent::Util::portable_socketpair() or die "socketpair: $!\n" 5 0 5
1735 or die "socketpair: $!\n";
1736 5 ▶ my ($error, $child_error) = AnyEvent::Util::portable_pipe
Branch: 1 branch
BranchTrueFalseTotal
() = &AnyEvent::Util::portable_pipe() or die "pipe: $!\n" 5 0 5
1737 or die "pipe: $!\n";
1738  
1739 5 my $pid = fork;
1740 5 ▶ defined $pid or die "fork: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $pid or die "fork: $!\n" 5 0 5
1741  
1742 5 ▶ unless ($pid) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($pid) 2 3 5
1743 2 ▶ open STDIN, "<&", $child or POSIX::_exit 126;
Branch: 1 branch
BranchTrueFalseTotal
open STDIN, "<&", $child or POSIX::_exit(126) 2 0 2
1744 2 ▶ open STDOUT, ">&", $child or POSIX::_exit 126;
Branch: 1 branch
BranchTrueFalseTotal
open STDOUT, ">&", $child or POSIX::_exit(126) 2 0 2
1745 2 ▶ open STDERR, ">&", $child_error or POSIX::_exit 126;
Branch: 1 branch
BranchTrueFalseTotal
open STDERR, ">&", $child_error or POSIX::_exit(126) 2 0 2
1746  
1747 2 close $parent;
1748 2 close $error;
1749 2 close $child;
1750 2 close $child_error;
1751  
1752 2 ▶ my $passwd_fd = fs_passwd_fd () if $bwrap && !$remote && !@exec_prefix;
Branch: 1 branch
BranchTrueFalseTotal
if $bwrap and not $remote and not @exec_prefix 0 2 2
Condition33%2/6
$bwrap and not $remote and not @exec_prefix
!ll&&!rl&&r
200
$bwrap and not $remote
!ll&&!rl&&r
200
MC/DC0%0/3
$bwrap and not $remote and not @exec_prefix
$bwrap not $remote not @exec_prefix
Truth table25%1/4
A and not(B) and not(C)
A= $bwrapB= not $remoteC= not @exec_prefix
ABCresult
0XX0
10X0
1100
1111
1753 2 ▶ AnyEvent::Util::close_all_fds_except (0, 1, 2, ($bwrap && !$remote && !@exec_prefix ? 3 : ()));
Branch: 1 branch
BranchTrueFalseTotal
$bwrap && !$remote && !@exec_prefix ? : 0 2 2
Condition33%2/6
$bwrap and not $remote and not @exec_prefix
!ll&&!rl&&r
200
$bwrap and not $remote
!ll&&!rl&&r
200
MC/DC0%0/3
$bwrap and not $remote and not @exec_prefix
$bwrap not $remote not @exec_prefix
Truth table25%1/4
A and not(B) and not(C)
A= $bwrapB= not $remoteC= not @exec_prefix
ABCresult
0XX0
10X0
1100
1111
1754  
1755 2 exec {$program} $program, @argv;
1756 0 print STDERR "exec $program: $!\n";
1757 0 POSIX::_exit 126;
1758 }
1759  
1760 3 close $child;
1761 3 close $child_error;
1762  
1763 3 my $io = AnyEvent::Handle->new (fh => $parent);
1764 3 my $err = AnyEvent::Handle->new (fh => $error);
1765 3 my $proc = { pid => $pid };
1766  
1767 # keep the watcher alive independently so a fatal I/O error still reaps.
1768 1 ▶ $proc->{child} = AE::child $pid, sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1769 1 $proc->{status} = $_[1];
1770 1 delete $proc->{pid};
1771 1 delete $proc->{child};
1772 1 ▶ (delete $proc->{done})->($proc->{status}) if $proc->{done};
Branch: 1 branch
BranchTrueFalseTotal
if $proc->{"done"} 1 0 1
1773 3 };
1774  
1775 3 $io->{proc} = $proc;
1776 3 $io->{proc_err} = $err;
1777 3 ▶ $io->push_write ($remote_input) if $remote;
Branch: 1 branch
BranchTrueFalseTotal
if $remote 0 3 3
1778  
1779 3 $io
1780 }
1781  
1782 # signal a spawned process while its pid is still owned by us.
1783 1 ▶sub proc_kill {
Subroutine proc_kill: called CC=3 SCAR=16.5
1784 1 my ($proc, $signal) = @_;
1785  
1786 1 ▶ my $pid = $proc->{pid} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $pid = $proc->{"pid"} or return 0 1 1
1787  
1788 0 ▶ $signal //= "KILL";
Condition0%0/2
$signal //= "KILL"
l!l
00
MC/DC0%0/1
$signal //= "KILL"
$signal
Truth table0%0/2
A
A= $signal
Aresult
11
00
1789 0 kill $signal => $pid
1790 }
1791  
1792 # abandon a process and release its streams; repeated cleanup is harmless.
1793 1 ▶sub proc_destroy {
Subroutine proc_destroy: called CC=3 SCAR=11.4
1794 1 my ($io) = @_;
1795  
1796 1 ▶ proc_kill (delete $io->{proc}) if $io->{proc};
Branch: 1 branch
BranchTrueFalseTotal
if $io->{"proc"} 1 0 1
1797 1 ▶ (delete $io->{proc_err})->destroy if $io->{proc_err};
Branch: 1 branch
BranchTrueFalseTotal
if $io->{"proc_err"} 1 0 1
1798 1 $io->destroy;
1799 }
1800  
1801 # register the process's exit callback, or call it immediately if reaped.
1802 3 ▶sub proc_on_exit {
Subroutine proc_on_exit: called CC=2 SCAR=7.1
1803 3 my ($proc, $done) = @_;
1804  
1805 return $done->($proc->{status})
1806 3 ▶ if defined $proc->{status};
Branch: 1 branch
BranchTrueFalseTotal
if defined $proc->{"status"} 0 3 3
1807  
1808 3 $proc->{done} = $done;
1809 }
1810  
1811 # run a one-shot subprocess, leaving output interpretation to the caller.
1812 # the stream callbacks consume rbuf and may return true to terminate the child.
1813 2 ▶sub proc_run {
Subroutine proc_run: called CC=4 SCAR=15.8
1814 2 my ($req, $command, $input, $timeout, $on_stdout, $on_stderr, $done) = @_;
1815  
1816 2 my $io = proc_spawn @$command;
1817 1 my $err = $io->{proc_err};
1818 1 my $proc = $io->{proc};
1819 1 my ($open, $timed_out, $failure, $timer) = (2);
1820  
1821 3 ▶ my $complete = sub {
Subroutine __ANON__: called CC=5 SCAR=16.2
1822 3 ▶ return if $open || !defined $proc->{status};
Branch: 1 branch
BranchTrueFalseTotal
if $open or not defined $proc->{"status"} 2 1 3
Condition100%3/3
$open or not defined $proc->{"status"}
l!l&&r!l&&!r
111
MC/DC100%2/2
$open or not defined $proc->{"status"}
$open not defined $proc->{"status"}
Truth table100%3/3
A or not(B)
A= $openB= not defined $proc->{"status"}
ABresult
1X1
011
000
1823 1 ▶ my $cb = $done or return;
Branch: 1 branch
BranchTrueFalseTotal
my $cb = $done or return 1 0 1
1824 1 undef $done;
1825 1 undef $timer;
1826 1 proc_destroy $io;
1827 1 ▶ return if $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"finished"} 0 1 1
1828 1 delete $req->{on_cancel};
1829 1 $cb->($proc->{status}, $timed_out, $failure);
1830 1 };
1831  
1832 0 ▶ my $stop = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1833 0 undef $timer;
1834 0 delete $req->{on_cancel};
1835 0 $open = 0;
1836 0 proc_destroy $io;
1837 0 $complete->();
1838 1 };
1839 1 $req->{on_cancel} = $stop;
1840  
1841 1 for my $stream ([$io, $on_stdout], [$err, $on_stderr]) {
1842 2 my ($handle, $consume) = @$stream;
1843 2 my $closed;
1844 2 ▶ my $finish = sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
1845 2 ▶ return if $closed++;
Branch: 1 branch
BranchTrueFalseTotal
if $closed++ 0 2 2
1846 2 --$open;
1847 2 $complete->();
1848 2 };
1849 3 ▶ my $read = sub {
Subroutine __ANON__: called CC=4 SCAR=17.9
1850 3 my ($handle, $eof) = @_;
1851 3 my $stop = eval { $consume->($handle, $eof) };
1852 3 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 3 3
1853 0 ▶ $failure ||= $@;
Condition0%0/3
$failure ||= $@
l!l&&r!l&&!r
000
MC/DC0%0/2
$failure ||= $@
$failure $@
Truth table0%0/3
A ||= B
A= $failureB= $@
ABresult
1X1
011
000
1854 0 $stop = 1;
1855 }
1856 3 ▶ proc_kill $proc if $stop;
Branch: 1 branch
BranchTrueFalseTotal
if $stop 0 3 3
1857 2 };
1858 2 ▶ $handle->on_read (sub { $read->($_[0], 0) });
Subroutine __ANON__: called CC=1 SCAR=0.0
1859 2 ▶ $handle->on_eof (sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1860 2 $read->($_[0], 1);
1861 2 $finish->();
1862 2 });
1863 0 ▶ $handle->on_error (sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
1864 0 ▶ return unless $_[1];
Branch: 1 branch
BranchTrueFalseTotal
unless $_[1] 0 0 0
1865 0 $read->($_[0], 0);
1866 0 ▶ $failure ||= "subprocess I/O: $_[2]\n" unless $timed_out;
Branch: 1 branch
BranchTrueFalseTotal
unless $timed_out 0 0 0
Condition0%0/2
$failure ||= "subprocess I/O: $_[2]\n"
l!l
00
MC/DC0%0/1
$failure ||= "subprocess I/O: $_[2]\n"
$failure
Truth table0%0/2
A
A= $failure
Aresult
11
00
1867 0 proc_kill $proc;
1868 0 $finish->();
1869 2 });
1870 }
1871  
1872 1 my $ok = eval {
1873 1 ▶ $io->push_write ($input) if length $input;
Branch: 1 branch
BranchTrueFalseTotal
if length $input 1 0 1
1874 1 $io->push_shutdown;
1875 1 1
1876 };
1877 1 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 1 1
1878 0 my $error = $@;
1879 0 proc_destroy $io;
1880 0 die $error;
1881 }
1882  
1883 0 ▶ $timer = AE::timer $timeout, 0, sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1884 0 $timed_out = 1;
1885 0 $stop->();
1886 1 };
1887  
1888 1 proc_on_exit $proc, $complete;
1889 }
1890  
1891 # run a subprocess and collect bounded output.
1892 0 ▶sub fs_run {
Subroutine fs_run: not called CC=1 SCAR=6.9
1893 0 my ($req, $command, $input, $timeout, $byte_limit, $line_limit, $done) = @_;
1894  
1895 0 my ($truncated, $line_truncated);
1896 0 my ($stdout, $stderr) = ("", "");
1897  
1898 0 ▶ my $capture = sub {
Subroutine __ANON__: not called CC=10 SCAR=47.0
1899 0 my ($target, $data, $lines) = @_;
1900  
1901 0 ▶ return if $lines and $line_truncated;
Branch: 1 branch
BranchTrueFalseTotal
if $lines and $line_truncated 0 0 0
Condition0%0/3
$lines and $line_truncated
!ll&&!rl&&r
000
MC/DC0%0/2
$lines and $line_truncated
$lines $line_truncated
Truth table0%0/3
A and B
A= $linesB= $line_truncated
ABresult
0X0
100
111
1902 0 ▶ return unless length $data;
Branch: 1 branch
BranchTrueFalseTotal
unless length $data 0 0 0
1903 0 my $remaining = $byte_limit - (length $stdout) - (length $stderr);
1904 0 ▶ $truncated = 1 if length $data > $remaining;
Branch: 1 branch
BranchTrueFalseTotal
if length $data > $remaining 0 0 0
1905 0 ▶ $$target .= substr $data, 0, $remaining
Branch: 1 branch
BranchTrueFalseTotal
if $remaining > 0 0 0 0
1906 if $remaining > 0;
1907  
1908 0 ▶ if ($lines and $line_limit and ($$target =~ tr/\n//) > $line_limit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lines and $line_limit and $$target =~ tr/\n// > $line_limit) 0 0 0
Condition0%0/6
$lines and $line_limit and $$target =~ tr/\n// > $line_limit
!ll&&!rl&&r
000
$lines and $line_limit
!ll&&!rl&&r
000
MC/DC0%0/3
$lines and $line_limit and $$target =~ tr/\n// > $line_limit
$lines $line_limit $$target =~ tr/\n// > $line_limit
Truth table0%0/4
A and B and C
A= $linesB= $line_limitC= $$target =~ tr/\n// > $line_limit
ABCresult
0XX0
10X0
1100
1111
1909 0 my $end = -1;
1910 $end = index $$target, "\n", $end + 1
1911 0 for 1 .. $line_limit;
1912 0 substr $$target, $end + 1, length $$target, "";
1913 0 $truncated = $line_truncated = 1;
1914 0 return 1
1915 }
1916  
1917 0
1918 0 };
1919  
1920 proc_run $req, $command, $input, $timeout,
1921 0 ▶ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1922 0 my ($handle) = @_;
1923 0 my $stop = $capture->(\$stdout, $handle->{rbuf}, 1);
1924 0 $handle->{rbuf} = "";
1925 0 $stop
1926 },
1927 0 ▶ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1928 0 my ($handle) = @_;
1929 0 $capture->(\$stderr, $handle->{rbuf}, 0);
1930 0 $handle->{rbuf} = "";
1931 0 0
1932 },
1933 0 ▶ sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
1934 0 my ($status, $timed_out, $failure) = @_;
1935 0 ▶ return $done->(0, $failure) if $failure;
Branch: 1 branch
BranchTrueFalseTotal
if $failure 0 0 0
1936 0 ▶ $done->(1, +{
Branch: 2 branches
BranchTrueFalseTotal
$timed_out ? : 0 0 0
$truncated || $timed_out ? : 0 0 0
Condition0%0/3
$truncated or $timed_out
l!l&&r!l&&!r
000
MC/DC0%0/2
$truncated or $timed_out
$truncated $timed_out
Truth table0%0/3
A or B
A= $truncatedB= $timed_out
ABresult
1X1
011
000
1937 stdout => $stdout,
1938 stderr => $stderr,
1939 exit => $status >> 8,
1940 signal => $status & 127,
1941 timed_out => $timed_out ? JSON::XS::true : JSON::XS::false,
1942 truncated => $truncated || $timed_out ? JSON::XS::true : JSON::XS::false,
1943 });
1944 0 };
1945 }
1946  
1947 4 my $perl_slave = q{#perl
1948 binmode STDIN;
1949 binmode STDOUT;
1950 $SIG{PIPE} = "IGNORE";
1951 $| = 1;
1952  
1953 for (;;) {
1954 4 == read STDIN, my $buf, 4
1955 or last;
1956 my $len = unpack "N", $buf;
1957 $len == read STDIN, $buf, $len
1958 or die "short perl frame\n";
1959  
1960 my @result = do {
1961 (my $source, local @ARGV) = unpack "(w/a*)*", $buf;
1962 ("+", eval $source)
1963 };
1964  
1965 @result = ("-", $@)
1966 if $@;
1967  
1968 print pack "N/a*", pack "(w/a*)*", @result
1969 or die "stdout: $!\n"
1970 }
1971 };
1972  
1973 10 ▶sub perl_frame {
Subroutine perl_frame: called CC=1 SCAR=0.0
1974 10 pack "N/a*", pack "(w/a*)*", @_
1975 }
1976  
1977 4 my $perl_worker;
1978  
1979 11 ▶sub perl_eval {
Subroutine perl_eval: called CC=6 SCAR=23.7
1980 11 my ($req, $workdir, $sandbox_grants, $source, $args, $timeout, $done) = @_;
1981  
1982 11 my @command = ((fs_sandbox $workdir, $sandbox_grants), $perl, "-e", $perl_slave);
1983 11 my $key = pack "(w/a*)*", @command;
1984 11 my $io = $perl_worker;
1985 11 undef $perl_worker;
1986  
1987 11 ▶ if ($io && ($io->{perl_key} ne $key || !$io->{proc}{pid})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($io and $io->{"perl_key"} ne $key || !$io->{"proc"}{"pid"}) 0 11 11
Condition50%3/6
$io and $io->{"perl_key"} ne $key || !$io->{"proc"}{"pid"}
!ll&&!rl&&r
380
$io->{"perl_key"} ne $key or not $io->{"proc"}{"pid"}
l!l&&r!l&&!r
008
MC/DC0%0/3
$io and $io->{"perl_key"} ne $key || !$io->{"proc"}{"pid"}
$io $io->{"perl_key"} ne $key not $io->{"proc"}{"pid"}
Truth table50%2/4
A and B or not(C)
A= $ioB= $io->{"perl_key"} ne $keyC= not $io->{"proc"}{"pid"}
ABCresult
0XX0
1000
11X1
1011
1988 0 proc_destroy $io;
1989 0 undef $io;
1990 }
1991  
1992 11 ▶ unless ($io) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($io) 3 8 11
1993 3 $io = proc_spawn @command;
1994 2 $io->{rbuf_max} = (1 << 20) + 4096;
1995 2 $io->{perl_key} = $key;
1996 2 weaken (my $this = $io);
1997  
1998 0 ▶ my $idle_destroy = sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
1999 0 ▶ my $io = $this or return;
Branch: 1 branch
BranchTrueFalseTotal
my $io = $this or return 0 0 0
2000  
2001 0 ▶ undef $perl_worker if $perl_worker && $perl_worker == $io;
Branch: 1 branch
BranchTrueFalseTotal
if $perl_worker and $perl_worker == $io 0 0 0
Condition0%0/3
$perl_worker and $perl_worker == $io
!ll&&!rl&&r
000
MC/DC0%0/2
$perl_worker and $perl_worker == $io
$perl_worker $perl_worker == $io
Truth table0%0/3
A and B
A= $perl_workerB= $perl_worker == $io
ABresult
0X0
100
111
2002 0 proc_destroy $io;
2003 2 };
2004 0 ▶ my $idle_stderr = sub { $_[0]{rbuf} = "" };
Subroutine __ANON__: not called CC=1 SCAR=1.2
2005  
2006 10 ▶ $io->{perl_idle} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2007 10 my ($io) = @_;
2008 10 my $err = $io->{proc_err};
2009  
2010 10 $io ->on_eof ($idle_destroy);
2011 10 $io ->on_error ($idle_destroy);
2012 10 $err->on_eof ($idle_destroy);
2013 10 $err->on_error ($idle_destroy);
2014 10 $err->on_read ($idle_stderr );
2015 10 $io ->on_read ($idle_destroy);
2016 2 };
2017  
2018 0 ▶ proc_on_exit $io->{proc}, sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
2019 0 ▶ my $io = $this or return;
Branch: 1 branch
BranchTrueFalseTotal
my $io = $this or return 0 0 0
2020  
2021 0 ▶ $io->{perl_on_exit}->($_[0]) if $io->{perl_on_exit};
Branch: 1 branch
BranchTrueFalseTotal
if $io->{"perl_on_exit"} 0 0 0
2022 0 ▶ $idle_destroy->() if $perl_worker && $perl_worker == $io;
Branch: 1 branch
BranchTrueFalseTotal
if $perl_worker and $perl_worker == $io 0 0 0
Condition0%0/3
$perl_worker and $perl_worker == $io
!ll&&!rl&&r
000
MC/DC0%0/2
$perl_worker and $perl_worker == $io
$perl_worker $perl_worker == $io
Truth table0%0/3
A and B
A= $perl_workerB= $perl_worker == $io
ABresult
0X0
100
111
2023 2 };
2024 }
2025  
2026 10 my $err = $io->{proc_err};
2027 10 my $timer;
2028 10 my $stderr = "";
2029  
2030 10 ▶ my $finish = sub {
Subroutine __ANON__: called CC=17 SCAR=41.5
2031 10 my ($failure, $payload) = @_;
2032 10 ▶ my $cb = $done or return;
Branch: 1 branch
BranchTrueFalseTotal
my $cb = $done or return 10 0 10
2033 10 undef $done;
2034 10 undef $timer;
2035 10 delete $req->{on_cancel};
2036 10 delete $io->{perl_on_exit};
2037  
2038 10 ▶ if ($failure || defined $io->{proc}{status}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($failure or defined $io->{"proc"}{"status"}) 0 10 10
Condition33%1/3
$failure or defined $io->{"proc"}{"status"}
l!l&&r!l&&!r
0010
MC/DC0%0/2
$failure or defined $io->{"proc"}{"status"}
$failure defined $io->{"proc"}{"status"}
Truth table33%1/3
A or B
A= $failureB= defined $io->{"proc"}{"status"}
ABresult
1X1
011
000
2039 0 my $status = $io->{proc}{status};
2040 0 ▶ my $reason = $failure || "exited (exit " . ($status >> 8)
Condition0%0/2
$failure || 'exited (exit ' . ($status >> 8) . ', signal ' . ($status & 127) . ')'
l!l
00
MC/DC0%0/1
$failure || 'exited (exit ' . ($status >> 8) . ', signal ' . ($status & 127) . ')'
$failure
Truth table0%0/2
A
A= $failure
Aresult
11
00
2041 . ", signal " . ($status & 127) . ")";
2042 0 ▶ AE::log warn => "sandbox perl worker: $reason"
Branch: 1 branch
BranchTrueFalseTotal
unless $failure and $failure =~ /\Asandbox perl (?:cancelled|timed out)\n\z/u 0 0 0
Condition0%0/3
$failure and $failure =~ /\Asandbox perl (?:cancelled|timed out)\n\z/u
!ll&&!rl&&r
000
MC/DC0%0/2
$failure and $failure =~ /\Asandbox perl (?:cancelled|timed out)\n\z/u
$failure $failure =~ /\Asandbox perl (?:cancelled|timed out)\n\z/u
Truth table0%0/3
A and B
A= $failureB= $failure =~ /\Asandbox perl (?:cancelled|timed out)\n\z/u
ABresult
0X0
100
111
2043 unless $failure && $failure =~ /\Asandbox perl (?:cancelled|timed out)\n\z/;
2044 0 proc_destroy $io;
2045 return $cb->(0, $failure || "sandbox perl exited\n")
2046 0 ▶ unless $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
unless $req->{"finished"} 0 0 0
Condition0%0/2
$failure || "sandbox perl exited\n"
l!l
00
MC/DC0%0/1
$failure || "sandbox perl exited\n"
$failure
Truth table0%0/2
A
A= $failure
Aresult
11
00
2047 0 return;
2048 }
2049  
2050 10 my (@response, $error);
2051 10 my $ok = eval {
2052 10 @response = unpack "(w/a*)*", $payload;
2053 10 my $status = shift @response;
2054 10 ▶ defined $status or die "missing perl response status\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $status or die "missing perl response status\n" 10 0 10
2055 10 ▶ if ($status eq "-") {
Branch: 2 branches
BranchTrueFalseTotal
if ($status eq '-') { } 0 10 10
elsif ($status ne '+') { } 0 10 10
2056 0 $error = AnyEvent::MCP::utf8dec $response[0];
2057 } elsif ($status ne "+") {
2058 0 die "invalid perl response status\n";
2059 }
2060 1
2061 10 };
2062  
2063 10 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 10 10
2064 0 my $error = $@;
2065 0 AE::log warn => "sandbox perl worker: $error";
2066 0 proc_destroy $io;
2067 0 ▶ return $cb->(0, $error) unless $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
unless $req->{"finished"} 0 0 0
2068 0 return;
2069 }
2070  
2071 # the response completes the request; the interpreter remains idle.
2072 10 ▶ proc_destroy $perl_worker if $perl_worker;
Branch: 1 branch
BranchTrueFalseTotal
if $perl_worker 0 10 10
2073 10 $perl_worker = $io;
2074 10 $io->{perl_idle}->($io);
2075 10 ▶ return if $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"finished"} 0 10 10
2076 10 ▶ return $cb->(0, $error) if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 0 10 10
2077 10 $cb->(1, \@response);
2078 10 };
2079  
2080 0 ▶ $io->{perl_on_exit} = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2081 0 my ($status) = @_;
2082 0 $finish->("sandbox perl failed (exit " . ($status >> 8)
2083 . ", signal " . ($status & 127) . "): $stderr\n");
2084 10 };
2085  
2086 0 ▶ $req->{on_cancel} = sub { $finish->("sandbox perl cancelled\n") };
Subroutine __ANON__: not called CC=1 SCAR=1.2
2087 0 ▶ $io->on_eof (sub { $finish->("short perl response\n") });
Subroutine __ANON__: not called CC=1 SCAR=1.2
2088 0 ▶ $io->on_error (sub { $finish->("sandbox perl stdout: $_[2]\n") if $_[1] });
Subroutine __ANON__: not called CC=2 SCAR=13.0
Branch: 1 branch
BranchTrueFalseTotal
if $_[1] 0 0 0
2089 0 ▶ $err->on_read (sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
2090 0 ▶ $stderr .= substr $_[0]{rbuf}, 0, 65536 - length $stderr
Branch: 1 branch
BranchTrueFalseTotal
if length $stderr < 65536 0 0 0
2091 if length $stderr < 65536;
2092 0 $_[0]{rbuf} = "";
2093 10 });
2094 0 ▶ $err->on_eof (sub { $finish->("sandbox perl stderr closed\n") });
Subroutine __ANON__: not called CC=1 SCAR=1.2
2095 0 ▶ $err->on_error (sub { $finish->("sandbox perl stderr: $_[2]\n") if $_[1] });
Subroutine __ANON__: not called CC=2 SCAR=13.0
Branch: 1 branch
BranchTrueFalseTotal
if $_[1] 0 0 0
2096  
2097 0 ▶ $timer = AE::timer $timeout, 0, sub { $finish->("sandbox perl timed out\n") };
Subroutine __ANON__: not called CC=1 SCAR=1.2
2098 10 my $ok = eval {
2099 10 ▶ $io->push_read (packstring => "N", sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
2100 10 my ($io, $payload) = @_;
2101  
2102 return $finish->("unexpected sandbox perl output\n")
2103 10 ▶ if length $io->{rbuf};
Branch: 1 branch
BranchTrueFalseTotal
if length $io->{"rbuf"} 0 10 10
2104 10 $finish->(undef, $payload);
2105 10 });
2106 10 $io->push_write (perl_frame $source, @$args);
2107 10 1
2108 };
2109 10 ▶ $finish->($@) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 10 10
2110 }
2111  
2112 # resolve a configured workdir by persistent ID or exact path.
2113 13 ▶sub fs_workdir {
Subroutine fs_workdir: called CC=11 SCAR=35.1
2114 13 my ($id) = @_;
2115  
2116 13 ▶ $id = $workdir_ids->{ids}[0] if !defined $id and @workdir == 1;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $id and @workdir == 1 13 0 13
Condition33%1/3
not defined $id and @workdir == 1
!ll&&!rl&&r
0013
MC/DC0%0/2
not defined $id and @workdir == 1
not defined $id @workdir == 1
Truth table33%1/3
not(A) and B
A= not defined $idB= @workdir == 1
ABresult
0X0
100
111
2117  
2118 13 ▶ defined $id && !ref $id
Branch: 1 branch
BranchTrueFalseTotal
defined $id and not ref $id or die "select a configured workdir by ID or exact path\n" 13 0 13
Condition33%1/3
defined $id and not ref $id
!ll&&!rl&&r
0013
MC/DC0%0/2
defined $id and not ref $id
defined $id not ref $id
Truth table33%1/3
A and not(B)
A= defined $idB= not ref $id
ABresult
0X0
100
111
2119 or die "select a configured workdir by ID or exact path\n";
2120  
2121 13 my $i;
2122 13 ▶ if ($id =~ /\A[0-9]+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($id =~ /\A[0-9]+\z/u) { } 13 0 13
2123 13 ($i) = grep $workdir_ids->{ids}[$_] == $id, 0 .. $#workdir;
2124 13 ▶ defined $i or die "Unknown workdir ID '$id'\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $i or die "Unknown workdir ID '${id}'\n" 13 0 13
2125 } else {
2126 0 ▶ my @match = grep { $id eq $workdir_identity[$_] || $id eq $workdir[$_] } 0 .. $#workdir;
Condition0%0/3
$id eq $workdir_identity[$_] || $id eq $workdir[$_]
l!l&&r!l&&!r
000
MC/DC0%0/2
$id eq $workdir_identity[$_] || $id eq $workdir[$_]
$id eq $workdir_identity[$_] $id eq $workdir[$_]
Truth table0%0/3
A || B
A= $id eq $workdir_identity[$_]B= $id eq $workdir[$_]
ABresult
1X1
011
000
2127 0 ▶ @match == 1 or die @match
Branch: 2 branches
BranchTrueFalseTotal
@match == 1 or die @match ? "Ambiguous configured workdir '${id}'\n" : "Unknown configured workdir '${id}'\n" 0 0 0
@match ? : 0 0 0
2128 ? "Ambiguous configured workdir '$id'\n"
2129 : "Unknown configured workdir '$id'\n";
2130 0 $i = $match[0];
2131 }
2132  
2133 13 ▶ wantarray ? ($workdir[$i], $workdir_identity[$i]) : $workdir[$i]
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 13 0 13
2134 }
2135  
2136 4 my $workdir_schema = {
2137 description => "Workdir ID or configured absolute path. Get IDs/paths from cerebro-fs.workdirs. IDs are persistent.",
2138 anyOf => [
2139 { type => "integer", minimum => 1 },
2140 { type => "string", minLength => 1 },
2141 ],
2142 };
2143  
2144 sub fs_result;
2145  
2146 # command output options affect presentation, never argv or permission scope.
2147 4 my %output_schema = (
2148 grep => { type => "string", description => "Optional PCRE stdout line filter after capture; no shell." },
2149 max_lines => { type => "integer", minimum => 1, maximum => 100000, default => 2000,
2150 description => "Max stdout lines after filtering." },
2151 max_bytes => { type => "integer", minimum => 1, maximum => 1048576, default => 65536,
2152 description => "Max returned UTF-8 bytes per stream; stderr unfiltered." },
2153 );
2154  
2155 2 ▶sub fs_output_options {
Subroutine fs_output_options: called CC=13 SCAR=41.4
2156 2 my ($args) = @_;
2157  
2158 2 ▶ my %options = (max_lines => $args->{max_lines} // 2000, max_bytes => $args->{max_bytes} // 65536);
Condition50%2/4
$args->{"max_lines"} // 2000
l!l
02
$args->{"max_bytes"} // 65536
l!l
02
MC/DC0%0/1
$args->{"max_lines"} // 2000
$args->{"max_lines"}
MC/DC0%0/1
$args->{"max_bytes"} // 65536
$args->{"max_bytes"}
Truth table50%1/2
A
A= $args->{"max_lines"}
Aresult
11
00
Truth table50%1/2
A
A= $args->{"max_bytes"}
Aresult
11
00
2159 2 for my $name (qw(max_lines max_bytes)) {
2160 $options{$name} =~ /\A[0-9]+\z/ && $options{$name} >= 1
2161 && $options{$name} <= $output_schema{$name}{maximum}
2162 4 ▶ or die "invalid $name\n";
Branch: 1 branch
BranchTrueFalseTotal
$options{$name} =~ /\A[0-9]+\z/u and $options{$name} >= 1 and $options{$name} <= $output_schema{$name}{"maximum"} or die "invalid $name\n" 4 0 4
Condition33%2/6
$options{$name} =~ /\A[0-9]+\z/u and $options{$name} >= 1 and $options{$name} <= $output_schema{$name}{"maximum"}
!ll&&!rl&&r
004
$options{$name} =~ /\A[0-9]+\z/u and $options{$name} >= 1
!ll&&!rl&&r
004
MC/DC0%0/3
$options{$name} =~ /\A[0-9]+\z/u and $options{$name} >= 1 and $options{$name} <= $output_schema{$name}{"maximum"}
$options{$name} =~ /\A[0-9]+\z/u $options{$name} >= 1 $options{$name} <= $output_schema{$name}{"maximum"}
Truth table25%1/4
A and B and C
A= $options{$name} =~ /\A[0-9]+\z/uB= $options{$name} >= 1C= $options{$name} <= $output_schema{$name}{"maximum"}
ABCresult
0XX0
10X0
1100
1111
2163 }
2164  
2165 2 ▶ if (exists $args->{grep}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args->{"grep"}) 0 2 2
2166 defined $args->{grep} && !ref $args->{grep} && $args->{grep} !~ /\0/
2167 0 ▶ && length $args->{grep} <= 65536
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{"grep"} and not ref $args->{"grep"} and not $args->{"grep"} =~ /\0/u and length $args->{"grep"} <= 65536 or die "grep must be a string without NUL, at most 65536 characters\n" 0 0 0
Condition0%0/9
defined $args->{"grep"} and not ref $args->{"grep"} and not $args->{"grep"} =~ /\0/u and length $args->{"grep"} <= 65536
!ll&&!rl&&r
000
defined $args->{"grep"} and not ref $args->{"grep"} and not $args->{"grep"} =~ /\0/u
!ll&&!rl&&r
000
defined $args->{"grep"} and not ref $args->{"grep"}
!ll&&!rl&&r
000
MC/DC0%0/4
defined $args->{"grep"} and not ref $args->{"grep"} and not $args->{"grep"} =~ /\0/u and length $args->{"grep"} <= 65536
defined $args->{"grep"} not ref $args->{"grep"} not $args->{"grep"} =~ /\0/u length $args->{"grep"} <= 65536
Truth table0%0/5
A and not(B) and not(C) and D
A= defined $args->{"grep"}B= not ref $args->{"grep"}C= not $args->{"grep"} =~ /\0/uD= length $args->{"grep"} <= 65536
ABCDresult
0XXX0
10XX0
110X0
11100
11111
2168 or die "grep must be a string without NUL, at most 65536 characters\n";
2169 0 ▶ $grep or die "output filtering needs GNU grep\n";
Branch: 1 branch
BranchTrueFalseTotal
$grep or die "output filtering needs GNU grep\n" 0 0 0
2170 0 $options{grep} = AnyEvent::MCP::utf8enc $args->{grep};
2171 }
2172  
2173 2 \%options
2174 }
2175  
2176 # clipping a UTF-8 stream may leave at most three bytes of an incomplete character.
2177 2 ▶sub fs_output_text {
Subroutine fs_output_text: called CC=4 SCAR=16.1
2178 2 my ($bytes, $cut) = @_;
2179  
2180 2 ▶ for (0 .. ($cut ? 3 : 0)) {
Branch: 1 branch
BranchTrueFalseTotal
$cut ? : 0 2 2
2181 2 my $text = $bytes;
2182 2 ▶ return $text if utf8::decode $text;
Branch: 1 branch
BranchTrueFalseTotal
if utf8::decode($text) 2 0 2
2183 0 chop $bytes;
2184 }
2185  
2186 0 die "command output is not UTF-8\n";
2187 }
2188  
2189 # preserve child status while bounding capture and, separately, returned output.
2190 2 ▶sub fs_command {
Subroutine fs_command: called CC=4 SCAR=18.9
2191 2 my ($req, $workdir, $grants, $argv, $input, $timeout, $options, $cwd) = @_;
2192  
2193 # argv and input are octets; workdir and cwd are Unicode paths.
2194 2 my $workdir_bytes = AnyEvent::MCP::utf8enc $workdir;
2195  
2196 # check the actual directory inside the worker, after resolving symlinks.
2197 2 ▶ $argv = [$perl, "-MCwd", "-e", q{
Branch: 1 branch
BranchTrueFalseTotal
if defined $cwd 0 2 2
2198 my $workdir = shift;
2199 chdir shift or die "VCS chdir: $!\n";
2200 my $cwd = Cwd::getcwd ();
2201 defined $cwd && ($workdir eq "/" || $cwd eq $workdir || (index $cwd, "$workdir/") == 0)
2202 or die "VCS cwd must resolve within the selected workdir\n";
2203 exec {$ARGV[0]} @ARGV;
2204 die "VCS exec: $!\n";
2205 }, $workdir_bytes, (AnyEvent::MCP::utf8enc $cwd), @$argv] if defined $cwd;
2206  
2207 2 ▶ my @command = ((fs_sandbox $workdir, $grants),
Branch: 2 branches
BranchTrueFalseTotal
$bwrap ? : 0 2 2
$remote ? : 0 2 2
2208 $bwrap ? @$argv
2209 : ($remote ? $perl : $^X, "-e", 'chdir shift or die "chdir: $!"; exec @ARGV; die "exec: $!";', $workdir_bytes, @$argv));
2210 2 my ($stdout, $stderr) = ("", "");
2211 2 my ($stdout_cut, $stderr_cut);
2212  
2213 3 ▶ my $capture = sub {
Subroutine __ANON__: called CC=3 SCAR=11.2
2214 3 my ($handle, $out, $cut) = @_;
2215 3 my $remaining = 1048576 - length $$out;
2216 3 ▶ $$cut = 1 if length $handle->{rbuf} > $remaining;
Branch: 1 branch
BranchTrueFalseTotal
if length $handle->{"rbuf"} > $remaining 0 3 3
2217 3 ▶ $$out .= substr $handle->{rbuf}, 0, $remaining if $remaining > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $remaining > 0 3 0 3
2218 3 $handle->{rbuf} = "";
2219 3 0
2220 2 };
2221  
2222 proc_run $req, \@command, $input, $timeout,
2223 2 ▶ sub { $capture->($_[0], \$stdout, \$stdout_cut) },
Subroutine __ANON__: called CC=1 SCAR=0.0
2224 1 ▶ sub { $capture->($_[0], \$stderr, \$stderr_cut) },
Subroutine __ANON__: called CC=1 SCAR=0.0
2225 1 ▶ sub {
Subroutine __ANON__: called CC=8 SCAR=32.1
2226 1 my ($status, $timed_out, $failure) = @_;
2227 1 ▶ return $req->error ($failure) if $failure;
Branch: 1 branch
BranchTrueFalseTotal
if $failure 0 1 1
2228  
2229 1 ▶ my $result = {
Branch: 2 branches
BranchTrueFalseTotal
$timed_out ? : 0 1 1
$stdout_cut || $stderr_cut || $timed_out ? : 0 1 1
Condition33%2/6
$stdout_cut or $stderr_cut or $timed_out
l!l&&r!l&&!r
001
$stdout_cut or $stderr_cut
l!l&&r!l&&!r
001
MC/DC0%0/3
$stdout_cut or $stderr_cut or $timed_out
$stdout_cut $stderr_cut $timed_out
Truth table25%1/4
A or B or C
A= $stdout_cutB= $stderr_cutC= $timed_out
ABCresult
1XX1
01X1
0011
0000
2230 exit => $status >> 8, signal => $status & 127,
2231 timed_out => $timed_out ? JSON::XS::true : JSON::XS::false,
2232 capture_truncated => $stdout_cut || $stderr_cut || $timed_out ? JSON::XS::true : JSON::XS::false,
2233 };
2234  
2235 1 ▶ my $finish = sub {
Subroutine __ANON__: called CC=12 SCAR=31.2
2236 1 my $ok = eval {
2237 1 ▶ $stdout_cut = 1 if length $stdout > $options->{max_bytes};
Branch: 1 branch
BranchTrueFalseTotal
if length $stdout > $options->{"max_bytes"} 0 1 1
2238 1 ▶ $stderr_cut = 1 if length $stderr > $options->{max_bytes};
Branch: 1 branch
BranchTrueFalseTotal
if length $stderr > $options->{"max_bytes"} 0 1 1
2239 1 my $out = fs_output_text (substr ($stdout, 0, $options->{max_bytes}), $stdout_cut);
2240 1 my $err = fs_output_text (substr ($stderr, 0, $options->{max_bytes}), $stderr_cut);
2241 1 my @lines = split /(?<=\n)/, $out;
2242 1 ▶ if (@lines > $options->{max_lines}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@lines > $options->{"max_lines"}) 0 1 1
2243 0 splice @lines, $options->{max_lines};
2244 0 $out = join "", @lines;
2245 0 $stdout_cut = 1;
2246 }
2247 1 @$result{qw(stdout stderr)} = ($out, $err);
2248 1 ▶ $result->{stdout_truncated} = $stdout_cut || $timed_out ? JSON::XS::true : JSON::XS::false;
Branch: 1 branch
BranchTrueFalseTotal
$stdout_cut || $timed_out ? : 0 1 1
Condition33%1/3
$stdout_cut or $timed_out
l!l&&r!l&&!r
001
MC/DC0%0/2
$stdout_cut or $timed_out
$stdout_cut $timed_out
Truth table33%1/3
A or B
A= $stdout_cutB= $timed_out
ABresult
1X1
011
000
2249 1 ▶ $result->{stderr_truncated} = $stderr_cut || $timed_out ? JSON::XS::true : JSON::XS::false;
Branch: 1 branch
BranchTrueFalseTotal
$stderr_cut || $timed_out ? : 0 1 1
Condition33%1/3
$stderr_cut or $timed_out
l!l&&r!l&&!r
001
MC/DC0%0/2
$stderr_cut or $timed_out
$stderr_cut $timed_out
Truth table33%1/3
A or B
A= $stderr_cutB= $timed_out
ABresult
1X1
011
000
2250 1 ▶ $result->{truncated} = $stdout_cut || $stderr_cut || $timed_out ? JSON::XS::true : JSON::XS::false;
Branch: 1 branch
BranchTrueFalseTotal
$stdout_cut || $stderr_cut || $timed_out ? : 0 1 1
Condition33%2/6
$stdout_cut or $stderr_cut or $timed_out
l!l&&r!l&&!r
001
$stdout_cut or $stderr_cut
l!l&&r!l&&!r
001
MC/DC0%0/3
$stdout_cut or $stderr_cut or $timed_out
$stdout_cut $stderr_cut $timed_out
Truth table25%1/4
A or B or C
A= $stdout_cutB= $stderr_cutC= $timed_out
ABCresult
1XX1
01X1
0011
0000
2251 1 1
2252 };
2253 1 ▶ return $req->error ($@) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 1 1
2254 1 $req->reply (fs_result $result, exists $result->{filter_error});
2255 1 };
2256  
2257 1 ▶ return $finish->() unless exists $options->{grep};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $options->{"grep"} 1 0 1
2258  
2259 {
2260 0 my $ok = eval { $stdout = AnyEvent::MCP::utf8enc (fs_output_text $stdout, $stdout_cut); 1 };
2261 0 ▶ return $req->error ($@) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
2262 }
2263  
2264 # regex execution stays in a timed worker, outside the broker's event loop.
2265 0 my @filter = ((fs_sandbox $workdir, $grants), $grep, "-aP", "--", $options->{grep});
2266 0 ▶ fs_run $req, \@filter, $stdout, 5, 1048576, 0, sub {
Subroutine __ANON__: not called CC=8 SCAR=42.8
2267 0 my ($success, $filtered) = @_;
2268 0 ▶ if (!$success || $filtered->{exit} > 1 || $filtered->{signal} || $filtered->{timed_out}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $success or $filtered->{'exit'} > 1 or $filtered->{'signal'} or $filtered->{'timed_out'}) { } 0 0 0
Condition0%0/9
not $success or $filtered->{"exit"} > 1 or $filtered->{"signal"} or $filtered->{"timed_out"}
l!l&&r!l&&!r
000
not $success or $filtered->{"exit"} > 1 or $filtered->{"signal"}
l!l&&r!l&&!r
000
not $success or $filtered->{"exit"} > 1
l!l&&r!l&&!r
000
MC/DC0%0/4
not $success or $filtered->{"exit"} > 1 or $filtered->{"signal"} or $filtered->{"timed_out"}
not $success $filtered->{"exit"} > 1 $filtered->{"signal"} $filtered->{"timed_out"}
Truth table0%0/5
not(A) or B or C or D
A= not $successB= $filtered->{"exit"} > 1C= $filtered->{"signal"}D= $filtered->{"timed_out"}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
2269 0 ▶ my $error = $success ? $filtered->{stderr} : $filtered;
Branch: 1 branch
BranchTrueFalseTotal
$success ? : 0 0 0
2270 0 ▶ $error = eval { fs_output_text (substr ($error, 0, 4096), 1) } || "no diagnostic";
Condition0%0/2
eval { do { fs_output_text(substr($error, 0, 4096), 1) } } || 'no diagnostic'
l!l
00
MC/DC0%0/1
eval { do { fs_output_text(substr($error, 0, 4096), 1) } } || 'no diagnostic'
eval { do { fs_output_text(substr($error, 0, 4096), 1) } }
Truth table0%0/2
A
A= eval { do { fs_output_text(substr($error, 0, 4096), 1) } }
Aresult
11
00
2271 0 $result->{filter_error} = "stdout filter failed: $error";
2272 0 $stdout = "";
2273 0 $stdout_cut = 1;
2274 } else {
2275 0 $stdout = $filtered->{stdout};
2276 0 ▶ $stdout_cut ||= $filtered->{truncated};
Condition0%0/3
$stdout_cut ||= $filtered->{"truncated"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$stdout_cut ||= $filtered->{"truncated"}
$stdout_cut $filtered->{"truncated"}
Truth table0%0/3
A ||= B
A= $stdout_cutB= $filtered->{"truncated"}
ABresult
1X1
011
000
2277 }
2278 0 $finish->();
2279 0 };
2280 2 };
2281 }
2282  
2283 # wrap raw text as an MCP text result.
2284 14 ▶sub fs_text_result {
Subroutine fs_text_result: called CC=2 SCAR=7.0
2285 14 my ($text, $failed) = @_;
2286  
2287 14 my $response = {
2288 content => [{
2289 type => "text",
2290 text => $text,
2291 }],
2292 };
2293  
2294 14 ▶ $response->{isError} = JSON::XS::true if $failed;
Branch: 1 branch
BranchTrueFalseTotal
if $failed 0 14 14
2295  
2296 14 $response
2297 }
2298  
2299 # wrap a Perl value as an MCP text result.
2300 12 ▶sub fs_result {
Subroutine fs_result: called CC=1 SCAR=0.0
2301 12 my ($result, $failed) = @_;
2302  
2303 12 my $response = fs_text_result (JSON::XS->new->encode ($result), $failed);
2304 12 $response->{structuredContent} = $result;
2305  
2306 12 $response
2307 }
2308  
2309 mcp_tool workdirs =>
2310 "List workdirs, VCS markers (remote snapshot at startup), available VCS clients, sandbox grants, trusted mounts, runtime paths.",
2311 {
2312 type => "object",
2313 properties => {},
2314 additionalProperties => JSON::XS::false,
2315 },
2316 3 ▶ sub {
Subroutine __ANON__: called CC=7 SCAR=25.7
2317 3 my ($req, $args) = @_;
2318  
2319 3 AE::log debug => "fs workdirs";
2320  
2321 # report metadata markers, not an inferred repository for the tree.
2322 3 my %marker = (cvs => "CVS", git => ".git", hg => ".hg", svn => ".svn");
2323 my %workdir_vcs = map {
2324 3 my $i = $_;
2325 ($workdir_identity[$i] => $remote ? $remote_vcs_marker[$i] : [grep {
2326 3 ▶ lstat "$workdir[$i]/$marker{$_}" && (-d _ || -l _ || ($_ eq "git" && -f _))
Branch: 1 branch
BranchTrueFalseTotal
$remote ? : 0 3 3
Condition8%1/12
lstat "$workdir[$i]/$marker{$_}" && (-d _ || -l _ || $_ eq 'git' && -f _)
!ll&&!rl&&r
1200
-d _ or -l _ or $_ eq "git" and -f _
l!l&&r!l&&!r
000
-d _ or -l _
l!l&&r!l&&!r
000
$_ eq "git" and -f _
!ll&&!rl&&r
000
MC/DC0%0/5
lstat "$workdir[$i]/$marker{$_}" && (-d _ || -l _ || $_ eq 'git' && -f _)
lstat "$workdir[$i]/$marker{$_}" -d _ -l _ $_ eq "git" -f _
Truth table16%1/6
A && B or C or D and E
A= lstat "$workdir[$i]/$marker{$_}"B= -d _C= -l _D= $_ eq "git"E= -f _
ABCDEresult
0XXXX0
1000X0
100100
11XXX1
101XX1
100111
2327 } sort keys %marker])
2328 } 0 .. $#workdir;
2329  
2330 $req->reply (fs_result +{
2331 ($remote ? (host => $host, rsh => $rsh) : ()),
2332 3 workdirs => { map { $workdir_ids->{ids}[$_] => $workdir_identity[$_] } reverse 0 .. $#workdir },
2333 3 resolved_workdirs => { map { $workdir_ids->{ids}[$_] => $workdir[$_] } 0 .. $#workdir },
2334 workdir_vcs => \%workdir_vcs,
2335 3 ▶ vcs_backends => [sort grep defined $vcs_program{$_}, keys %vcs_program],
Branch: 1 branch
BranchTrueFalseTotal
$remote ? : 0 3 3
2336 umask => (sprintf "%04o", $umask),
2337 runtime_paths => \@runtime_path,
2338 mounts => \@mount,
2339 sandbox_grants => \%sandbox_grant,
2340 exec_default_sandbox_grants => \@exec_default_sandbox_grants,
2341 unavailable_sandbox_grants => ["host-proc"],
2342 });
2343 }
2344 4 ;
2345  
2346 # escape a pathname for compact line-oriented text output.
2347 0 ▶sub escape_path {
Subroutine escape_path: not called CC=1 SCAR=6.9
2348 0 my ($text) = @_;
2349  
2350 0 $text =~ s/\\/\\\\/g;
2351 0 $text =~ s/\n/\\n/g;
2352 0 $text
2353 }
2354  
2355 0 ▶sub format_iec_number {
Subroutine format_iec_number: not called CC=4 SCAR=30.0
2356 0 my ($number) = @_;
2357  
2358 0 for my $suffix ("", qw(k M G T P)) {
2359 0 ▶ return "$number$suffix" if $number < 1024 or $suffix eq "P";
Branch: 1 branch
BranchTrueFalseTotal
if $number < 1024 or $suffix eq "P" 0 0 0
Condition0%0/3
$number < 1024 or $suffix eq "P"
l!l&&r!l&&!r
000
MC/DC0%0/2
$number < 1024 or $suffix eq "P"
$number < 1024 $suffix eq "P"
Truth table0%0/3
A or B
A= $number < 1024B= $suffix eq "P"
ABresult
1X1
011
000
2360 0 $number = int (($number + 512) / 1024);
2361 }
2362 }
2363  
2364 0 ▶sub fs_find_relative {
Subroutine fs_find_relative: not called CC=3 SCAR=24.8
2365 0 my ($base, $path) = @_;
2366  
2367 0 ▶ return "" if $path eq $base;
Branch: 1 branch
BranchTrueFalseTotal
if $path eq $base 0 0 0
2368 0 ▶ substr $path, (length $base) + ($base eq "/" ? 0 : 1)
Branch: 1 branch
BranchTrueFalseTotal
$base eq '/' ? : 0 0 0
2369 }
2370  
2371 0 ▶sub format_path_listing {
Subroutine format_path_listing: not called CC=9 SCAR=45.0
2372 0 my ($base, $record, $truncated) = @_;
2373  
2374 0 my (@line, $directory);
2375  
2376 0 for my $record (sort { $a->[2] cmp $b->[2] } @$record) {
2377 0 my ($type, $size, $full_path) = @$record;
2378 0 my $relative = fs_find_relative $base, $full_path;
2379  
2380 0 ▶ if ($type eq "d") {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "d") 0 0 0
2381 0 push @line, "/" . (escape_path $relative);
2382 0 $directory = $relative;
2383 0 next;
2384 }
2385  
2386 0 my ($dir, $name);
2387  
2388 0 ▶ if (!length $relative) {
Branch: 1 branch
BranchTrueFalseTotal
if (not length $relative) { } 0 0 0
2389 0 ($name) = $full_path =~ m{([^/]*)\z};
2390 } else {
2391 0 ($dir, $name) = $relative =~ m{\A(?:(.*)/)?([^/]*)\z};
2392 0 ▶ $dir //= "";
Condition0%0/2
$dir //= ""
l!l
00
MC/DC0%0/1
$dir //= ""
$dir
Truth table0%0/2
A
A= $dir
Aresult
11
00
2393  
2394 0 ▶ if (!defined $directory or $directory ne $dir) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $directory or $directory ne $dir) 0 0 0
Condition0%0/3
not defined $directory or $directory ne $dir
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $directory or $directory ne $dir
not defined $directory $directory ne $dir
Truth table0%0/3
not(A) or B
A= not defined $directoryB= $directory ne $dir
ABresult
1X1
011
000
2395 0 push @line, "/" . (escape_path $dir);
2396 0 $directory = $dir;
2397 }
2398 }
2399  
2400 0 $name = escape_path $name;
2401 0 ▶ push @line, $type eq "f"
Branch: 1 branch
BranchTrueFalseTotal
$type eq 'f' ? : 0 0 0
2402 ? (join "\t", $type, (format_iec_number $size), $name)
2403 : (join "\t", $type, $name);
2404 }
2405  
2406 0 ▶ push @line, "!truncated" if $truncated;
Branch: 1 branch
BranchTrueFalseTotal
if $truncated 0 0 0
2407  
2408 0 join "", map "$_\n", @line
2409 }
2410  
2411 0 ▶sub fs_list_find {
Subroutine fs_list_find: not called CC=8 SCAR=42.8
2412 0 my ($req, $args, $recurse) = @_;
2413  
2414 0 ▶ my $tool = $recurse ? "find" : "list";
Branch: 1 branch
BranchTrueFalseTotal
$recurse ? : 0 0 0
2415  
2416 0 my ($workdir, $identity) = fs_workdir $args->{workdir};
2417 0 ▶ my $path = fs_path $workdir, length $args->{path} ? $args->{path} : ".";
Branch: 1 branch
BranchTrueFalseTotal
length $args->{'path'} ? : 0 0 0
2418 0 ▶ my $limit = $args->{limit} // 200;
Condition0%0/2
$args->{"limit"} // 200
l!l
00
MC/DC0%0/1
$args->{"limit"} // 200
$args->{"limit"}
Truth table0%0/2
A
A= $args->{"limit"}
Aresult
11
00
2419 0 ▶ $limit <= 1000
Branch: 1 branch
BranchTrueFalseTotal
$limit <= 1000 or die "invalid limit\n" 0 0 0
2420 or die "invalid limit\n";
2421  
2422 my $granted = fs_require_paths ($req, $workdir, $identity, [$path], "read",
2423 0 ▶ $args->{reason} // "$tool $path");
Condition0%0/2
$args->{"reason"} // "$tool $path"
l!l
00
MC/DC0%0/1
$args->{"reason"} // "$tool $path"
$args->{"reason"}
Truth table0%0/2
A
A= $args->{"reason"}
Aresult
11
00
2424  
2425 0 ▶ if ($recurse) {
Branch: 1 branch
BranchTrueFalseTotal
if ($recurse) { } 0 0 0
2426 0 AE::log debug => join " ", "fs", $tool, $path, (substr $args->{name}, 0, 40);
2427 } else {
2428 0 AE::log debug => "fs $tool $path";
2429 }
2430  
2431 0 my $find_path = AnyEvent::MCP::utf8enc $path;
2432 0 my @command = ((fs_sandbox $workdir, $granted), $find, $find_path);
2433  
2434 0 ▶ if ($recurse) {
Branch: 1 branch
BranchTrueFalseTotal
if ($recurse) { } 0 0 0
2435 0 my $needle = AnyEvent::MCP::utf8enc $args->{name};
2436 0 $needle =~ s/([\\*?\[])/\\$1/g;
2437 0 push @command, "!", "-type", "d", "-name", "*$needle*";
2438 } else {
2439 0 push @command, "-maxdepth", "1";
2440 }
2441  
2442 0 push @command, "-printf", q{%y\0%s\0%p\0};
2443  
2444 0 my (@record, $seen, $truncated, $failure);
2445 0 my $stderr = "";
2446  
2447 proc_run $req, \@command, "", 30,
2448 0 ▶ sub {
Subroutine __ANON__: not called CC=13 SCAR=52.0
2449 0 my ($handle, $eof) = @_;
2450  
2451 0 ▶ while (!$failure and !$truncated
Branch: 1 branch
BranchTrueFalseTotal
if (not $failure || $truncated and $handle->{"rbuf"} =~ s/\A([^\0]*)\0([^\0]*)\0([^\0]*)\0//su) 0 0 0
Condition0%0/6
not $failure || $truncated and $handle->{"rbuf"} =~ s/\A([^\0]*)\0([^\0]*)\0([^\0]*)\0//su
!ll&&!rl&&r
000
$failure || $truncated
l!l&&r!l&&!r
000
MC/DC0%0/3
not $failure || $truncated and $handle->{"rbuf"} =~ s/\A([^\0]*)\0([^\0]*)\0([^\0]*)\0//su
$failure $truncated $handle->{"rbuf"} =~ s/\A([^\0]*)\0([^\0]*)\0([^\0]*)\0//su
Truth table0%0/4
not(A || B) and C
A= $failureB= $truncatedC= $handle->{"rbuf"} =~ s/\A([^\0]*)\0([^\0]*)\0([^\0]*)\0//su
ABCresult
1XX0
01X0
0000
0011
2452 and $handle->{rbuf} =~ s/\A([^\0]*)\0([^\0]*)\0([^\0]*)\0//s) {
2453 0 my ($type, $size, $raw_path) = ($1, $2, $3);
2454 0 my $full_path = eval { AnyEvent::MCP::utf8dec $raw_path };
2455  
2456 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
2457 0 $failure = "$tool returned a non-UTF-8 pathname\n";
2458 0 last;
2459 }
2460  
2461 0 ▶ if (++$seen > $limit) {
Branch: 1 branch
BranchTrueFalseTotal
if (++$seen > $limit) 0 0 0
2462 0 $truncated = 1;
2463 0 last;
2464 }
2465  
2466 0 push @record, [$type, $size, $full_path];
2467 }
2468  
2469 $failure ||= "incomplete $tool output\n"
2470 0 ▶ if $eof && length $handle->{rbuf} && !$truncated;
Branch: 1 branch
BranchTrueFalseTotal
if $eof and length $handle->{"rbuf"} and not $truncated 0 0 0
Condition0%0/8
$eof and length $handle->{"rbuf"} and not $truncated
!ll&&!rl&&r
000
$eof and length $handle->{"rbuf"}
!ll&&!rl&&r
000
$failure ||= "incomplete $tool output\n"
l!l
00
MC/DC0%0/3
$eof and length $handle->{"rbuf"} and not $truncated
$eof length $handle->{"rbuf"} not $truncated
MC/DC0%0/1
$failure ||= "incomplete $tool output\n"
$failure
Truth table0%0/4
A and B and not(C)
A= $eofB= length $handle->{"rbuf"}C= not $truncated
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/2
A
A= $failure
Aresult
11
00
2471 0 ▶ $handle->{rbuf} = "" if $failure or $truncated;
Branch: 1 branch
BranchTrueFalseTotal
if $failure or $truncated 0 0 0
Condition0%0/3
$failure or $truncated
l!l&&r!l&&!r
000
MC/DC0%0/2
$failure or $truncated
$failure $truncated
Truth table0%0/3
A or B
A= $failureB= $truncated
ABresult
1X1
011
000
2472 0 ▶ $failure || $truncated
Branch: 1 branch
BranchTrueFalseTotal
$failure or $truncated 0 0 0
2473 },
2474 0 ▶ sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
2475 0 my ($handle) = @_;
2476 0 my $remaining = 65536 - length $stderr;
2477 0 ▶ $stderr .= substr $handle->{rbuf}, 0, $remaining if $remaining > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $remaining > 0 0 0 0
2478 0 $handle->{rbuf} = "";
2479 0 0
2480 },
2481 0 ▶ sub {
Subroutine __ANON__: not called CC=11 SCAR=48.8
2482 0 my ($status, $timed_out, $io_failure) = @_;
2483 0 ▶ return if $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"finished"} 0 0 0
2484  
2485 0 my $result;
2486 0 my $ok = eval {
2487 0 ▶ die "$tool timed out\n" if $timed_out;
Branch: 1 branch
BranchTrueFalseTotal
if $timed_out 0 0 0
2488 0 ▶ die $failure || $io_failure if $failure || $io_failure;
Branch: 1 branch
BranchTrueFalseTotal
if $failure or $io_failure 0 0 0
Condition0%0/6
$failure or $io_failure
l!l&&r!l&&!r
000
$failure || $io_failure
l!l&&r!l&&!r
000
MC/DC0%0/2
$failure or $io_failure
$failure $io_failure
MC/DC0%0/2
$failure || $io_failure
$failure $io_failure
Truth table0%0/3
A or B
A= $failureB= $io_failure
ABresult
1X1
011
000
Truth table0%0/3
A || B
A= $failureB= $io_failure
ABresult
1X1
011
000
2489  
2490 0 ▶ if (($status >> 8 or $status & 127) and !$truncated) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status >> 8 || $status & 127 and not $truncated) 0 0 0
Condition0%0/6
$status >> 8 || $status & 127 and not $truncated
!ll&&!rl&&r
000
$status >> 8 or $status & 127
l!l&&r!l&&!r
000
MC/DC0%0/3
$status >> 8 || $status & 127 and not $truncated
$status >> 8 $status & 127 not $truncated
Truth table0%0/5
A or B and not(C)
A= $status >> 8B= $status & 127C= not $truncated
ABCresult
00X0
1X00
0100
1X11
0111
2491 0 my $error = eval { AnyEvent::MCP::utf8dec $stderr };
2492 0 ▶ $error = "non-UTF-8 error output" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
2493 0 die "$tool failed (exit " . ($status >> 8) . ", signal " . ($status & 127) . "): $error\n";
2494 }
2495  
2496 0 $result = fs_text_result (format_path_listing $path, \@record, $truncated);
2497 0 1
2498 };
2499  
2500 0 ▶ if ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ok) { } 0 0 0
2501 0 $req->reply ($result);
2502 } else {
2503 0 $req->error ($@);
2504 }
2505 0 };
2506 }
2507  
2508 $find && mcp_tool list =>
2509 "List immediate entries; no symlink following. "
2510 . "Text format: /relative-directory headers; f<TAB>approx-size<TAB>name for files; "
2511 . "TYPE<TAB>name for l/p/s/b/c/? nodes. "
2512 . "Size suffixes k/M/G/T/P use IEC powers (1024); "
2513 . "!truncated means limit exceeded. Names escape backslash/newline.",
2514 {
2515 type => "object",
2516 properties => {
2517 path => {
2518 type => "string",
2519 description => "Directory; omitted/empty = .",
2520 },
2521 limit => {
2522 type => "integer",
2523 minimum => 1,
2524 maximum => 1000,
2525 default => 200,
2526 },
2527 workdir => $workdir_schema,
2528 reason => {
2529 type => "string",
2530 description => "Why access needed.",
2531 },
2532 },
2533 additionalProperties => JSON::XS::false,
2534 },
2535 0 ▶ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2536 0 fs_list_find $_[0], $_[1], 0
2537 }
2538 4 ▶;
Branch: 1 branch
BranchTrueFalseTotal
$find and mcp_tool("list", "List immediate entries; no symlink following. Text format: /relative-directory headers; f<TAB>approx-size<TAB>name for files; TYPE<TAB>name for l/p/s/b/c/? nodes. Size suffixes k/M/G/T/P use IEC powers (1024); !truncated means limit exceeded. Names escape backslash/newline.", {"type", "object", "properties", {"path", {"type", "string", "description", "Directory; omitted/empty = ."}, "limit", {"type", "integer", "minimum", 1, "maximum", 1000, "default", 200}, "workdir", $workdir_schema, "reason", {"type", "string", "description", "Why access needed."}}, "additionalProperties", &JSON::XS::false()}, sub { fs_list_find($_[0], $_[1], 0); } ) 4 0 4
2539  
2540 $find && mcp_tool find =>
2541 "Find non-directory entries recursively by literal basename substring; no symlink following. Output as list.",
2542 {
2543 type => "object",
2544 properties => {
2545 path => {
2546 type => "string",
2547 description => "Search root; omitted/empty = .",
2548 },
2549 name => {
2550 type => "string",
2551 minLength => 1,
2552 description => "Literal basename substring.",
2553 },
2554 limit => {
2555 type => "integer",
2556 minimum => 1,
2557 maximum => 1000,
2558 default => 200,
2559 },
2560 workdir => $workdir_schema,
2561 reason => {
2562 type => "string",
2563 description => "Why access needed.",
2564 },
2565 },
2566 required => ["name"],
2567 additionalProperties => JSON::XS::false,
2568 },
2569 0 ▶ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2570 0 fs_list_find $_[0], $_[1], 1
2571 }
2572 4 ▶;
Branch: 1 branch
BranchTrueFalseTotal
$find and mcp_tool("find", "Find non-directory entries recursively by literal basename substring; no symlink following. Output as list.", {"type", "object", "properties", {"path", {"type", "string", "description", "Search root; omitted/empty = ."}, "name", {"type", "string", "minLength", 1, "description", "Literal basename substring."}, "limit", {"type", "integer", "minimum", 1, "maximum", 1000, "default", 200}, "workdir", $workdir_schema, "reason", {"type", "string", "description", "Why access needed."}}, "required", ["name"], "additionalProperties", &JSON::XS::false()}, sub { fs_list_find($_[0], $_[1], 1); } ) 4 0 4
2573  
2574 4 my $file_read = q{#perl
2575 my ($path, $offset, $length) = @ARGV;
2576  
2577 open my $fh, "<:raw", $path or return 0, "open: $!";
2578 defined sysseek $fh, $offset, 0 or return 0, "seek: $!";
2579 my $n = sysread $fh, my $data, $length;
2580 defined $n or return 0, "read: $!";
2581  
2582 (1, $data)
2583 };
2584  
2585 $perl && mcp_tool file_read =>
2586 "Read up to 1 MiB at byte offset. Returns {data: BASE64}, even for text; {error: STRING} on filesystem failure. Prefer read-lines for source/text.",
2587 {
2588 type => "object",
2589 properties => {
2590 path => {
2591 type => "string",
2592 },
2593 offset => {
2594 type => "integer",
2595 minimum => 0,
2596 default => 0,
2597 },
2598 length => {
2599 type => "integer",
2600 minimum => 1,
2601 maximum => 1<<20,
2602 default => 1<<16,
2603 },
2604 workdir => $workdir_schema,
2605 reason => {
2606 type => "string",
2607 description => "Why access needed.",
2608 },
2609 },
2610 required => ["path"],
2611 additionalProperties => JSON::XS::false,
2612 },
2613 4 ▶ sub {
Subroutine __ANON__: called CC=5 SCAR=17.8
2614 4 my ($req, $args) = @_;
2615  
2616 4 my ($workdir, $identity) = fs_workdir $args->{workdir};
2617 4 ▶ my $offset = $args->{offset} // 0;
Condition50%1/2
$args->{"offset"} // 0
l!l
04
MC/DC0%0/1
$args->{"offset"} // 0
$args->{"offset"}
Truth table50%1/2
A
A= $args->{"offset"}
Aresult
11
00
2618 4 ▶ my $length = $args->{length} // 65536;
Condition50%1/2
$args->{"length"} // 65536
l!l
04
MC/DC0%0/1
$args->{"length"} // 65536
$args->{"length"}
Truth table50%1/2
A
A= $args->{"length"}
Aresult
11
00
2619 4 ▶ $length <= 1<<20
Branch: 1 branch
BranchTrueFalseTotal
$length <= 1048576 or die "invalid read range\n" 4 0 4
2620 or die "invalid read range\n";
2621 4 my $path = fs_path $workdir, $args->{path};
2622  
2623 my $granted = fs_require_paths ($req, $workdir, $identity, [$path], "read",
2624 4 ▶ $args->{reason} // "read $path");
Condition50%1/2
$args->{"reason"} // "read $path"
l!l
04
MC/DC0%0/1
$args->{"reason"} // "read $path"
$args->{"reason"}
Truth table50%1/2
A
A= $args->{"reason"}
Aresult
11
00
2625  
2626 4 AE::log debug => join " ", "fs file-read", $path, $offset, $length;
2627  
2628 perl_eval $req, $workdir, $granted, $file_read,
2629 4 ▶ [AnyEvent::MCP::utf8enc $path, $offset, $length], 30, sub {
Subroutine __ANON__: called CC=5 SCAR=19.6
2630 4 my ($success, $result) = @_;
2631  
2632 4 ▶ return $req->error ($result)
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 4 4
2633 unless $success;
2634  
2635 4 ▶ @$result == 2
Branch: 1 branch
BranchTrueFalseTotal
@$result == 2 or return $req->error("invalid file-read response\n") 4 0 4
2636 or return $req->error ("invalid file-read response\n");
2637 4 my ($ok, $value) = @$result;
2638 4 ▶ if ($ok eq "1") {
Branch: 2 branches
BranchTrueFalseTotal
if ($ok eq '1') { } 4 0 4
elsif ($ok eq '0') { } 0 0 0
2639 4 $req->reply (fs_result {
2640 data => MIME::Base64::encode_base64 ($value, ""),
2641 });
2642 } elsif ($ok eq "0") {
2643 0 $req->reply (fs_result {
2644 error => AnyEvent::MCP::utf8dec $value,
2645 });
2646 } else {
2647 0 $req->error ("invalid file-read status\n");
2648 }
2649 4 };
2650 }
2651 4 ▶;
Branch: 1 branch
BranchTrueFalseTotal
$perl and mcp_tool("file_read", "Read up to 1 MiB at byte offset. Returns {data: BASE64}, even for text; {error: STRING} on filesystem failure. Prefer read-lines for source/text.", {"type", "object", "properties", {"path", {"type", "string"}, "offset", {"type", "integer", "minimum", 0, "default", 0}, "length", {"type", "integer", "minimum", 1, "maximum", 1048576, "default", 65536}, "workdir", $workdir_schema, "reason", {"type", "string", "description", "Why access needed."}}, "required", ["path"], "additionalProperties", &JSON::XS::false()}, sub { my($req, $args) = @_; my($workdir, $identity) = fs_workdir($args->{"workdir"}); my $offset = $args->{"offset"} // 0; my $length = $args->{"length"} // 65536; $length <= 1048576 or die "invalid read range\n"; my $path = fs_path($workdir, $args->{"path"}); my $granted = fs_require_paths($req, $workdir, $identity, [$path], "read", $args->{"reason"} // "read $path"); &AE::log("debug", join(" ", "fs file-read", $path, $offset, $length)); perl_eval($req, $workdir, $granted, $file_read, [&AnyEvent::MCP::utf8enc($path), $offset, $length], 30, sub { my($success, $result) = @_; return $req->error($result) unless $success; @$result == 2 or return $req->error("invalid file-read response\n"); my($ok, $value) = @$result; if ($ok eq 1) { $req->reply(fs_result({"data", &MIME::Base64::encode_base64($value, "")})); } elsif ($ok eq 0) { $req->reply(fs_result({"error", &AnyEvent::MCP::utf8dec($value)})); } else { $req->error("invalid file-read status\n"); } ; } ); } ) 4 0 4
2652  
2653 $sed && mcp_tool read_lines =>
2654 "Read byte-LF (0x0A) lines by positive line ranges. "
2655 . "encoding: strict utf-8 (default), latin1 (raw bytes as text), base64 (exact range bytes). "
2656 . "linenums=true prefixes absolute line number plus colon (before base64 encoding). "
2657 . "Per range: two MCP text items, [range=N,M] metadata (truncated=1 if cut), then lines without added newlines. Preserves order, overlaps, duplicates; max 1 MiB raw output.",
2658 {
2659 type => "object",
2660 properties => {
2661 path => {
2662 type => "string",
2663 },
2664 ranges => {
2665 type => "array",
2666 description => 'Inclusive line ranges as strings, e.g. ["1,60", "80"]. Comma, not dash.',
2667 items => {
2668 type => "string",
2669 pattern => q{^[1-9][0-9]*(?:,[1-9][0-9]*)?$},
2670 },
2671 minItems => 1,
2672 maxItems => 20,
2673 },
2674 encoding => {
2675 type => "string",
2676 description => "Range format: strict utf-8 (default), latin1, base64. Lines split at byte LF (0x0A).",
2677 enum => ["utf-8", "latin1", "base64"],
2678 default => "utf-8",
2679 },
2680 linenums => {
2681 type => "boolean",
2682 description => "Prefix all lines, including blanks, with absolute number and colon.",
2683 default => JSON::XS::false,
2684 },
2685 workdir => $workdir_schema,
2686 reason => {
2687 type => "string",
2688 description => "Why access needed.",
2689 },
2690 },
2691 required => ["path", "ranges"],
2692 additionalProperties => JSON::XS::false,
2693 },
2694 0 ▶ sub {
Subroutine __ANON__: not called CC=7 SCAR=40.3
2695 0 my ($req, $args) = @_;
2696  
2697 0 ▶ my $encoding = $args->{encoding} // "utf-8";
Condition0%0/2
$args->{"encoding"} // "utf-8"
l!l
00
MC/DC0%0/1
$args->{"encoding"} // "utf-8"
$args->{"encoding"}
Truth table0%0/2
A
A= $args->{"encoding"}
Aresult
11
00
2698 0 ▶ $encoding =~ /\A(?:utf-8|latin1|base64)\z/ or die "invalid read-lines encoding\n";
Branch: 1 branch
BranchTrueFalseTotal
$encoding =~ /\A(?:utf-8|latin1|base64)\z/u or die "invalid read-lines encoding\n" 0 0 0
2699  
2700 0 my ($workdir, $identity) = fs_workdir $args->{workdir};
2701 0 my $path = fs_path $workdir, $args->{path};
2702 my @range = map {
2703 0 ▶ my ($start, $end) = /\A([1-9]\d*)(?:,([1-9]\d*))?\z/
Branch: 1 branch
BranchTrueFalseTotal
() = /\A([1-9]\d*)(?:,([1-9]\d*))?\z/u or die "invalid line range\n" 0 0 0
2704 or die "invalid line range\n";
2705 0 ▶ $end //= $start;
Condition0%0/3
$end //= $start
l!l&&r!l&&!r
000
MC/DC0%0/2
$end //= $start
$end $start
Truth table0%0/3
A //= B
A= $endB= $start
ABresult
1X1
011
000
2706 0 ▶ $start <= $end
Branch: 1 branch
BranchTrueFalseTotal
$start <= $end or die "invalid line range\n" 0 0 0
2707 or die "invalid line range\n";
2708 0 [$_, $start, $end]
2709 0 } @{$args->{ranges}};
2710  
2711 my $granted = fs_require_paths ($req, $workdir, $identity, [$path], "read",
2712 0 ▶ $args->{reason} // "read lines $path");
Condition0%0/2
$args->{"reason"} // "read lines $path"
l!l
00
MC/DC0%0/1
$args->{"reason"} // "read lines $path"
$args->{"reason"}
Truth table0%0/2
A
A= $args->{"reason"}
Aresult
11
00
2713  
2714 0 AE::log debug => join " ", "fs read-lines", $path, map $_->[0], @range;
2715  
2716 0 my (@result, $truncated);
2717 0 my $remaining = 1 << 20;
2718 0 my $next;
2719 0 ▶ $next = sub {
Subroutine __ANON__: not called CC=8 SCAR=42.8
2720 0 ▶ unless (@range) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@range) 0 0 0
2721 0 undef $next;
2722 0 my @content;
2723 0 for my $i (0 .. $#result) {
2724 0 my ($range, $body) = @{$result[$i]};
2725 0 my $header = "[range=$range";
2726 0 ▶ $header .= " truncated=1" if $truncated && $i == $#result;
Branch: 1 branch
BranchTrueFalseTotal
if $truncated and $i == $#result 0 0 0
Condition0%0/3
$truncated and $i == $#result
!ll&&!rl&&r
000
MC/DC0%0/2
$truncated and $i == $#result
$truncated $i == $#result
Truth table0%0/3
A and B
A= $truncatedB= $i == $#result
ABresult
0X0
100
111
2727 0 push @content,
2728 { type => "text", text => "$header]" },
2729 { type => "text", text => $body };
2730 }
2731 0 ▶ push @content, { type => "text", text => "[truncated=1]" }
Branch: 1 branch
BranchTrueFalseTotal
if $truncated and not @content 0 0 0
Condition0%0/3
$truncated and not @content
!ll&&!rl&&r
000
MC/DC0%0/2
$truncated and not @content
$truncated not @content
Truth table0%0/3
A and not(B)
A= $truncatedB= not @content
ABresult
0X0
100
111
2732 if $truncated && !@content;
2733 0 return $req->reply ({ content => \@content });
2734 }
2735  
2736 0 my ($range, $start, $end) = @{shift @range};
2737 0 ▶ my @command = (
Branch: 1 branch
BranchTrueFalseTotal
$start == $end ? : 0 0 0
2738 (fs_sandbox $workdir, $granted),
2739 $sed, "-n",
2740 "-e", ($start == $end ? "${start}p" : "${start},${end}p"),
2741 "-e", "${end}Q", # Preserve unterminated final line (GNU sed).
2742 AnyEvent::MCP::utf8enc $path,
2743 );
2744  
2745 0 ▶ fs_run $req, \@command, "", 30, $remaining, 0, sub {
Subroutine __ANON__: not called CC=14 SCAR=53.5
2746 0 my ($success, $value) = @_;
2747  
2748 0 ▶ return $req->error ($value)
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 0 0
2749 unless $success;
2750  
2751 0 my $body;
2752 0 my $ok = eval {
2753 0 ▶ die "read-lines timed out\n" if $value->{timed_out};
Branch: 1 branch
BranchTrueFalseTotal
if $value->{"timed_out"} 0 0 0
2754 0 ▶ if ($value->{exit} or $value->{signal}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value->{"exit"} or $value->{"signal"}) 0 0 0
Condition0%0/3
$value->{"exit"} or $value->{"signal"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$value->{"exit"} or $value->{"signal"}
$value->{"exit"} $value->{"signal"}
Truth table0%0/3
A or B
A= $value->{"exit"}B= $value->{"signal"}
ABresult
1X1
011
000
2755 0 my $stderr = AnyEvent::MCP::utf8dec $value->{stderr};
2756 0 die "read-lines failed (exit $value->{exit}, signal $value->{signal}): $stderr\n";
2757 }
2758 0 ▶ if ($args->{linenums} && length $value->{stdout}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"linenums"} and length $value->{"stdout"}) 0 0 0
Condition0%0/3
$args->{"linenums"} and length $value->{"stdout"}
!ll&&!rl&&r
000
MC/DC0%0/2
$args->{"linenums"} and length $value->{"stdout"}
$args->{"linenums"} length $value->{"stdout"}
Truth table0%0/3
A and B
A= $args->{"linenums"}B= length $value->{"stdout"}
ABresult
0X0
100
111
2759 0 my $line = $start;
2760 0 $value->{stdout} =~ s/^/$line++ . ":"/gme;
2761 0 ▶ if (length $value->{stdout} > $remaining) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $value->{"stdout"} > $remaining) 0 0 0
2762 0 substr ($value->{stdout}, $remaining) = "";
2763 0 $value->{truncated} = 1;
2764 }
2765 }
2766 $body = $encoding eq "utf-8" ? AnyEvent::MCP::utf8dec $value->{stdout}
2767 : $encoding eq "base64" ? MIME::Base64::encode_base64 ($value->{stdout}, "")
2768 0 ▶ : $value->{stdout}; # Unflagged byte strings are Latin-1 to Perl/JSON::XS.
Branch: 2 branches
BranchTrueFalseTotal
$encoding eq 'utf-8' ? : 0 0 0
$encoding eq 'base64' ? : 0 0 0
2769 0 1
2770 };
2771 0 ▶ return $req->error ($@)
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
2772 unless $ok;
2773  
2774 0 push @result, [$range, $body];
2775 0 $remaining -= length $value->{stdout};
2776 0 ▶ if ($value->{truncated} or ($remaining <= 0 and @range)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value->{"truncated"} or $remaining <= 0 and @range) 0 0 0
Condition0%0/6
$value->{"truncated"} or $remaining <= 0 and @range
l!l&&r!l&&!r
000
$remaining <= 0 and @range
!ll&&!rl&&r
000
MC/DC0%0/3
$value->{"truncated"} or $remaining <= 0 and @range
$value->{"truncated"} $remaining <= 0 @range
Truth table0%0/4
A or B and C
A= $value->{"truncated"}B= $remaining <= 0C= @range
ABCresult
1XX1
0111
00X0
0100
2777 0 $truncated = 1;
2778 0 @range = ();
2779 }
2780 0 $next->();
2781 0 };
2782 0 };
2783  
2784 0 $next->();
2785 }
2786 4 ▶;
Branch: 1 branch
BranchTrueFalseTotal
$sed and mcp_tool("read_lines", "Read byte-LF (0x0A) lines by positive line ranges. encoding: strict utf-8 (default), latin1 (raw bytes as text), base64 (exact range bytes). linenums=true prefixes absolute line number plus colon (before base64 encoding). Per range: two MCP text items, [range=N,M] metadata (truncated=1 if cut), then lines without added newlines. Preserves order, overlaps, duplicates; max 1 MiB raw output.", {"type", "object", "properties", {"path", {"type", "string"}, "ranges", {"type", "array", "description", "Inclusive line ranges as strings, e.g. [\"1,60\", \"80\"]. Comma, not dash.", "items", {"type", "string", "pattern", "^[1-9][0-9]*(?:,[1-9][0-9]*)?\$"}, "minItems", 1, "maxItems", 20}, "encoding", {"type", "string", "description", "Range format: strict utf-8 (default), latin1, base64. Lines split at byte LF (0x0A).", "enum", ["utf-8", "latin1", "base64"], "default", "utf-8"}, "linenums", {"type", "boolean", "description", "Prefix all lines, including blanks, with absolute number and colon.", "default", &JSON::XS::false()}, "workdir", $workdir_schema, "reason", {"type", "string", "description", "Why access needed."}}, "required", ["path", "ranges"], "additionalProperties", &JSON::XS::false()}, sub { my($req, $args) = @_; my $encoding = $args->{"encoding"} // "utf-8"; $encoding =~ /\A(?:utf-8|latin1|base64)\z/u or die "invalid read-lines encoding\n"; my($workdir, $identity) = fs_workdir($args->{"workdir"}); my $path = fs_path($workdir, $args->{"path"}); my(@range) = map({my($start, $end) = /\A([1-9]\d*)(?:,([1-9]\d*))?\z/u or die "invalid line range\n"; $end //= $start; $start <= $end or die "invalid line range\n"; [$_, $start, $end];} @{$$args{"ranges"};}); my $granted = fs_require_paths($req, $workdir, $identity, [$path], "read", $args->{"reason"} // "read lines $path"); &AE::log("debug", join(" ", "fs read-lines", $path, map($_->[0], @range))); my(@result, $truncated); my $remaining = 1048576; my $next; $next = sub { unless (@range) { undef $next; my @content; foreach my $i (0 .. $#result) { my($range, $body) = @{$result[$i];}; my $header = "[range=$range"; $header .= ' truncated=1' if $truncated and $i == $#result; push @content, {"type", "text", "text", "$header]"}, {"type", "text", "text", $body}; } ; push @content, {"type", "text", "text", "[truncated=1]"} if $truncated and not @content; return $req->reply({"content", \@content}); } ; my($range, $start, $end) = @{shift @range;}; my(@command) = (fs_sandbox($workdir, $granted), $sed, "-n", "-e", $start == $end ? "${start}p" : "$start,${end}p", "-e", "${end}Q", &AnyEvent::MCP::utf8enc($path)); fs_run($req, \@command, "", 30, $remaining, 0, sub { my($success, $value) = @_; return $req->error($value) unless $success; my $body; my $ok = eval { do { die "read-lines timed out\n" if $value->{"timed_out"}; if ($value->{"exit"} or $value->{"signal"}) { my $stderr = &AnyEvent::MCP::utf8dec($value->{"stderr"}); die qq[read-lines failed (exit $value->{"exit"}, signal $value->{"signal"}): $stderr\n]; } ; if ($args->{"linenums"} and length $value->{"stdout"}) { my $line = $start; $value->{"stdout"} =~ s/^/$line++ . ':';/egmu; if (length $value->{"stdout"} > $remaining) { substr($value->{"stdout"}, $remaining) = ""; $value->{"truncated"} = 1; } ; } ; $body = $encoding eq "utf-8" ? &AnyEvent::MCP::utf8dec($value->{"stdout"}) : ($encoding eq "base64" ? &MIME::Base64::encode_base64($value->{"stdout"}, "") : $value->{"stdout"}); 1 } }; return $req->error($@) unless $ok; push @result, [$range, $body]; $remaining -= length $value->{"stdout"}; if ($value->{"truncated"} or $remaining <= 0 and @range) { $truncated = 1; @range = (); } ; &$next(); } ); } ; &$next(); } ) 4 0 4
2787  
2788 4 my $file_write = q{#perl
2789 my ($path, $offset, $data) = @ARGV;
2790  
2791 use Fcntl qw(O_WRONLY O_CREAT);
2792 sysopen my $fh, $path, O_WRONLY | O_CREAT, 0666 or return 0, "open: $!";
2793  
2794 binmode $fh;
2795 defined sysseek $fh, $offset, 0 or return 0, "seek: $!";
2796 my $n = syswrite $fh, $data;
2797 defined $n or return 0, "write: $!";
2798  
2799 (1, "$n")
2800 };
2801  
2802 $perl && mcp_tool file_write =>
2803 "Write up to 1 MiB Base64-decoded bytes at offset; no truncation. Returns {bytes: INTEGER} or {error: STRING} on filesystem failure.",
2804 {
2805 type => "object",
2806 properties => {
2807 path => {
2808 type => "string",
2809 },
2810 offset => {
2811 type => "integer",
2812 minimum => 0,
2813 default => 0,
2814 },
2815 data => {
2816 type => "string",
2817 },
2818 workdir => $workdir_schema,
2819 reason => {
2820 type => "string",
2821 description => "Why access needed.",
2822 },
2823 },
2824 required => ["path", "data"],
2825 additionalProperties => JSON::XS::false,
2826 },
2827 3 ▶ sub {
Subroutine __ANON__: called CC=5 SCAR=17.7
2828 3 my ($req, $args) = @_;
2829  
2830 3 my ($workdir, $identity) = fs_workdir $args->{workdir};
2831 3 ▶ my $offset = $args->{offset} // 0;
Condition50%1/2
$args->{"offset"} // 0
l!l
03
MC/DC0%0/1
$args->{"offset"} // 0
$args->{"offset"}
Truth table50%1/2
A
A= $args->{"offset"}
Aresult
11
00
2832 3 my $data = MIME::Base64::decode_base64 $args->{data};
2833 MIME::Base64::encode_base64 ($data, "") eq $args->{data}
2834 3 ▶ or die "invalid base64 data\n";
Branch: 1 branch
BranchTrueFalseTotal
&MIME::Base64::encode_base64($data, "") eq $args->{"data"} or die "invalid base64 data\n" 3 0 3
2835 3 ▶ length $data <= 1048576
Branch: 1 branch
BranchTrueFalseTotal
length $data <= 1048576 or die "write data exceeds 1 MiB\n" 3 0 3
2836 or die "write data exceeds 1 MiB\n";
2837 3 my $path = fs_path $workdir, $args->{path};
2838  
2839 my $granted = fs_require_paths ($req, $workdir, $identity, [$path], "write",
2840 3 ▶ $args->{reason} // "write $path");
Condition50%1/2
$args->{"reason"} // "write $path"
l!l
03
MC/DC0%0/1
$args->{"reason"} // "write $path"
$args->{"reason"}
Truth table50%1/2
A
A= $args->{"reason"}
Aresult
11
00
2841  
2842 3 AE::log debug => join " ", "fs file-write", $path, $offset, length ($data);
2843  
2844 perl_eval $req, $workdir, $granted, $file_write,
2845 2 ▶ [AnyEvent::MCP::utf8enc $path, $offset, $data], 30, sub {
Subroutine __ANON__: called CC=6 SCAR=21.6
2846 2 my ($success, $result) = @_;
2847  
2848 2 ▶ return $req->error ($result)
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 2 2
2849 unless $success;
2850  
2851 2 ▶ @$result == 2
Branch: 1 branch
BranchTrueFalseTotal
@$result == 2 or return $req->error("invalid file-write response\n") 2 0 2
2852 or return $req->error ("invalid file-write response\n");
2853 2 my ($ok, $value) = @$result;
2854 2 ▶ if ($ok eq "1") {
Branch: 2 branches
BranchTrueFalseTotal
if ($ok eq '1') { } 2 0 2
elsif ($ok eq '0') { } 0 0 0
2855 2 ▶ $value =~ /\A[0-9]+\z/
Branch: 1 branch
BranchTrueFalseTotal
$value =~ /\A[0-9]+\z/u or return $req->error("invalid file-write byte count\n") 2 0 2
2856 or return $req->error ("invalid file-write byte count\n");
2857 2 $req->reply (fs_result {
2858 bytes => 0 + $value,
2859 });
2860 } elsif ($ok eq "0") {
2861 0 $req->reply (fs_result {
2862 error => AnyEvent::MCP::utf8dec $value,
2863 });
2864 } else {
2865 0 $req->error ("invalid file-write status\n");
2866 }
2867 3 };
2868 }
2869 4 ▶;
Branch: 1 branch
BranchTrueFalseTotal
$perl and mcp_tool("file_write", "Write up to 1 MiB Base64-decoded bytes at offset; no truncation. Returns {bytes: INTEGER} or {error: STRING} on filesystem failure.", {"type", "object", "properties", {"path", {"type", "string"}, "offset", {"type", "integer", "minimum", 0, "default", 0}, "data", {"type", "string"}, "workdir", $workdir_schema, "reason", {"type", "string", "description", "Why access needed."}}, "required", ["path", "data"], "additionalProperties", &JSON::XS::false()}, sub { my($req, $args) = @_; my($workdir, $identity) = fs_workdir($args->{"workdir"}); my $offset = $args->{"offset"} // 0; my $data = &MIME::Base64::decode_base64($args->{"data"}); &MIME::Base64::encode_base64($data, "") eq $args->{"data"} or die "invalid base64 data\n"; length $data <= 1048576 or die "write data exceeds 1 MiB\n"; my $path = fs_path($workdir, $args->{"path"}); my $granted = fs_require_paths($req, $workdir, $identity, [$path], "write", $args->{"reason"} // "write $path"); &AE::log("debug", join(" ", "fs file-write", $path, $offset, length $data)); perl_eval($req, $workdir, $granted, $file_write, [&AnyEvent::MCP::utf8enc($path), $offset, $data], 30, sub { my($success, $result) = @_; return $req->error($result) unless $success; @$result == 2 or return $req->error("invalid file-write response\n"); my($ok, $value) = @$result; if ($ok eq 1) { $value =~ /\A[0-9]+\z/u or return $req->error("invalid file-write byte count\n"); $req->reply(fs_result({"bytes", 0 + $value})); } elsif ($ok eq 0) { $req->reply(fs_result({"error", &AnyEvent::MCP::utf8dec($value)})); } else { $req->error("invalid file-write status\n"); } ; } ); } ) 4 0 4
2870  
2871 4 my $path_op = q{#perl
2872 while (@ARGV) {
2873 my $op = shift;
2874  
2875 if ($op eq "unlink") {
2876 my $path = shift;
2877  
2878 unlink $path
2879 or die "unlink $path: $!\n";
2880 } elsif ($op eq "rmdir") {
2881 my $path = shift;
2882  
2883 rmdir $path
2884 or die "rmdir $path: $!\n";
2885 } elsif ($op eq "mkdir") {
2886 my ($path, $mode) = splice @ARGV, 0, 2;
2887 $mode = oct $mode;
2888 mkdir $path, $mode
2889 or die "mkdir $path: $!\n";
2890 chmod $mode, $path
2891 or die "chmod $path: $!\n";
2892 } elsif ($op eq "mkpath") {
2893 my ($path, $mode) = splice @ARGV, 0, 2;
2894 $mode = oct $mode;
2895 my $prefix = "";
2896  
2897 for (split m{/}, $path) {
2898 next unless length;
2899 $prefix .= "/$_";
2900 next if -d $prefix;
2901 mkdir $prefix, $mode
2902 or die "mkdir $prefix: $!\n";
2903 chmod $mode, $prefix
2904 or die "chmod $prefix: $!\n";
2905 }
2906 } elsif ($op eq "symlink") {
2907 my ($target, $path) = splice @ARGV, 0, 2;
2908 symlink $target, $path
2909 or die "symlink $path: $!\n";
2910 } elsif ($op eq "truncate") {
2911 my ($path, $size) = splice @ARGV, 0, 2;
2912 truncate $path, $size
2913 or die "truncate $path: $!\n";
2914 } elsif ($op eq "chmod") {
2915 my ($path, $mode) = splice @ARGV, 0, 2;
2916 $mode = oct $mode;
2917 chmod $mode, $path
2918 or die "chmod $path: $!\n";
2919 } elsif ($op eq "rename") {
2920 my ($path, $to) = splice @ARGV, 0, 2;
2921 rename $path, $to
2922 or die "rename $path -> $to: $!\n";
2923 } else {
2924 die "invalid path operation '$op'\n";
2925 }
2926 }
2927  
2928 1
2929 };
2930  
2931 $perl && mcp_tool path_op =>
2932 "Mutate paths in fixed order: unlink, rmdir, mkpath, mkdir, symlink, truncate, chmod, rename. "
2933 . "Stop at first failure; earlier changes remain (no rollback). "
2934 . "mkpath creates missing components in worker; symlink target is link text, not sandbox authority.",
2935 {
2936 type => "object",
2937 properties => {
2938 path => {
2939 type => "string",
2940 },
2941 unlink => {
2942 type => "boolean",
2943 },
2944 rmdir => {
2945 type => "boolean",
2946 },
2947 mkdir => {
2948 description => "Create directory with final mode (ignores umask).",
2949 anyOf => [
2950 { type => "string", pattern => q{^[0-7]+$} },
2951 { type => "integer", minimum => 0 },
2952 ],
2953 },
2954 mkpath => {
2955 description => "Create missing directories with final mode (ignores umask).",
2956 anyOf => [
2957 { type => "string", pattern => q{^[0-7]+$} },
2958 { type => "integer", minimum => 0 },
2959 ],
2960 },
2961 symlink => {
2962 type => "string",
2963 minLength => 1,
2964 description => "Create symlink; value is link target.",
2965 },
2966 truncate => {
2967 type => "integer",
2968 minimum => 0,
2969 },
2970 chmod => {
2971 anyOf => [
2972 { type => "string", pattern => q{^[0-7]+$} },
2973 { type => "integer", minimum => 0 },
2974 ],
2975 },
2976 rename => {
2977 type => "string",
2978 minLength => 1,
2979 description => "Rename destination.",
2980 },
2981 workdir => $workdir_schema,
2982 reason => {
2983 type => "string",
2984 description => "Why access needed.",
2985 },
2986 },
2987 required => ["path"],
2988 additionalProperties => JSON::XS::false,
2989 },
2990 2 ▶ sub {
Subroutine __ANON__: called CC=22 SCAR=35.9
2991 2 my ($req, $args) = @_;
2992  
2993 ($args->{unlink} or $args->{rmdir}
2994 2 ▶ or grep { exists $args->{$_} } qw(mkdir mkpath symlink truncate chmod rename))
Branch: 1 branch
BranchTrueFalseTotal
$args->{"unlink"} or $args->{"rmdir"} or grep {exists $args->{$_};} "mkdir", "mkpath", "symlink", "truncate", "chmod", "rename" or die "no path operation requested\n" 2 0 2
Condition33%2/6
$args->{"unlink"} or $args->{"rmdir"} or grep {exists $args->{$_};} "mkdir", "mkpath", "symlink", "truncate", "chmod", "rename"
l!l&&r!l&&!r
020
$args->{"unlink"} or $args->{"rmdir"}
l!l&&r!l&&!r
002
MC/DC0%0/3
$args->{"unlink"} or $args->{"rmdir"} or grep {exists $args->{$_};} "mkdir", "mkpath", "symlink", "truncate", "chmod", "rename"
$args->{"unlink"} $args->{"rmdir"} grep {exists $args->{$_};} "mkdir", "mkpath", "symlink", "truncate", "chmod", "rename"
Truth table25%1/4
A or B or C
A= $args->{"unlink"}B= $args->{"rmdir"}C= grep {exists $args->{$_};} "mkdir", "mkpath", "symlink", "truncate", "chmod", "rename"
ABCresult
1XX1
01X1
0011
0000
2995 or die "no path operation requested\n";
2996  
2997 2 my ($workdir, $identity) = fs_workdir $args->{workdir};
2998 2 my $path = fs_path $workdir, $args->{path};
2999 my $rename = exists $args->{rename}
3000 ? fs_path $workdir, $args->{rename}
3001 2 ▶ : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $args->{'rename'} ? : 2 0 2
3002 die "mkpath requires a path in the selected workdir\n"
3003 2 ▶ if exists $args->{mkpath} && !fs_inside ($path, $workdir);
Branch: 1 branch
BranchTrueFalseTotal
if exists $args->{"mkpath"} and not fs_inside($path, $workdir) 0 2 2
Condition33%1/3
exists $args->{"mkpath"} and not fs_inside($path, $workdir)
!ll&&!rl&&r
200
MC/DC0%0/2
exists $args->{"mkpath"} and not fs_inside($path, $workdir)
exists $args->{"mkpath"} not fs_inside($path, $workdir)
Truth table33%1/3
A and not(B)
A= exists $args->{"mkpath"}B= not fs_inside($path, $workdir)
ABresult
0X0
100
111
3004  
3005 2 my $json = JSON::XS->new;
3006 my @log = map {
3007 2 ($_ eq "unlink" or $_ eq "rmdir")
3008 ? ($args->{$_} ? $_ : ())
3009 : (exists $args->{$_}
3010 16 ▶ ? "$_: " . $json->encode ($_ eq "rename" ? $rename : $args->{$_}) : ())
Branch: 4 branches
BranchTrueFalseTotal
$_ eq 'unlink' || $_ eq 'rmdir' ? : 4 12 16
$args->{$_} ? : 0 4 4
exists $args->{$_} ? : 2 10 12
$_ eq 'rename' ? : 2 0 2
Condition100%3/3
$_ eq "unlink" or $_ eq "rmdir"
l!l&&r!l&&!r
2212
MC/DC100%2/2
$_ eq "unlink" or $_ eq "rmdir"
$_ eq "unlink" $_ eq "rmdir"
Truth table100%3/3
A or B
A= $_ eq "unlink"B= $_ eq "rmdir"
ABresult
1X1
011
000
3011 } qw(unlink rmdir mkpath mkdir symlink truncate chmod rename);
3012 my $reason = join "\n",
3013 2 ▶ (defined $args->{reason} ? $args->{reason} : ()),
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{'reason'} ? : 0 2 2
3014 "Path: " . $json->encode ($path), "Operations (in order):", map " $_", @log;
3015  
3016 2 ▶ my $granted = fs_require_paths $req, $workdir, $identity,
Branch: 1 branch
BranchTrueFalseTotal
defined $rename ? : 2 0 2
3017 [$path, (defined $rename ? $rename : ())], "write", $reason;
3018  
3019 2 AE::log debug => join " ", "fs path-op", $path, @log;
3020  
3021 2 my @operation;
3022 2 my $raw_path = AnyEvent::MCP::utf8enc $path;
3023  
3024 push @operation, unlink => $raw_path
3025 2 ▶ if $args->{unlink};
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"unlink"} 0 2 2
3026 push @operation, rmdir => $raw_path
3027 2 ▶ if $args->{rmdir};
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"rmdir"} 0 2 2
3028 push @operation, mkpath => $raw_path, $args->{mkpath}
3029 2 ▶ if exists $args->{mkpath};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args->{"mkpath"} 0 2 2
3030 push @operation, mkdir => $raw_path, $args->{mkdir}
3031 2 ▶ if exists $args->{mkdir};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args->{"mkdir"} 0 2 2
3032 push @operation, symlink => (AnyEvent::MCP::utf8enc $args->{symlink}), $raw_path
3033 2 ▶ if exists $args->{symlink};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args->{"symlink"} 0 2 2
3034 push @operation, truncate => $raw_path, $args->{truncate}
3035 2 ▶ if exists $args->{truncate};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args->{"truncate"} 0 2 2
3036 push @operation, chmod => $raw_path, $args->{chmod}
3037 2 ▶ if exists $args->{chmod};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args->{"chmod"} 0 2 2
3038 2 ▶ push @operation, rename => $raw_path, (AnyEvent::MCP::utf8enc $rename)
Branch: 1 branch
BranchTrueFalseTotal
if defined $rename 2 0 2
3039 if defined $rename;
3040  
3041 perl_eval $req, $workdir, $granted, $path_op,
3042 2 ▶ \@operation, 30, sub {
Subroutine __ANON__: called CC=4 SCAR=15.6
3043 2 my ($success, $result) = @_;
3044  
3045 2 ▶ return $req->error ($result)
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 2 2
3046 unless $success;
3047  
3048 2 ▶ @$result == 1 and $result->[0] eq "1"
Branch: 1 branch
BranchTrueFalseTotal
@$result == 1 and $result->[0] eq 1 or return $req->error("invalid path-op response\n") 2 0 2
Condition33%1/3
@$result == 1 and $result->[0] eq 1
!ll&&!rl&&r
002
MC/DC0%0/2
@$result == 1 and $result->[0] eq 1
@$result == 1 $result->[0] eq 1
Truth table33%1/3
A and B
A= @$result == 1B= $result->[0] eq 1
ABresult
0X0
100
111
3049 or return $req->error ("invalid path-op response\n");
3050 2 $req->reply (fs_text_result "ok\n");
3051 2 };
3052 }
3053 4 ▶;
Branch: 1 branch
BranchTrueFalseTotal
$perl and mcp_tool("path_op", "Mutate paths in fixed order: unlink, rmdir, mkpath, mkdir, symlink, truncate, chmod, rename. Stop at first failure; earlier changes remain (no rollback). mkpath creates missing components in worker; symlink target is link text, not sandbox authority.", {"type", "object", "properties", {"path", {"type", "string"}, "unlink", {"type", "boolean"}, "rmdir", {"type", "boolean"}, "mkdir", {"description", "Create directory with final mode (ignores umask).", "anyOf", [{"type", "string", "pattern", "^[0-7]+\$"}, {"type", "integer", "minimum", 0}]}, "mkpath", {"description", "Create missing directories with final mode (ignores umask).", "anyOf", [{"type", "string", "pattern", "^[0-7]+\$"}, {"type", "integer", "minimum", 0}]}, "symlink", {"type", "string", "minLength", 1, "description", "Create symlink; value is link target."}, "truncate", {"type", "integer", "minimum", 0}, "chmod", {"anyOf", [{"type", "string", "pattern", "^[0-7]+\$"}, {"type", "integer", "minimum", 0}]}, "rename", {"type", "string", "minLength", 1, "description", "Rename destination."}, "workdir", $workdir_schema, "reason", {"type", "string", "description", "Why access needed."}}, "required", ["path"], "additionalProperties", &JSON::XS::false()}, sub { my($req, $args) = @_; $args->{"unlink"} or $args->{"rmdir"} or grep {exists $args->{$_};} "mkdir", "mkpath", "symlink", "truncate", "chmod", "rename" or die "no path operation requested\n"; my($workdir, $identity) = fs_workdir($args->{"workdir"}); my $path = fs_path($workdir, $args->{"path"}); my $rename = exists $args->{"rename"} ? fs_path($workdir, $args->{"rename"}) : undef; die "mkpath requires a path in the selected workdir\n" if exists $args->{"mkpath"} and not fs_inside($path, $workdir); my $json = "JSON::XS"->new; my(@log) = map({$_ eq "unlink" || $_ eq "rmdir" ? $args->{$_} ? $_ : () : (exists $args->{$_} ? "${_}: " . $json->encode($_ eq "rename" ? $rename : $args->{$_}) : ());} "unlink", "rmdir", "mkpath", "mkdir", "symlink", "truncate", "chmod", "rename"); my $reason = join("\n", defined $args->{"reason"} ? $args->{"reason"} : (), 'Path: ' . $json->encode($path), "Operations (in order):", map((" $_"), @log)); my $granted = fs_require_paths($req, $workdir, $identity, [$path, defined $rename ? $rename : ()], "write", $reason); &AE::log("debug", join(" ", "fs path-op", $path, @log)); my @operation; my $raw_path = &AnyEvent::MCP::utf8enc($path); push @operation, "unlink", $raw_path if $args->{"unlink"}; push @operation, "rmdir", $raw_path if $args->{"rmdir"}; push @operation, "mkpath", $raw_path, $args->{"mkpath"} if exists $args->{"mkpath"}; push @operation, "mkdir", $raw_path, $args->{"mkdir"} if exists $args->{"mkdir"}; push @operation, "symlink", &AnyEvent::MCP::utf8enc($args->{"symlink"}), $raw_path if exists $args->{"symlink"}; push @operation, "truncate", $raw_path, $args->{"truncate"} if exists $args->{"truncate"}; push @operation, "chmod", $raw_path, $args->{"chmod"} if exists $args->{"chmod"}; push @operation, "rename", $raw_path, &AnyEvent::MCP::utf8enc($rename) if defined $rename; perl_eval($req, $workdir, $granted, $path_op, \@operation, 30, sub { my($success, $result) = @_; return $req->error($result) unless $success; @$result == 1 and $result->[0] eq 1 or return $req->error("invalid path-op response\n"); $req->reply(fs_text_result("ok\n")); } ); } ) 4 0 4
3054  
3055 4 my $file_patch = q{#perl
3056 use Fcntl qw(O_RDWR O_CREAT O_EXCL);
3057 use Errno qw(EEXIST ENAMETOOLONG);
3058  
3059 my ($patch, $path, $diff, @max_offset) = @ARGV;
3060  
3061 my $create_tempfile = sub {
3062 my ($name) = @_;
3063 utf8::decode $name
3064 or return undef, "invalid UTF-8 tempfile name";
3065  
3066 my $slash = rindex $name, "/";
3067 my $dir = $slash < 0 ? "" : substr $name, 0, $slash + 1;
3068 my $file = substr $name, $slash + 1;
3069  
3070 for (;;) {
3071 my $pathname = "$dir$file";
3072 utf8::encode $pathname;
3073  
3074 if (sysopen my $fh, $pathname, O_RDWR | O_CREAT | O_EXCL, 0600) {
3075 binmode $fh;
3076 return $fh, $pathname
3077 }
3078  
3079 if ($! == EEXIST) {
3080 $file .= "~";
3081 } elsif ($! == ENAMETOOLONG) {
3082 substr $file, (length $file) * .75, 2, "~";
3083 } else {
3084 return undef, "open tempfile: $!"
3085 }
3086 }
3087 };
3088  
3089 # deliberately self-contained: patch validation must not load host modules.
3090 my $check_patch_output = sub {
3091 my ($status, $output, @max_offset) = @_;
3092 my (@hunks, @unparsed);
3093  
3094 for (split /\n/, $output) {
3095 if (/^Hunk #(\d+) (succeeded|FAILED|ignored) at (-?\d+)(?: with fuzz (\d+))?(?: \(offset (-?\d+) lines?\))?\.\z/) {
3096 push @hunks, [0 + $1, $2 eq "succeeded", 0 + $4, 0 + $5];
3097 } elsif (!length
3098 || /^Hmm\.\.\. +Looks like a unified diff to me\.\.\.\z/
3099 || /^The text leading up to this was:\z/
3100 || /^-+\z/ || /^\|/
3101 || /^patching file / || /^checking file /
3102 || /^Using Plan [AB]\.\.\.\z/ || /^done\z/) {
3103 # GNU patch --verbose framing.
3104 } else {
3105 push @unparsed, $_;
3106 }
3107 }
3108  
3109 $status == 0
3110 or die "patch failed (wait status $status):\n$output";
3111 @unparsed == 0
3112 or die "patch: unrecognized output:\n" . (join "\n", @unparsed) . "\n";
3113 @hunks == @max_offset && @hunks
3114 or die "patch: expected " . @max_offset . " hunks, got " . @hunks . "\n";
3115  
3116 for my $i (0 .. $#hunks) {
3117 my ($number, $success, $fuzz, $offset) = @{$hunks[$i]};
3118  
3119 $number == $i + 1
3120 or die "patch: unexpected hunk number $number\n";
3121 $success
3122 or die "patch: hunk $number failed\n";
3123 !$fuzz
3124 or die "patch: hunk $number used fuzz $fuzz\n";
3125 abs ($offset) <= $max_offset[$i]
3126 or die "patch: hunk $number offset $offset exceeds $max_offset[$i]\n";
3127 }
3128 };
3129  
3130 my $run_patch = sub {
3131 my ($newname, $path, $diff) = @_;
3132  
3133 my ($errfh, $errname) = $create_tempfile->("/tmp/mcp-fs~~patch~~");
3134 $errfh
3135 or return undef, $errname;
3136  
3137 local $ENV{LC_ALL} = "C";
3138 open my $write, "|-", "sh", "-c",
3139 q{exec "$4" --unified --verbose --binary --batch --forward --get=0 --fuzz=0 --reject-file=- --no-backup-if-mismatch -o "$2" "$1" >"$3" 2>&1},
3140 "--", $path, $newname, $errname, $patch
3141 or return undef, "open patch pipe: $!";
3142  
3143 my $write_error;
3144 {
3145 print $write $diff
3146 or $write_error = "write patch: $!";
3147 close $write;
3148 }
3149  
3150 my $status = $?;
3151  
3152 unlink $errname
3153 or return undef, "unlink patch stderr: $!";
3154 defined sysseek $errfh, 0, 0
3155 or return undef, "seek patch stderr: $!";
3156 my $output = do { local $/; <$errfh> };
3157 $output = "" unless defined $output;
3158 $output =~ s/\s+\z//;
3159  
3160 return undef, $write_error
3161 if $write_error and !$status;
3162  
3163 $status, $output
3164 };
3165  
3166 my $replace_file = sub {
3167 my ($path, $before, $newfh, $newname) = @_;
3168  
3169 chown $before->[4], $before->[5], $newfh;
3170 chmod $before->[2], $newfh;
3171  
3172 my @after = lstat $path;
3173 @after
3174 or return undef, "lstat: $!";
3175 (join "\0", @$before[0, 1, 2, 3, 4, 5, 7, 9, 10])
3176 eq (join "\0", @after[0, 1, 2, 3, 4, 5, 7, 9, 10])
3177 or return undef, "file changed while applying patch";
3178 my @new = stat $newfh;
3179 $after[3] == 1
3180 or return undef, "refusing to replace multiply-linked file";
3181 (join "\0", @after[2, 4, 5]) eq (join "\0", @new[2, 4, 5])
3182 or return undef, "cannot preserve file metadata";
3183  
3184 rename $newname, $path
3185 or return undef, "rename: $!";
3186  
3187 $new[7], undef
3188 };
3189  
3190 my @before = lstat $path;
3191 @before
3192 or return 0, "lstat: $!";
3193 -f _
3194 or return 0, "not a regular file";
3195  
3196 my ($newfh, $newname) = $create_tempfile->("$path~~new~~");
3197 $newfh
3198 or return 0, $newname;
3199  
3200 my ($status, $output) = $run_patch->($newname, $path, $diff);
3201 unless (defined $status) {
3202 unlink $newname;
3203 return 0, $output
3204 }
3205  
3206 unless (eval { $check_patch_output->($status, $output, @max_offset); 1 }) {
3207 my $error = $@;
3208 unlink $newname;
3209 return 0, $error
3210 }
3211  
3212 my ($bytes, $error) = $replace_file->($path, \@before, $newfh, $newname);
3213 unlink $newname unless defined $bytes;
3214 defined $bytes
3215 ? (1, "$bytes")
3216 : (0, $error)
3217 };
3218  
3219 $perl && $patch && mcp_tool file_patch =>
3220 "Patch one regular file via unified diff. Recompute hunk counts; no fuzz. "
3221 . "Whole-hunk relocation bounded per hunk by distinct old-side lines. "
3222 . "Pure insertion only at file start; elsewhere include old-side context. "
3223 . "diff: Unicode text (encoded UTF-8) "
3224 . "or Base64 raw bytes; autodetect by @ hunk markers ("
3225 . "Base64 cannot contain @).",
3226 {
3227 type => "object",
3228 properties => {
3229 path => { type => "string" },
3230 diff => { type => "string", minLength => 1 },
3231 workdir => $workdir_schema,
3232 reason => {
3233 type => "string",
3234 description => "Why access needed.",
3235 },
3236 },
3237 required => ["path", "diff"],
3238 additionalProperties => JSON::XS::false,
3239 },
3240 0 ▶ sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
3241 0 my ($req, $args) = @_;
3242  
3243 0 my ($workdir, $identity) = fs_workdir $args->{workdir};
3244 0 my $path = fs_path $workdir, $args->{path};
3245 0 my $diff = $args->{diff};
3246 0 my $detail = $diff;
3247  
3248 0 ▶ if ((index $diff, "@") >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($diff, '@') != -1) { } 0 0 0
3249 0 $diff = AnyEvent::MCP::utf8enc $diff;
3250 } else {
3251 0 my $bytes = MIME::Base64::decode_base64 $diff;
3252 0 ▶ MIME::Base64::encode_base64 ($bytes, "") eq $diff
Branch: 1 branch
BranchTrueFalseTotal
&MIME::Base64::encode_base64($bytes, "") eq $diff or die "invalid base64 diff\n" 0 0 0
3253 or die "invalid base64 diff\n";
3254 0 $diff = $bytes;
3255 0 $detail = eval { AnyEvent::MCP::utf8dec $bytes };
3256  
3257 0 ▶ unless (defined $detail) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $detail) 0 0 0
3258 0 $detail = $bytes;
3259 0 $detail =~ s/([^\x09\x0a\x20-\x5b\x5d-\x7e])/sprintf "\\x{%02X}", ord $1/ge;
3260 0 $detail = "Raw patch: " . length ($bytes) . " bytes (escaped byte view)\n\n" . $detail;
3261 }
3262 }
3263  
3264 0 my $max_offset;
3265 0 ($diff, $max_offset) = AnyEvent::MCP::normalize_udiff $diff;
3266 0 ▶ length $diff <= 4<<20
Branch: 1 branch
BranchTrueFalseTotal
length $diff <= 4194304 or die "patch exceeds 4 MiB\n" 0 0 0
3267 or die "patch exceeds 4 MiB\n";
3268  
3269 my $granted = fs_require_paths ($req, $workdir, $identity, [$path], "write",
3270 0 ▶ $args->{reason} // "patch $path", { "View patch" => "File: $path\n\n$detail" });
Condition0%0/2
$args->{"reason"} // "patch $path"
l!l
00
MC/DC0%0/1
$args->{"reason"} // "patch $path"
$args->{"reason"}
Truth table0%0/2
A
A= $args->{"reason"}
Aresult
11
00
3271  
3272 0 AE::log debug => join " ", "fs file-patch", $path, scalar (@$max_offset), "hunks", length ($diff), "bytes";
3273  
3274 perl_eval $req, $workdir, $granted, $file_patch,
3275 0 ▶ [$patch, AnyEvent::MCP::utf8enc $path, $diff, @$max_offset], 30, sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
3276 0 my ($success, $result) = @_;
3277  
3278 0 ▶ return $req->error ($result)
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 0 0
3279 unless $success;
3280  
3281 0 ▶ @$result == 2
Branch: 1 branch
BranchTrueFalseTotal
@$result == 2 or return $req->error("invalid file-patch response\n") 0 0 0
3282 or return $req->error ("invalid file-patch response\n");
3283 0 my ($ok, $value) = @$result;
3284  
3285 0 ▶ if ($ok eq "1") {
Branch: 2 branches
BranchTrueFalseTotal
if ($ok eq '1') { } 0 0 0
elsif ($ok eq '0') { } 0 0 0
3286 0 ▶ $value =~ /\A[0-9]+\z/
Branch: 1 branch
BranchTrueFalseTotal
$value =~ /\A[0-9]+\z/u or return $req->error("invalid file-patch byte count\n") 0 0 0
3287 or return $req->error ("invalid file-patch byte count\n");
3288 0 $req->reply (fs_result {
3289 bytes => 0 + $value,
3290 });
3291 } elsif ($ok eq "0") {
3292 0 $req->reply (fs_result {
3293 error => AnyEvent::MCP::utf8dec $value,
3294 });
3295 } else {
3296 0 $req->error ("invalid file-patch status\n");
3297 }
3298 0 };
3299 }
3300 4 ▶;
Branch: 1 branch
BranchTrueFalseTotal
$perl and $patch and mcp_tool("file_patch", "Patch one regular file via unified diff. Recompute hunk counts; no fuzz. Whole-hunk relocation bounded per hunk by distinct old-side lines. Pure insertion only at file start; elsewhere include old-side context. diff: Unicode text (encoded UTF-8) or Base64 raw bytes; autodetect by \@ hunk markers (Base64 cannot contain \@).", {"type", "object", "properties", {"path", {"type", "string"}, "diff", {"type", "string", "minLength", 1}, "workdir", $workdir_schema, "reason", {"type", "string", "description", "Why access needed."}}, "required", ["path", "diff"], "additionalProperties", &JSON::XS::false()}, sub { my($req, $args) = @_; my($workdir, $identity) = fs_workdir($args->{"workdir"}); my $path = fs_path($workdir, $args->{"path"}); my $diff = $args->{"diff"}; my $detail = $diff; if (index($diff, "\@") != -1) { $diff = &AnyEvent::MCP::utf8enc($diff); } else { my $bytes = &MIME::Base64::decode_base64($diff); &MIME::Base64::encode_base64($bytes, "") eq $diff or die "invalid base64 diff\n"; $diff = $bytes; $detail = eval { do { &AnyEvent::MCP::utf8dec($bytes) } }; unless (defined $detail) { $detail = $bytes; $detail =~ s/([^\x09\x0a\x20-\x5b\x5d-\x7e])/sprintf "\\x{%02X}", ord $1;/egu; $detail = 'Raw patch: ' . length($bytes) . " bytes (escaped byte view)\n\n" . $detail; } ; } ; my $max_offset; ($diff, $max_offset) = AnyEvent::MCP::normalize_udiff($diff); length $diff <= 4194304 or die "patch exceeds 4 MiB\n"; my $granted = fs_require_paths($req, $workdir, $identity, [$path], "write", $args->{"reason"} // "patch $path", {"View patch", "File: $path\n\n$detail"}); &AE::log("debug", join(" ", "fs file-patch", $path, scalar @$max_offset, "hunks", length $diff, "bytes")); perl_eval($req, $workdir, $granted, $file_patch, [$patch, &AnyEvent::MCP::utf8enc($path), $diff, @$max_offset], 30, sub { my($success, $result) = @_; return $req->error($result) unless $success; @$result == 2 or return $req->error("invalid file-patch response\n"); my($ok, $value) = @$result; if ($ok eq 1) { $value =~ /\A[0-9]+\z/u or return $req->error("invalid file-patch byte count\n"); $req->reply(fs_result({"bytes", 0 + $value})); } elsif ($ok eq 0) { $req->reply(fs_result({"error", &AnyEvent::MCP::utf8dec($value)})); } else { $req->error("invalid file-patch status\n"); } ; } ); } ) 0 4 4
Condition33%1/3
$perl and $patch
!ll&&!rl&&r
040
MC/DC0%0/2
$perl and $patch
$perl $patch
Truth table33%1/3
A and B
A= $perlB= $patch
ABresult
0X0
100
111
3301  
3302 $find && $grep && mcp_tool grep =>
3303 "Search regular files up to 1 MiB recursively; skip symlinks and .git. "
3304 . "Literal match default; mode=pcre uses GNU grep -P. "
3305 . "Stop at limit; report truncation and timeout separately.",
3306 {
3307 type => "object",
3308 properties => {
3309 path => {
3310 type => "string",
3311 description => "Search root; omitted/empty = .",
3312 },
3313 pattern => {
3314 type => "string",
3315 minLength => 1,
3316 },
3317 mode => {
3318 type => "string",
3319 enum => ["fixed", "pcre"],
3320 default => "fixed",
3321 },
3322 limit => {
3323 type => "integer",
3324 minimum => 1,
3325 maximum => 1000,
3326 default => 200,
3327 description => "Max matching lines.",
3328 },
3329 workdir => $workdir_schema,
3330 reason => {
3331 type => "string",
3332 description => "Why access needed.",
3333 },
3334 },
3335 required => ["pattern"],
3336 additionalProperties => JSON::XS::false,
3337 },
3338 0 ▶ sub {
Subroutine __ANON__: not called CC=9 SCAR=45.0
3339 0 my ($req, $args) = @_;
3340  
3341 0 my ($workdir, $identity) = fs_workdir $args->{workdir};
3342 0 ▶ my $path = fs_path $workdir, length $args->{path} ? $args->{path} : ".";
Branch: 1 branch
BranchTrueFalseTotal
length $args->{'path'} ? : 0 0 0
3343 0 ▶ my $mode = $args->{mode} // "fixed";
Condition0%0/2
$args->{"mode"} // "fixed"
l!l
00
MC/DC0%0/1
$args->{"mode"} // "fixed"
$args->{"mode"}
Truth table0%0/2
A
A= $args->{"mode"}
Aresult
11
00
3344 0 ▶ $mode eq "fixed" or $mode eq "pcre"
Branch: 1 branch
BranchTrueFalseTotal
$mode eq "fixed" or $mode eq "pcre" or die "invalid grep mode\n" 0 0 0
Condition0%0/3
$mode eq "fixed" or $mode eq "pcre"
l!l&&r!l&&!r
000
MC/DC0%0/2
$mode eq "fixed" or $mode eq "pcre"
$mode eq "fixed" $mode eq "pcre"
Truth table0%0/3
A or B
A= $mode eq "fixed"B= $mode eq "pcre"
ABresult
1X1
011
000
3345 or die "invalid grep mode\n";
3346 0 ▶ my $limit = $args->{limit} // 200;
Condition0%0/2
$args->{"limit"} // 200
l!l
00
MC/DC0%0/1
$args->{"limit"} // 200
$args->{"limit"}
Truth table0%0/2
A
A= $args->{"limit"}
Aresult
11
00
3347 0 ▶ $limit <= 1000
Branch: 1 branch
BranchTrueFalseTotal
$limit <= 1000 or die "invalid limit\n" 0 0 0
3348 or die "invalid limit\n";
3349 my $granted = fs_require_paths ($req, $workdir, $identity, [$path], "read",
3350 0 ▶ $args->{reason} // "grep $path");
Condition0%0/2
$args->{"reason"} // "grep $path"
l!l
00
MC/DC0%0/1
$args->{"reason"} // "grep $path"
$args->{"reason"}
Truth table0%0/2
A
A= $args->{"reason"}
Aresult
11
00
3351  
3352 0 AE::log debug => join " ", "fs grep", $path, $mode, (substr $args->{pattern}, 0, 40);
3353  
3354 0 my $find_path = AnyEvent::MCP::utf8enc $path;
3355 0 my $pattern = AnyEvent::MCP::utf8enc $args->{pattern};
3356 0 ▶ my @command = (
Branch: 1 branch
BranchTrueFalseTotal
$mode eq 'pcre' ? : 0 0 0
3357 (fs_sandbox $workdir, $granted),
3358 $find, $find_path,
3359 "-name", ".git", "-prune", "-o",
3360 "-type", "f",
3361 "-size", "-1048577c",
3362 "-exec",
3363 # GNU find treats any nonzero -exec ... + batch as failure.
3364 # grep uses 1 for no matches, which is a successful empty search;
3365 # preserve all other errors (including find traversal failures).
3366 "/bin/sh", "-c", q{"$@" || [ "$?" -eq 1 ]}, "sh",
3367 $grep, ($mode eq "pcre" ? "-P" : "-F"),
3368 "-I", "-H", "-n", "--color=never", "-e", $pattern,
3369 "{}", "+",
3370 );
3371  
3372 0 ▶ fs_run $req, \@command, "", 30, 1024 * 1024, $limit, sub {
Subroutine __ANON__: not called CC=7 SCAR=40.3
3373 0 my ($success, $result) = @_;
3374  
3375 0 ▶ return $req->error ($result)
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 0 0
3376 unless $success;
3377  
3378 0 my $response;
3379 0 my $ok = eval {
3380 0 my $stdout = AnyEvent::MCP::utf8dec $result->{stdout};
3381 0 my $stderr = AnyEvent::MCP::utf8dec $result->{stderr};
3382  
3383 0 ▶ if (($result->{exit} or $result->{signal})
Branch: 1 branch
BranchTrueFalseTotal
if ($result->{"exit"} || $result->{"signal"} and not $result->{"truncated"} and not $result->{"timed_out"}) 0 0 0
Condition0%0/9
$result->{"exit"} || $result->{"signal"} and not $result->{"truncated"} and not $result->{"timed_out"}
!ll&&!rl&&r
000
$result->{"exit"} || $result->{"signal"} and not $result->{"truncated"}
!ll&&!rl&&r
000
$result->{"exit"} or $result->{"signal"}
l!l&&r!l&&!r
000
MC/DC0%0/4
$result->{"exit"} || $result->{"signal"} and not $result->{"truncated"} and not $result->{"timed_out"}
$result->{"exit"} $result->{"signal"} not $result->{"truncated"} not $result->{"timed_out"}
Truth table0%0/7
A or B and not(C) and not(D)
A= $result->{"exit"}B= $result->{"signal"}C= not $result->{"truncated"}D= not $result->{"timed_out"}
ABCDresult
00XX0
1X0X0
010X0
1X100
01100
1X111
01111
3384 and !$result->{truncated} and !$result->{timed_out}) {
3385 0 die "grep failed (exit $result->{exit}, signal $result->{signal}): $stderr\n";
3386 }
3387  
3388 $response = {
3389 stdout => $stdout,
3390 stderr => $stderr,
3391 timed_out => $result->{timed_out},
3392 truncated => $result->{truncated},
3393 0 };
3394 0 1
3395 };
3396 0 ▶ return $req->error ($@)
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
3397 unless $ok;
3398  
3399 0 $req->reply (fs_result $response);
3400 0 };
3401 }
3402 4 ▶;
Branch: 1 branch
BranchTrueFalseTotal
$find and $grep and mcp_tool("grep", "Search regular files up to 1 MiB recursively; skip symlinks and .git. Literal match default; mode=pcre uses GNU grep -P. Stop at limit; report truncation and timeout separately.", {"type", "object", "properties", {"path", {"type", "string", "description", "Search root; omitted/empty = ."}, "pattern", {"type", "string", "minLength", 1}, "mode", {"type", "string", "enum", ["fixed", "pcre"], "default", "fixed"}, "limit", {"type", "integer", "minimum", 1, "maximum", 1000, "default", 200, "description", "Max matching lines."}, "workdir", $workdir_schema, "reason", {"type", "string", "description", "Why access needed."}}, "required", ["pattern"], "additionalProperties", &JSON::XS::false()}, sub { my($req, $args) = @_; my($workdir, $identity) = fs_workdir($args->{"workdir"}); my $path = fs_path($workdir, length $args->{"path"} ? $args->{"path"} : "."); my $mode = $args->{"mode"} // "fixed"; $mode eq "fixed" or $mode eq "pcre" or die "invalid grep mode\n"; my $limit = $args->{"limit"} // 200; $limit <= 1000 or die "invalid limit\n"; my $granted = fs_require_paths($req, $workdir, $identity, [$path], "read", $args->{"reason"} // "grep $path"); &AE::log("debug", join(" ", "fs grep", $path, $mode, substr($args->{"pattern"}, 0, 40))); my $find_path = &AnyEvent::MCP::utf8enc($path); my $pattern = &AnyEvent::MCP::utf8enc($args->{"pattern"}); my(@command) = (fs_sandbox($workdir, $granted), $find, $find_path, "-name", ".git", "-prune", "-o", "-type", "f", "-size", "-1048577c", "-exec", "/bin/sh", "-c", "\"\$\@\" || [ \"\$?\" -eq 1 ]", "sh", $grep, $mode eq "pcre" ? "-P" : "-F", "-I", "-H", "-n", "--color=never", "-e", $pattern, "{}", "+"); fs_run($req, \@command, "", 30, 1048576, $limit, sub { my($success, $result) = @_; return $req->error($result) unless $success; my $response; my $ok = eval { do { my $stdout = &AnyEvent::MCP::utf8dec($result->{"stdout"}); my $stderr = &AnyEvent::MCP::utf8dec($result->{"stderr"}); if ($result->{"exit"} || $result->{"signal"} and not $result->{"truncated"} and not $result->{"timed_out"}) { die qq[grep failed (exit $result->{"exit"}, signal $result->{"signal"}): $stderr\n]; } ; $response = {"stdout", $stdout, "stderr", $stderr, "timed_out", $result->{"timed_out"}, "truncated", $result->{"truncated"}}; 1 } }; return $req->error($@) unless $ok; $req->reply(fs_result($response)); } ); } ) 4 0 4
Condition33%1/3
$find and $grep
!ll&&!rl&&r
004
MC/DC0%0/2
$find and $grep
$find $grep
Truth table33%1/3
A and B
A= $findB= $grep
ABresult
0X0
100
111
3403  
3404 4 my $stat = q{#perl
3405 map {
3406 my @s = lstat $_;
3407  
3408 pack "(w/a*)*", (@s
3409 ? (1, (-l _ ? "link" : -d _ ? "directory" : -f _ ? "file" : "other"), @s)
3410 : (0, "lstat: $!"))
3411 } @ARGV
3412 };
3413  
3414 $perl && mcp_tool stat =>
3415 "lstat up to 100 paths; no symlink following.",
3416 {
3417 type => "object",
3418 properties => {
3419 paths => {
3420 type => "array",
3421 items => {
3422 type => "string",
3423 },
3424 minItems => 1,
3425 maxItems => 100,
3426 },
3427 workdir => $workdir_schema,
3428 reason => {
3429 type => "string",
3430 description => "Why access needed.",
3431 },
3432 },
3433 required => ["paths"],
3434 additionalProperties => JSON::XS::false,
3435 },
3436 2 ▶ sub {
Subroutine __ANON__: called CC=6 SCAR=18.8
3437 2 my ($req, $args) = @_;
3438  
3439 2 my ($workdir, $identity) = fs_workdir $args->{workdir};
3440 2 ▶ ARRAY:: eq ref $args->{paths} and @{$args->{paths}} and @{$args->{paths}} <= 100
Branch: 1 branch
BranchTrueFalseTotal
"ARRAY" eq ref $args->{"paths"} and @{$args->{"paths"};} and @{$args->{"paths"};} <= 100 or die "stat needs 1..100 paths\n" 2 0 2
Condition33%2/6
"ARRAY" eq ref $args->{"paths"} and @{$args->{"paths"};} and @{$args->{"paths"};} <= 100
!ll&&!rl&&r
002
"ARRAY" eq ref $args->{"paths"} and @{$args->{"paths"};}
!ll&&!rl&&r
002
MC/DC0%0/3
"ARRAY" eq ref $args->{"paths"} and @{$args->{"paths"};} and @{$args->{"paths"};} <= 100
"ARRAY" eq ref $args->{"paths"} @{$args->{"paths"};} @{$args->{"paths"};} <= 100
Truth table25%1/4
A and B and C
A= "ARRAY" eq ref $args->{"paths"}B= @{$args->{"paths"};}C= @{$args->{"paths"};} <= 100
ABCresult
0XX0
10X0
1100
1111
3441 or die "stat needs 1..100 paths\n";
3442 2 my @paths = map { fs_path $workdir, $_ } @{$args->{paths}};
3443 die "stat paths must be inside the selected workdir\n"
3444 2 ▶ if grep { !fs_inside ($_, $workdir) } @paths;
Branch: 1 branch
BranchTrueFalseTotal
if grep {not fs_inside($_, $workdir);} @paths 0 2 2
3445  
3446 2 my $granted = fs_require_paths $req, $workdir, $identity, \@paths, "read", $args->{reason};
3447  
3448 2 my @log = @paths;
3449 2 ▶ splice @log, 3, @log - 3, "..." if @log > 3;
Branch: 1 branch
BranchTrueFalseTotal
if @log > 3 0 2 2
3450 2 AE::log debug => join " ", "fs stat", @log;
3451  
3452 2 perl_eval $req, $workdir, $granted, $stat, [map { AnyEvent::MCP::utf8enc $_ } @paths],
3453 2 ▶ 30, sub {
Subroutine __ANON__: called CC=5 SCAR=16.7
3454 2 my ($success, $result) = @_;
3455  
3456 2 ▶ return $req->error ($result)
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 2 2
3457 unless $success;
3458  
3459 2 ▶ @$result == @paths
Branch: 1 branch
BranchTrueFalseTotal
@$result == @paths or return $req->error("invalid stat response\n") 2 0 2
3460 or return $req->error ("invalid stat response\n");
3461  
3462 2 my @result;
3463 2 for my $i (0 .. $#paths) {
3464 2 my ($ok, @s) = unpack "(w/a*)*", $result->[$i];
3465  
3466 2 ▶ if ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ok) { } 2 0 2
3467 2 my $type = shift @s;
3468 2 push @result, +{
3469 path => $paths[$i],
3470 type => $type,
3471 size => 0 + $s[7],
3472 mode => (sprintf "%04o", $s[2] & 07777),
3473 uid => 0 + $s[4],
3474 gid => 0 + $s[5],
3475 mtime => 0 + $s[9],
3476 };
3477 } else {
3478 0 push @result, +{
3479 path => $paths[$i],
3480 error => AnyEvent::MCP::utf8dec $s[0],
3481 };
3482 }
3483 }
3484  
3485 2 $req->reply (fs_result { result => \@result });
3486 2 };
3487 }
3488 4 ▶;
Branch: 1 branch
BranchTrueFalseTotal
$perl and mcp_tool("stat", "lstat up to 100 paths; no symlink following.", {"type", "object", "properties", {"paths", {"type", "array", "items", {"type", "string"}, "minItems", 1, "maxItems", 100}, "workdir", $workdir_schema, "reason", {"type", "string", "description", "Why access needed."}}, "required", ["paths"], "additionalProperties", &JSON::XS::false()}, sub { my($req, $args) = @_; my($workdir, $identity) = fs_workdir($args->{"workdir"}); "ARRAY" eq ref $args->{"paths"} and @{$args->{"paths"};} and @{$args->{"paths"};} <= 100 or die "stat needs 1..100 paths\n"; my(@paths) = map({fs_path($workdir, $_);} @{$$args{"paths"};}); die "stat paths must be inside the selected workdir\n" if grep {not fs_inside($_, $workdir);} @paths; my $granted = fs_require_paths($req, $workdir, $identity, \@paths, "read", $args->{"reason"}); my(@log) = @paths; splice @log, 3, @log - 3, "..." if @log > 3; &AE::log("debug", join(" ", "fs stat", @log)); perl_eval($req, $workdir, $granted, $stat, [map({&AnyEvent::MCP::utf8enc($_);} @paths)], 30, sub { my($success, $result) = @_; return $req->error($result) unless $success; @$result == @paths or return $req->error("invalid stat response\n"); my @result; foreach my $i (0 .. $#paths) { my($ok, @s) = unpack("(w/a*)*", $result->[$i]); if ($ok) { my $type = shift @s; push @result, {"path", $paths[$i], "type", $type, "size", 0 + $s[7], "mode", sprintf("%04o", $s[2] & 4095), "uid", 0 + $s[4], "gid", 0 + $s[5], "mtime", 0 + $s[9]}; } else { push @result, {"path", $paths[$i], "error", &AnyEvent::MCP::utf8dec($s[0])}; } ; } ; $req->reply(fs_result({"result", \@result})); } ); } ) 4 0 4
3489  
3490 mcp_tool exec =>
3491 "Run argv " . ($bwrap ? "in bubblewrap. " : "UNSANDBOXED with full host-user privileges. ")
3492 . ($bwrap ? "Private /tmp by default (gone after exec); use for temp files/IPC. shared-tmp exposes HOST /tmp (sockets/services). Request ONLY for HOST /tmp, NOT ordinary temp/IPC. " : "")
3493 . "stdin_encoding: utf-8 (default), latin1 or base64; max 4 MiB decoded. "
3494 . "stdout/stderr UTF-8, captured to 1 MiB each; max_lines/max_bytes bound response. Optional grep: PCRE stdout filter after capture; stderr unfiltered. Reports capture truncation. "
3495 . "Explicit sandbox_grants replace default workdir-read. Exit/signal/timeout are normal results, not tool errors. No command-prefix safety classification. Timeout >300 s requires "
3496 . "long-running grant; max six hours.",
3497 {
3498 type => "object",
3499 properties => {
3500 %output_schema,
3501 workdir => $workdir_schema,
3502 argv => {
3503 type => "array",
3504 items => { type => "string" },
3505 minItems => 1,
3506 },
3507 sandbox_grants => {
3508 type => "array",
3509 description => "Providing sandbox_grants (even []) replaces this default entirely; otherwise workdir-read under bubblewrap. Without bubblewrap: full host authority. host-proc unavailable under bubblewrap.",
3510 items => {
3511 type => "string",
3512 enum => [sort keys %sandbox_grant],
3513 },
3514 },
3515 reason => {
3516 type => "string",
3517 description => "Why command needs authority.",
3518 },
3519 stdin => { type => "string" },
3520 stdin_encoding => {
3521 type => "string",
3522 default => "utf-8",
3523 enum => [qw(utf-8 latin1 base64)],
3524 description => "stdin bytes: UTF-8 (default), Latin-1 code points U+0000..U+00FF, or canonical Base64; max 4 MiB decoded.",
3525 },
3526 timeout => {
3527 type => "integer",
3528 minimum => 1,
3529 maximum => 21600,
3530 default => 30,
3531 description => "Timeout seconds; >300 also requires long-running grant.",
3532 },
3533 },
3534 required => [qw(argv reason)],
3535 additionalProperties => JSON::XS::false,
3536 },
3537 2 ▶ sub {
Subroutine __ANON__: called CC=34 SCAR=49.6
3538 2 my ($req, $args) = @_;
3539  
3540 2 my $output = fs_output_options $args;
3541  
3542 2 ▶ ARRAY:: eq ref $args->{argv} and @{$args->{argv}}
Branch: 1 branch
BranchTrueFalseTotal
"ARRAY" eq ref $args->{"argv"} and @{$args->{"argv"};} or die "exec needs argv strings without NUL\n" 2 0 2
Condition33%1/3
"ARRAY" eq ref $args->{"argv"} and @{$args->{"argv"};}
!ll&&!rl&&r
002
MC/DC0%0/2
"ARRAY" eq ref $args->{"argv"} and @{$args->{"argv"};}
"ARRAY" eq ref $args->{"argv"} @{$args->{"argv"};}
Truth table33%1/3
A and B
A= "ARRAY" eq ref $args->{"argv"}B= @{$args->{"argv"};}
ABresult
0X0
100
111
3543 or die "exec needs argv strings without NUL\n";
3544 2 for my $arg (@{$args->{argv}}) {
3545 6 ▶ defined $arg and !ref $arg and $arg !~ /\0/
Branch: 1 branch
BranchTrueFalseTotal
defined $arg and not ref $arg and not $arg =~ /\0/u or die "exec needs argv strings without NUL\n" 6 0 6
Condition33%2/6
defined $arg and not ref $arg and not $arg =~ /\0/u
!ll&&!rl&&r
006
defined $arg and not ref $arg
!ll&&!rl&&r
006
MC/DC0%0/3
defined $arg and not ref $arg and not $arg =~ /\0/u
defined $arg not ref $arg not $arg =~ /\0/u
Truth table25%1/4
A and not(B) and not(C)
A= defined $argB= not ref $argC= not $arg =~ /\0/u
ABCresult
0XX0
10X0
1100
1111
3546 or die "exec needs argv strings without NUL\n";
3547 }
3548 2 ▶ length $args->{argv}[0] or die "exec needs an executable\n";
Branch: 1 branch
BranchTrueFalseTotal
length $args->{"argv"}[0] or die "exec needs an executable\n" 2 0 2
3549  
3550 2 my ($workdir, $identity) = fs_workdir $args->{workdir};
3551 2 ▶ my $timeout = $args->{timeout} // 30;
Condition50%1/2
$args->{"timeout"} // 30
l!l
02
MC/DC0%0/1
$args->{"timeout"} // 30
$args->{"timeout"}
Truth table50%1/2
A
A= $args->{"timeout"}
Aresult
11
00
3552 2 ▶ $timeout >= 1 && $timeout <= 21600 && $timeout == int $timeout
Branch: 1 branch
BranchTrueFalseTotal
$timeout >= 1 and $timeout <= 21600 and $timeout == int $timeout or die "invalid timeout\n" 2 0 2
Condition33%2/6
$timeout >= 1 and $timeout <= 21600 and $timeout == int $timeout
!ll&&!rl&&r
002
$timeout >= 1 and $timeout <= 21600
!ll&&!rl&&r
002
MC/DC0%0/3
$timeout >= 1 and $timeout <= 21600 and $timeout == int $timeout
$timeout >= 1 $timeout <= 21600 $timeout == int $timeout
Truth table25%1/4
A and B and C
A= $timeout >= 1B= $timeout <= 21600C= $timeout == int $timeout
ABCresult
0XX0
10X0
1100
1111
3553 or die "invalid timeout\n";
3554  
3555 0 ▶ my $sandbox_grants = [exists $args->{sandbox_grants} ? @{$args->{sandbox_grants}} : @exec_default_sandbox_grants];
Branch: 1 branch
BranchTrueFalseTotal
exists $args->{'sandbox_grants'} ? : 0 2 2
3556 2 ▶ push @$sandbox_grants, "long-running" if $timeout > 300;
Branch: 1 branch
BranchTrueFalseTotal
if $timeout > 300 0 2 2
3557 2 $sandbox_grants = [fs_effective_grants @$sandbox_grants];
3558 2 my $requested = $permissions->closure ($sandbox_grants);
3559 die "host-proc sandbox authority is unresolved and unavailable in v1\n"
3560 2 ▶ if $bwrap && $requested->{"host-proc"};
Branch: 1 branch
BranchTrueFalseTotal
if $bwrap and $requested->{"host-proc"} 0 2 2
Condition33%1/3
$bwrap and $requested->{"host-proc"}
!ll&&!rl&&r
200
MC/DC0%0/2
$bwrap and $requested->{"host-proc"}
$bwrap $requested->{"host-proc"}
Truth table33%1/3
A and B
A= $bwrapB= $requested->{"host-proc"}
ABresult
0X0
100
111
3561  
3562 2 ▶ my $stdin_text = $args->{stdin} // "";
Condition50%1/2
$args->{"stdin"} // ""
l!l
20
MC/DC0%0/1
$args->{"stdin"} // ""
$args->{"stdin"}
Truth table50%1/2
A
A= $args->{"stdin"}
Aresult
11
00
3563 2 ▶ my $stdin_encoding = $args->{stdin_encoding} // "utf-8";
Condition50%1/2
$args->{"stdin_encoding"} // "utf-8"
l!l
02
MC/DC0%0/1
$args->{"stdin_encoding"} // "utf-8"
$args->{"stdin_encoding"}
Truth table50%1/2
A
A= $args->{"stdin_encoding"}
Aresult
11
00
3564 2 ▶ $stdin_encoding =~ /\A(?:utf-8|latin1|base64)\z/
Branch: 1 branch
BranchTrueFalseTotal
$stdin_encoding =~ /\A(?:utf-8|latin1|base64)\z/u or die "invalid stdin_encoding\n" 2 0 2
3565 or die "invalid stdin_encoding\n";
3566 2 my $input;
3567 2 ▶ if ($stdin_encoding eq "utf-8") {
Branch: 2 branches
BranchTrueFalseTotal
if ($stdin_encoding eq 'utf-8') { } 2 0 2
elsif ($stdin_encoding eq 'latin1') { } 0 0 0
3568 2 $input = AnyEvent::MCP::utf8enc $stdin_text;
3569 } elsif ($stdin_encoding eq "latin1") {
3570 0 ▶ $stdin_text !~ /[^\x00-\xff]/
Branch: 1 branch
BranchTrueFalseTotal
$stdin_text =~ /[^\x00-\xff]/u and die "latin1 stdin contains code points above U+00FF\n" 0 0 0
3571 or die "latin1 stdin contains code points above U+00FF\n";
3572 0 $input = pack "C*", unpack "U*", $stdin_text;
3573 } else {
3574 0 $input = MIME::Base64::decode_base64 $stdin_text;
3575 0 ▶ MIME::Base64::encode_base64 ($input, "") eq $stdin_text
Branch: 1 branch
BranchTrueFalseTotal
&MIME::Base64::encode_base64($input, "") eq $stdin_text or die "invalid base64 stdin\n" 0 0 0
3576 or die "invalid base64 stdin\n";
3577 }
3578 2 ▶ length $input <= 4 * 1024 * 1024 or die "stdin exceeds 4 MiB\n";
Branch: 1 branch
BranchTrueFalseTotal
length $input <= 4194304 or die "stdin exceeds 4 MiB\n" 2 0 2
3579 2 my $stdin_detail = $stdin_text;
3580 2 ▶ if (length $input && $stdin_encoding ne "utf-8") {
Branch: 1 branch
BranchTrueFalseTotal
if (length $input and $stdin_encoding ne "utf-8") 0 2 2
Condition33%1/3
length $input and $stdin_encoding ne "utf-8"
!ll&&!rl&&r
020
MC/DC0%0/2
length $input and $stdin_encoding ne "utf-8"
length $input $stdin_encoding ne "utf-8"
Truth table33%1/3
A and B
A= length $inputB= $stdin_encoding ne "utf-8"
ABresult
0X0
100
111
3581 0 my $preview = substr $input, 0, 4096;
3582 0 $preview =~ s/([^\x20-\x5b\x5d-\x7e])/sprintf "\\x{%02X}", ord $1/ge;
3583 0 $stdin_detail = "$stdin_encoding stdin: " . length ($input) . " bytes (escaped preview)\n\n" . $preview;
3584 0 ▶ $stdin_detail .= "\n... (preview limited to 4096 bytes)"
Branch: 1 branch
BranchTrueFalseTotal
if length $input > 4096 0 0 0
3585 if length $input > 4096;
3586 }
3587  
3588 2 my $coder = JSON::XS->new->canonical;
3589 2 my $subject = $coder->encode ($args->{argv});
3590 2 my $executable = $coder->encode ($args->{argv}[0]);
3591 2 ▶ my $command_label = length $subject > 100 ? substr ($subject, 0, 97) . "..." : $subject;
Branch: 1 branch
BranchTrueFalseTotal
length $subject > 100 ? : 0 2 2
3592 2 my $executable_label = $args->{argv}[0];
3593 2 ▶ $executable_label = substr ($executable_label, 0, 97) . "..."
Branch: 1 branch
BranchTrueFalseTotal
if length $executable_label > 100 0 2 2
3594 if length $executable_label > 100;
3595 my $granted = fs_require_permission ($req, $identity, {
3596 tool => "exec",
3597 action => "exec",
3598 dimensions => fs_permission_dimensions (fs_grant_workdir ($identity, $sandbox_grants),
3599 $subject, [
3600 { label => "Exact command: $command_label", match => $subject },
3601 { label => "This executable: $executable_label (any arguments)",
3602 match => "^\\[\Q$executable\E(?:,.*)?\\]\\z" },
3603 { label => "any command", match => "^" },
3604 ]),
3605 reason => $args->{reason},
3606 2 ▶ sandbox_grants => $sandbox_grants,
Branch: 1 branch
BranchTrueFalseTotal
length $input ? : 2 0 2
3607 (length $input ? (details => { "View stdin" => $stdin_detail }) : ()),
3608 });
3609  
3610 2 ▶ $timeout <= 300 || $permissions->closure ($granted)->{"long-running"}
Branch: 1 branch
BranchTrueFalseTotal
$timeout <= 300 or $permissions->closure($granted)->{"long-running"} or die "permission reduced below long-running for exec\n" 2 0 2
Condition33%1/3
$timeout <= 300 or $permissions->closure($granted)->{"long-running"}
l!l&&r!l&&!r
200
MC/DC0%0/2
$timeout <= 300 or $permissions->closure($granted)->{"long-running"}
$timeout <= 300 $permissions->closure($granted)->{"long-running"}
Truth table33%1/3
A or B
A= $timeout <= 300B= $permissions->closure($granted)->{"long-running"}
ABresult
1X1
011
000
3611 or die "permission reduced below long-running for exec\n";
3612  
3613 2 ▶ AE::log debug => "fs exec "
Branch: 2 branches
BranchTrueFalseTotal
length $subject > 200 ? : 0 2 2
length $input ? : 2 0 2
3614 . (substr $subject, 0, 200)
3615 . (length $subject > 200 ? "..." : "")
3616 . (length $input ? " stdin=" . length ($input) : "");
3617  
3618 2 fs_command $req, $workdir, $granted, [map { AnyEvent::MCP::utf8enc $_ } @{$args->{argv}}], $input, $timeout, $output;
3619 }
3620 4 ▶;
Branch: 2 branches
BranchTrueFalseTotal
$bwrap ? : 0 4 4
$bwrap ? : 0 4 4
3621  
3622 # fixed operations accept filenames, never caller-supplied VCS options or shell code.
3623 4 for my $operation (qw(diff status log)) {
3624 mcp_tool "vcs-$operation" =>
3625 "Run $operation via Git, SVN, CVS or Mercurial in workdir. "
3626 . "Explicit backend; cwd within workdir (default .). "
3627 . "files relative to cwd; must stay in workdir; never options. "
3628 . "Dedicated permission plus workdir-read; CVS and SVN log also need ssh-agent/network. "
3629 . "Returns exit/signal, bounded stdout/stderr, truncation flags. "
3630 . "grep filters stdout via PCRE after 1 MiB capture; max_lines/max_bytes bound output. "
3631 . "Trusts VCS client/config; sandbox enforces approved filesystem/network grants.",
3632 {
3633 type => "object",
3634 properties => {
3635 workdir => $workdir_schema,
3636 cwd => { type => "string", default => ".",
3637 description => "cwd relative to workdir; empty = .; must stay inside. Mount boundary unchanged." },
3638 backend => { type => "string", enum => [qw(git svn cvs hg)] },
3639 files => { type => "array", items => { type => "string" }, default => [] },
3640 %output_schema,
3641 },
3642 required => ["backend"],
3643 additionalProperties => JSON::XS::false,
3644 },
3645 0 ▶ sub {
Subroutine __ANON__: not called CC=25 SCAR=64.8
3646 0 my ($req, $args) = @_;
3647  
3648 0 my $backend = $args->{backend};
3649 0 ▶ defined $backend && !ref $backend && $backend =~ /\A(?:git|svn|cvs|hg)\z/
Branch: 1 branch
BranchTrueFalseTotal
defined $backend and not ref $backend and $backend =~ /\A(?:git|svn|cvs|hg)\z/u or die "backend must be git, svn, cvs or hg\n" 0 0 0
Condition0%0/6
defined $backend and not ref $backend and $backend =~ /\A(?:git|svn|cvs|hg)\z/u
!ll&&!rl&&r
000
defined $backend and not ref $backend
!ll&&!rl&&r
000
MC/DC0%0/3
defined $backend and not ref $backend and $backend =~ /\A(?:git|svn|cvs|hg)\z/u
defined $backend not ref $backend $backend =~ /\A(?:git|svn|cvs|hg)\z/u
Truth table0%0/4
A and not(B) and C
A= defined $backendB= not ref $backendC= $backend =~ /\A(?:git|svn|cvs|hg)\z/u
ABCresult
0XX0
10X0
1100
1111
3650 or die "backend must be git, svn, cvs or hg\n";
3651 0 ▶ my $program = $vcs_program{$backend}
Branch: 1 branch
BranchTrueFalseTotal
my $program = $vcs_program{$backend} or die "$backend executable is unavailable\n" 0 0 0
3652 or die "$backend executable is unavailable\n";
3653 0 my $output = fs_output_options $args;
3654 0 my ($workdir, $identity) = fs_workdir $args->{workdir};
3655 0 ▶ my $cwd = fs_path $workdir, length $args->{cwd} ? $args->{cwd} : ".";
Branch: 1 branch
BranchTrueFalseTotal
length $args->{'cwd'} ? : 0 0 0
3656 0 ▶ fs_inside $cwd, $workdir or die "VCS cwd must stay within the selected workdir\n";
Branch: 1 branch
BranchTrueFalseTotal
fs_inside($cwd, $workdir) or die "VCS cwd must stay within the selected workdir\n" 0 0 0
3657 0 ▶ my $files = $args->{files} // [];
Condition0%0/2
$args->{"files"} // []
l!l
00
MC/DC0%0/1
$args->{"files"} // []
$args->{"files"}
Truth table0%0/2
A
A= $args->{"files"}
Aresult
11
00
3658 0 ▶ ref $files eq "ARRAY" or die "files must be an array of filenames\n";
Branch: 1 branch
BranchTrueFalseTotal
ref $files eq "ARRAY" or die "files must be an array of filenames\n" 0 0 0
3659 0 my @files;
3660 0 my @paths = ($cwd);
3661 0 for my $file (@$files) {
3662 0 my $path = fs_path $cwd, $file;
3663 0 ▶ fs_inside $path, $workdir or die "VCS files must stay within the selected workdir\n";
Branch: 1 branch
BranchTrueFalseTotal
fs_inside($path, $workdir) or die "VCS files must stay within the selected workdir\n" 0 0 0
3664 0 push @paths, $path;
3665 0 my $relative = File::Spec::Unix->abs2rel ($path, $cwd);
3666 0 push @files, (AnyEvent::MCP::utf8enc "./$relative");
3667 }
3668  
3669 0 ▶ my @argv = $backend eq "git"
Branch: 8 branches
BranchTrueFalseTotal
$backend eq 'git' ? : 0 0 0
$operation eq 'diff' ? : 0 0 0
$operation eq 'status' ? : 0 0 0
$backend eq 'svn' ? : 0 0 0
$operation eq 'diff' ? : 0 0 0
$backend eq 'cvs' ? : 0 0 0
$operation eq 'diff' ? : 0 0 0
$operation eq 'log' ? : 0 0 0
3670 ? ($program, "--no-pager", "--no-optional-locks", "--literal-pathspecs", "-c", "core.fsmonitor=false",
3671 $operation, ($operation eq "diff" ? qw(--no-ext-diff --no-textconv --no-color --ignore-submodules)
3672 : $operation eq "status" ? qw(--short --untracked-files=normal --ignore-submodules)
3673 : qw(--no-decorate)),
3674 "--", @files)
3675 : $backend eq "svn"
3676 ? ($program, "--non-interactive", "--no-auth-cache", $operation,
3677 ($operation eq "diff" ? ("--internal-diff") : ()), "--", map "$_\@", @files)
3678 : $backend eq "cvs"
3679 ? ($program, "-f", $operation,
3680 ($operation eq "diff" ? ("-u") : $operation eq "log" ? ("-N") : ()),
3681 "--", @files)
3682 : ($program, "--noninteractive", "--config", "ui.paginate=never", $operation, "--", @files);
3683  
3684 0 ▶ my @need = fs_effective_grants ("workdir-read",
Branch: 1 branch
BranchTrueFalseTotal
$backend eq 'cvs' || $backend eq 'svn' && $operation eq 'log' ? : 0 0 0
Condition0%0/6
$backend eq "cvs" or $backend eq "svn" and $operation eq "log"
l!l&&r!l&&!r
000
$backend eq "svn" and $operation eq "log"
!ll&&!rl&&r
000
MC/DC0%0/3
$backend eq "cvs" or $backend eq "svn" and $operation eq "log"
$backend eq "cvs" $backend eq "svn" $operation eq "log"
Truth table0%0/4
A or B and C
A= $backend eq "cvs"B= $backend eq "svn"C= $operation eq "log"
ABCresult
1XX1
0111
00X0
0100
3685 ($backend eq "cvs" || $backend eq "svn" && $operation eq "log" ? ("ssh-agent") : ()));
3686 my $granted = fs_require_permission ($req, $identity, {
3687 0 ▶ tool => $req->{tool}, action => "vcs-$operation",
Branch: 1 branch
BranchTrueFalseTotal
@files ? : 0 0 0
3688 dimensions => fs_permission_dimensions (fs_grant_workdir ($identity, \@need),
3689 $backend, [
3690 { label => "$backend working copies", match => $backend },
3691 { label => "all supported VCS clients", match => "^" },
3692 ]),
3693 sandbox_grants => \@need, paths => \@paths,
3694 reason => "$backend $operation in $cwd (workdir $identity)"
3695 . (@files ? ": " . join (", ", @files) : " (entire working copy)"),
3696 });
3697 0 my $have = $permissions->closure ($granted);
3698 0 ▶ $have->{$_} or die "permission reduced below $_ for $req->{tool}\n" for @need;
Branch: 1 branch
BranchTrueFalseTotal
$have->{$_} or die qq[permission reduced below $_ for $req->{"tool"}\n] 0 0 0
3699  
3700 0 AE::log debug => join " ", "fs vcs-$operation", $backend, $cwd, @files;
3701  
3702 0 fs_command $req, $workdir, $granted, \@argv, "", 30, $output, $cwd;
3703 12 };
3704 }
3705  
3706 mcp_config
3707 name => $name,
3708 idle_exit => 300,
3709 server_name => "mcp-fs",
3710 server_version => 0,
3711 0 ▶ on_error => sub { AE::log info => "mcp-tool $_[1]{tool}: $_[2]" },
Subroutine __ANON__: not called CC=1 SCAR=6.9
3712 3 ▶ on_start => sub {
Subroutine __ANON__: called CC=2 SCAR=7.6
3713 3 ▶ print STDERR "Permission rules: $permissions->{file}\n"
Branch: 1 branch
BranchTrueFalseTotal
if $_[0]->isa("AnyEvent::MCP::Server::HTTP") 0 3 3
3714 if $_[0]->isa ("AnyEvent::MCP::Server::HTTP");
3715 },
3716 4 short_instructions => "Filesystem access: read/edit files, run sandboxed commands, inspect VCS in configured workdirs. Discover tools when working with files.",
3717 instructions =>
3718 "Start with workdirs: IDs/paths, mounts, sandbox_grants. "
3719 . "Select persistent integer ID (listing key, not array position) or configured/resolved path. "
3720 . "Inactive mappings expire after seven days; IDs may be reused; stale paths fail. "
3721 . "Paths relative to selected workdir. "
3722 . "workdir-read/write grant only selected workdir; all-workdirs-read/write grant every workdir. "
3723 . "all-workdirs-read + workdir-write: read all, write selected only. "
3724 . "Absolute paths in other workdirs need all-workdirs grants; other absolute paths need home/world grants or shared-tmp for host tmp. "
3725 . "Multi-path stat stays in selected workdir; rename across paths needs combined grants and may fail EXDEV at mount boundary. "
3726 . "Symlinks resolve inside granted mounts; overlapping workdir access unspecified. "
3727 . "Trusted mounts add baseline authority; world-read keeps writable exceptions, world-write ignores them. "
3728 . "exec requires useful reason and explicit sandbox_grants when needed. "
3729 . "Prefer vcs-diff/vcs-status/vcs-log for working copies: explicit backend, fixed argv, automatic grants. "
3730 . "exec/VCS: grep filters stdout via PCRE after capture; max_lines/max_bytes bound output; stderr unfiltered. "
3731 . "capture_truncated means possible unseen matches.\n";
3732  
3733 4 mcp_start %$server_options, (stdio => $stdio);
3734  
« lib/AnyEvent/MCP/Worker/IMAP.pm ↑ Summary blib/lib/AnyEvent/MCP/Permissions/Ask.pm »