swarmauri_tool_findfile 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- swarmauri_tool_findfile/FindFileTool.py +163 -0
- swarmauri_tool_findfile/__init__.py +17 -0
- swarmauri_tool_findfile/_filesystem.py +273 -0
- swarmauri_tool_findfile/_windows_fs.py +349 -0
- swarmauri_tool_findfile-0.1.0.dist-info/METADATA +452 -0
- swarmauri_tool_findfile-0.1.0.dist-info/RECORD +10 -0
- swarmauri_tool_findfile-0.1.0.dist-info/WHEEL +4 -0
- swarmauri_tool_findfile-0.1.0.dist-info/entry_points.txt +3 -0
- swarmauri_tool_findfile-0.1.0.dist-info/licenses/LICENSE +201 -0
- swarmauri_tool_findfile-0.1.0.dist-info/licenses/NOTICE +4 -0
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import fnmatch
|
|
2
|
+
import stat
|
|
3
|
+
from contextlib import closing
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Dict, List, Literal
|
|
6
|
+
|
|
7
|
+
from pydantic import Field
|
|
8
|
+
|
|
9
|
+
from swarmauri_base.ComponentBase import ComponentBase
|
|
10
|
+
from swarmauri_base.tools.ToolBase import ToolBase
|
|
11
|
+
from swarmauri_standard.tools.Parameter import Parameter
|
|
12
|
+
|
|
13
|
+
from . import _filesystem
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@ComponentBase.register_type(ToolBase, "FindFileTool")
|
|
17
|
+
class FindFileTool(ToolBase):
|
|
18
|
+
"""Find files under a directory by name or wildcard pattern."""
|
|
19
|
+
|
|
20
|
+
version: str = "0.1.dev1"
|
|
21
|
+
allowed_roots: List[str] = Field(
|
|
22
|
+
default_factory=lambda: [str(Path.cwd())],
|
|
23
|
+
description="Trusted absolute directories set by the service owner.",
|
|
24
|
+
)
|
|
25
|
+
max_scanned_entries: int = Field(default=100_000, ge=1)
|
|
26
|
+
max_results: int = Field(default=10_000, ge=1)
|
|
27
|
+
max_return_bytes: int = Field(default=1024 * 1024, ge=1)
|
|
28
|
+
max_elapsed_seconds: float = Field(default=2.0, gt=0, allow_inf_nan=False)
|
|
29
|
+
max_depth: int = Field(default=64, ge=0)
|
|
30
|
+
max_pattern_length: int = Field(default=1024, ge=1)
|
|
31
|
+
parameters: List[Parameter] = Field(
|
|
32
|
+
default_factory=lambda: [
|
|
33
|
+
Parameter(
|
|
34
|
+
name="path",
|
|
35
|
+
input_type="string",
|
|
36
|
+
description=("Directory to search. A leading ~ is expanded."),
|
|
37
|
+
required=True,
|
|
38
|
+
),
|
|
39
|
+
Parameter(
|
|
40
|
+
name="pattern",
|
|
41
|
+
input_type="string",
|
|
42
|
+
description=(
|
|
43
|
+
"Shell-style wildcard matched case-insensitively "
|
|
44
|
+
"against each file name, for example *.log or report?.txt."
|
|
45
|
+
),
|
|
46
|
+
required=True,
|
|
47
|
+
),
|
|
48
|
+
Parameter(
|
|
49
|
+
name="recursive",
|
|
50
|
+
input_type="boolean",
|
|
51
|
+
description=(
|
|
52
|
+
"Also search subdirectories. Defaults to false, which "
|
|
53
|
+
"checks only the top level."
|
|
54
|
+
),
|
|
55
|
+
required=False,
|
|
56
|
+
),
|
|
57
|
+
]
|
|
58
|
+
)
|
|
59
|
+
name: str = "FindFileTool"
|
|
60
|
+
description: str = (
|
|
61
|
+
"Searches a directory for files whose name matches a shell-style "
|
|
62
|
+
"wildcard, case-insensitively, optionally walking subdirectories."
|
|
63
|
+
)
|
|
64
|
+
type: Literal["FindFileTool"] = "FindFileTool"
|
|
65
|
+
|
|
66
|
+
def __call__(
|
|
67
|
+
self, path: str, pattern: str, recursive: bool = False
|
|
68
|
+
) -> Dict[str, object]:
|
|
69
|
+
"""Find bounded regular-file matches through trusted directory handles.
|
|
70
|
+
|
|
71
|
+
Matching is case-insensitive against basenames. Symlinks and special
|
|
72
|
+
files are excluded in both modes. Failures return no partial matches.
|
|
73
|
+
"""
|
|
74
|
+
display = path if isinstance(path, str) else ""
|
|
75
|
+
try:
|
|
76
|
+
if not isinstance(path, str) or not path.strip():
|
|
77
|
+
raise ValueError("path must be a non-empty string")
|
|
78
|
+
if (
|
|
79
|
+
not isinstance(pattern, str)
|
|
80
|
+
or not pattern
|
|
81
|
+
or "\x00" in pattern
|
|
82
|
+
):
|
|
83
|
+
raise ValueError(
|
|
84
|
+
"pattern must be a non-empty string without NULs"
|
|
85
|
+
)
|
|
86
|
+
if len(pattern) > self.max_pattern_length:
|
|
87
|
+
raise ValueError("pattern exceeds the configured length limit")
|
|
88
|
+
if not isinstance(recursive, bool):
|
|
89
|
+
raise ValueError("recursive must be a boolean")
|
|
90
|
+
target = Path(path).expanduser().absolute()
|
|
91
|
+
display = str(target)
|
|
92
|
+
budget = _filesystem.Budget(
|
|
93
|
+
self.max_scanned_entries,
|
|
94
|
+
self.max_results,
|
|
95
|
+
self.max_return_bytes,
|
|
96
|
+
self.max_elapsed_seconds,
|
|
97
|
+
)
|
|
98
|
+
lowered = pattern.lower()
|
|
99
|
+
matches = []
|
|
100
|
+
|
|
101
|
+
def walk(descriptor, current, relative, depth):
|
|
102
|
+
with closing(
|
|
103
|
+
_filesystem.directory_entries(descriptor)
|
|
104
|
+
) as children:
|
|
105
|
+
for name, mode in children:
|
|
106
|
+
budget.visit()
|
|
107
|
+
if mode is None:
|
|
108
|
+
continue
|
|
109
|
+
if stat.S_ISREG(mode):
|
|
110
|
+
if fnmatch.fnmatchcase(name.lower(), lowered):
|
|
111
|
+
match = str(current / name)
|
|
112
|
+
budget.retain(match)
|
|
113
|
+
matches.append(match)
|
|
114
|
+
elif recursive and stat.S_ISDIR(mode):
|
|
115
|
+
if depth >= self.max_depth:
|
|
116
|
+
raise ValueError(
|
|
117
|
+
"Scan exceeded the directory-depth limit"
|
|
118
|
+
)
|
|
119
|
+
with _filesystem.child_directory(
|
|
120
|
+
descriptor, name, root_fd, relative / name
|
|
121
|
+
) as child:
|
|
122
|
+
walk(
|
|
123
|
+
child,
|
|
124
|
+
current / name,
|
|
125
|
+
relative / name,
|
|
126
|
+
depth + 1,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
with _filesystem.open_directory(target, self.allowed_roots) as (
|
|
130
|
+
descriptor,
|
|
131
|
+
root_fd,
|
|
132
|
+
relative,
|
|
133
|
+
):
|
|
134
|
+
walk(descriptor, target, relative, 0)
|
|
135
|
+
matches.sort()
|
|
136
|
+
result = {
|
|
137
|
+
"path": display,
|
|
138
|
+
"pattern": pattern,
|
|
139
|
+
"count": len(matches),
|
|
140
|
+
"matches": matches,
|
|
141
|
+
}
|
|
142
|
+
budget.finish(result)
|
|
143
|
+
return result
|
|
144
|
+
except FileNotFoundError:
|
|
145
|
+
return self._failure(display, pattern, "Directory does not exist.")
|
|
146
|
+
except NotADirectoryError:
|
|
147
|
+
return self._failure(display, pattern, "Path is not a directory.")
|
|
148
|
+
except (OSError, ValueError, TypeError, RuntimeError) as exc:
|
|
149
|
+
return self._failure(
|
|
150
|
+
display, pattern, f"Could not read directory: {exc}"
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
def _failure(self, target, pattern, message) -> Dict[str, object]:
|
|
154
|
+
return _filesystem.failure_response(
|
|
155
|
+
{
|
|
156
|
+
"path": str(target),
|
|
157
|
+
"pattern": pattern if isinstance(pattern, str) else "",
|
|
158
|
+
"count": 0,
|
|
159
|
+
"matches": [],
|
|
160
|
+
"error": message,
|
|
161
|
+
},
|
|
162
|
+
self.max_return_bytes,
|
|
163
|
+
)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from .FindFileTool import FindFileTool
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
__all__ = ["FindFileTool"]
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
# For Python 3.8 and newer
|
|
8
|
+
from importlib.metadata import version, PackageNotFoundError
|
|
9
|
+
except ImportError:
|
|
10
|
+
# For older Python versions, use the backport
|
|
11
|
+
from importlib_metadata import version, PackageNotFoundError
|
|
12
|
+
|
|
13
|
+
try:
|
|
14
|
+
__version__ = version("swarmauri_tool_findfile")
|
|
15
|
+
except PackageNotFoundError:
|
|
16
|
+
# If the package is not installed (for example, during development)
|
|
17
|
+
__version__ = "0.0.0"
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""Scan directories through held filesystem handles and bound the response."""
|
|
2
|
+
|
|
3
|
+
import ctypes
|
|
4
|
+
import errno
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
import os
|
|
8
|
+
import platform
|
|
9
|
+
import sys
|
|
10
|
+
import stat
|
|
11
|
+
from contextlib import contextmanager
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
_RESOLVE_NO_SYMLINKS = 0x04
|
|
15
|
+
_RESOLVE_BENEATH = 0x08
|
|
16
|
+
_OPENAT2_ARCHES = {
|
|
17
|
+
"x86_64",
|
|
18
|
+
"amd64",
|
|
19
|
+
"i386",
|
|
20
|
+
"i686",
|
|
21
|
+
"aarch64",
|
|
22
|
+
"arm64",
|
|
23
|
+
"armv7l",
|
|
24
|
+
"riscv64",
|
|
25
|
+
"ppc64",
|
|
26
|
+
"ppc64le",
|
|
27
|
+
"s390x",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class _OpenHow(ctypes.Structure):
|
|
32
|
+
_fields_ = [
|
|
33
|
+
("flags", ctypes.c_uint64),
|
|
34
|
+
("mode", ctypes.c_uint64),
|
|
35
|
+
("resolve", ctypes.c_uint64),
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _directory_flags() -> int:
|
|
40
|
+
"""Refuse platforms without descriptor-relative, no-symlink traversal."""
|
|
41
|
+
if (
|
|
42
|
+
os.open not in os.supports_dir_fd
|
|
43
|
+
or not hasattr(os, "O_DIRECTORY")
|
|
44
|
+
or not hasattr(os, "O_NOFOLLOW")
|
|
45
|
+
or not hasattr(os, "O_CLOEXEC")
|
|
46
|
+
):
|
|
47
|
+
raise OSError(
|
|
48
|
+
errno.ENOTSUP,
|
|
49
|
+
"This platform lacks secure directory-relative file creation",
|
|
50
|
+
)
|
|
51
|
+
return os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _open_root(root: Path, directory_flags: int) -> int:
|
|
55
|
+
"""Anchor a trusted absolute root without following any symlink."""
|
|
56
|
+
descriptor = os.open(root.anchor, directory_flags)
|
|
57
|
+
try:
|
|
58
|
+
if root.parts[1:]:
|
|
59
|
+
opened = _open_root_beneath(
|
|
60
|
+
descriptor, Path(*root.parts[1:]), directory_flags
|
|
61
|
+
)
|
|
62
|
+
if opened is not None:
|
|
63
|
+
os.close(descriptor)
|
|
64
|
+
return opened
|
|
65
|
+
for part in root.parts[1:]:
|
|
66
|
+
child = os.open(part, directory_flags, dir_fd=descriptor)
|
|
67
|
+
os.close(descriptor)
|
|
68
|
+
descriptor = child
|
|
69
|
+
return descriptor
|
|
70
|
+
except BaseException:
|
|
71
|
+
os.close(descriptor)
|
|
72
|
+
raise
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _linux_openat2(root_fd: int, relative: Path, flags: int) -> int | None:
|
|
76
|
+
"""Use kernel-enforced resolution, or signal that it is unavailable."""
|
|
77
|
+
if (
|
|
78
|
+
sys.platform != "linux"
|
|
79
|
+
or platform.machine().lower() not in _OPENAT2_ARCHES
|
|
80
|
+
):
|
|
81
|
+
return None
|
|
82
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
83
|
+
syscall = libc.syscall
|
|
84
|
+
syscall.restype = ctypes.c_long
|
|
85
|
+
how = _OpenHow(
|
|
86
|
+
flags=flags,
|
|
87
|
+
mode=0,
|
|
88
|
+
resolve=_RESOLVE_BENEATH | _RESOLVE_NO_SYMLINKS,
|
|
89
|
+
)
|
|
90
|
+
result = syscall(
|
|
91
|
+
ctypes.c_long(437),
|
|
92
|
+
ctypes.c_int(root_fd),
|
|
93
|
+
ctypes.c_char_p(os.fsencode(relative)),
|
|
94
|
+
ctypes.byref(how),
|
|
95
|
+
ctypes.c_size_t(ctypes.sizeof(how)),
|
|
96
|
+
)
|
|
97
|
+
if result >= 0:
|
|
98
|
+
return int(result)
|
|
99
|
+
code = ctypes.get_errno()
|
|
100
|
+
if code in {errno.ENOSYS, errno.EINVAL, errno.E2BIG}:
|
|
101
|
+
return None
|
|
102
|
+
raise OSError(code, os.strerror(code), str(relative))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# Root establishment and operation lookup use the same kernel primitive.
|
|
106
|
+
_open_root_beneath = _linux_openat2
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _open_direct_child(root_fd: int, relative: Path, flags: int) -> int:
|
|
110
|
+
"""Use a single no-follow lookup when kernel containment is unavailable."""
|
|
111
|
+
if len(relative.parts) != 1:
|
|
112
|
+
raise OSError(errno.ENOTSUP, "Nested paths require Linux openat2")
|
|
113
|
+
return os.open(relative.name, flags, 0o666, dir_fd=root_fd)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@contextmanager
|
|
117
|
+
def open_directory(target: Path, allowed_roots: list[str]):
|
|
118
|
+
"""Open beneath a trusted root without following any symlink."""
|
|
119
|
+
if "\x00" in str(target) or ".." in target.parts:
|
|
120
|
+
raise ValueError("NUL characters and parent traversal are not allowed")
|
|
121
|
+
if not allowed_roots:
|
|
122
|
+
raise ValueError("allowed_roots must contain a trusted directory")
|
|
123
|
+
roots = []
|
|
124
|
+
for spelling in allowed_roots:
|
|
125
|
+
root = Path(spelling).expanduser()
|
|
126
|
+
if not root.is_absolute() or ".." in root.parts:
|
|
127
|
+
raise ValueError(
|
|
128
|
+
"allowed_roots must be absolute without parent traversal"
|
|
129
|
+
)
|
|
130
|
+
if target.is_relative_to(root):
|
|
131
|
+
roots.append(root)
|
|
132
|
+
if not roots:
|
|
133
|
+
raise PermissionError("Path is outside configured allowed_roots")
|
|
134
|
+
root = max(roots, key=lambda candidate: len(candidate.parts))
|
|
135
|
+
relative = target.relative_to(root)
|
|
136
|
+
if os.name == "nt":
|
|
137
|
+
from . import _windows_fs
|
|
138
|
+
|
|
139
|
+
with _windows_fs.directory(
|
|
140
|
+
root.anchor, root.parts[1:] + relative.parts
|
|
141
|
+
) as handle:
|
|
142
|
+
yield handle, None, Path()
|
|
143
|
+
return
|
|
144
|
+
|
|
145
|
+
flags = _directory_flags()
|
|
146
|
+
root_fd = _open_root(root, flags)
|
|
147
|
+
try:
|
|
148
|
+
with _scan_posix(root_fd, relative) as descriptor:
|
|
149
|
+
yield descriptor, root_fd, relative
|
|
150
|
+
finally:
|
|
151
|
+
os.close(root_fd)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@contextmanager
|
|
155
|
+
def _scan_posix(root_fd: int, relative: Path):
|
|
156
|
+
"""Open and recheck each scanned directory against the original root."""
|
|
157
|
+
if not relative.parts:
|
|
158
|
+
yield root_fd
|
|
159
|
+
return
|
|
160
|
+
|
|
161
|
+
def lookup():
|
|
162
|
+
flags = _directory_flags()
|
|
163
|
+
descriptor = _linux_openat2(root_fd, relative, flags)
|
|
164
|
+
return (
|
|
165
|
+
_open_direct_child(root_fd, relative, flags)
|
|
166
|
+
if descriptor is None
|
|
167
|
+
else descriptor
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
descriptor = lookup()
|
|
171
|
+
try:
|
|
172
|
+
yield descriptor
|
|
173
|
+
current = lookup()
|
|
174
|
+
try:
|
|
175
|
+
if not os.path.samestat(os.fstat(descriptor), os.fstat(current)):
|
|
176
|
+
raise PermissionError("Directory changed during scan")
|
|
177
|
+
finally:
|
|
178
|
+
os.close(current)
|
|
179
|
+
finally:
|
|
180
|
+
os.close(descriptor)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@contextmanager
|
|
184
|
+
def child_directory(
|
|
185
|
+
parent_fd: int, name: str, root_fd: int | None, relative: Path
|
|
186
|
+
):
|
|
187
|
+
"""Open from the original POSIX root or the held Windows parent."""
|
|
188
|
+
if root_fd is not None:
|
|
189
|
+
with _scan_posix(root_fd, relative) as descriptor:
|
|
190
|
+
yield descriptor
|
|
191
|
+
return
|
|
192
|
+
|
|
193
|
+
from . import _windows_fs
|
|
194
|
+
|
|
195
|
+
handle = _windows_fs.child_directory(parent_fd, name)
|
|
196
|
+
try:
|
|
197
|
+
yield handle
|
|
198
|
+
finally:
|
|
199
|
+
_windows_fs.close_directory(handle)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def directory_entries(descriptor: int):
|
|
203
|
+
"""Yield entry names and types without following links."""
|
|
204
|
+
if os.name == "nt":
|
|
205
|
+
from . import _windows_fs
|
|
206
|
+
|
|
207
|
+
yield from _windows_fs.directory_entries(descriptor)
|
|
208
|
+
return
|
|
209
|
+
with os.scandir(descriptor) as children:
|
|
210
|
+
for child in children:
|
|
211
|
+
yield (
|
|
212
|
+
child.name,
|
|
213
|
+
stat.S_IFMT(child.stat(follow_symlinks=False).st_mode),
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class Budget:
|
|
218
|
+
"""Bound entries, retained JSON output, and scan time."""
|
|
219
|
+
|
|
220
|
+
def __init__(self, scanned: int, results: int, size: int, seconds: float):
|
|
221
|
+
self.max_scanned = scanned
|
|
222
|
+
self.max_results = results
|
|
223
|
+
self.max_bytes = size
|
|
224
|
+
self.deadline = time.monotonic() + seconds
|
|
225
|
+
self.scanned = 0
|
|
226
|
+
self.results = 0
|
|
227
|
+
self.size = 0
|
|
228
|
+
|
|
229
|
+
def check(self) -> None:
|
|
230
|
+
if time.monotonic() > self.deadline:
|
|
231
|
+
raise ValueError("Scan exceeded the elapsed-time limit")
|
|
232
|
+
|
|
233
|
+
def visit(self) -> None:
|
|
234
|
+
self.check()
|
|
235
|
+
self.scanned += 1
|
|
236
|
+
if self.scanned > self.max_scanned:
|
|
237
|
+
raise ValueError("Scan exceeded the scanned-entry limit")
|
|
238
|
+
|
|
239
|
+
def retain(self, item: object) -> None:
|
|
240
|
+
self.check()
|
|
241
|
+
self.results += 1
|
|
242
|
+
self.size += (
|
|
243
|
+
len(json.dumps(item, ensure_ascii=True).encode("utf-8")) + 2
|
|
244
|
+
)
|
|
245
|
+
if self.results > self.max_results:
|
|
246
|
+
raise ValueError("Scan exceeded the result limit")
|
|
247
|
+
if self.size > self.max_bytes:
|
|
248
|
+
raise ValueError("Scan exceeded the returned-byte limit")
|
|
249
|
+
|
|
250
|
+
def finish(self, result: dict) -> None:
|
|
251
|
+
self.check()
|
|
252
|
+
if (
|
|
253
|
+
len(json.dumps(result, ensure_ascii=True).encode("utf-8"))
|
|
254
|
+
> self.max_bytes
|
|
255
|
+
):
|
|
256
|
+
raise ValueError("Scan exceeded the returned-byte limit")
|
|
257
|
+
self.check()
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def failure_response(result: dict, limit: int) -> dict:
|
|
261
|
+
"""Bound echoed input and diagnostic output, retaining a useful error."""
|
|
262
|
+
# Keep room for a structured error even with tiny success budgets.
|
|
263
|
+
limit = max(256, min(limit, 4096))
|
|
264
|
+
for key, value in result.items():
|
|
265
|
+
if isinstance(value, str) and len(value) > limit:
|
|
266
|
+
result[key] = value[: limit - 3] + "..."
|
|
267
|
+
while len(json.dumps(result, ensure_ascii=True).encode("utf-8")) > limit:
|
|
268
|
+
key = max(
|
|
269
|
+
(key for key, value in result.items() if isinstance(value, str)),
|
|
270
|
+
key=lambda key: len(result[key]),
|
|
271
|
+
)
|
|
272
|
+
result[key] = result[key][: len(result[key]) // 2]
|
|
273
|
+
return result
|