@kawaz/sockat 0.0.0 → 0.1.0

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.
package/dist/sweep.js ADDED
@@ -0,0 +1,172 @@
1
+ import fs from "node:fs";
2
+ import { invalidArgument, systemError } from "./errors.js";
3
+ import { attempt, closeQuietly, entry, fstat, isOurDir, lstat, modeBits, procAt, realDir, sameId } from "./fsx.js";
4
+ import { openLocked } from "./lock.js";
5
+ import { isRandomName } from "./names.js";
6
+ import { joinUnder, splitPath } from "./paths.js";
7
+ import { bName, checkAncestors, givenShapeOk } from "./world.js";
8
+ // sweep and sweepBase (SPEC "sweep"): remove the D of processes that have
9
+ // ended, told by an exclusive lock taken at once.
10
+ /** Throws the errors collected: one as it is, several as an AggregateError. */
11
+ function throwAll(errors, message) {
12
+ if (errors.length === 1 && errors[0] !== undefined) {
13
+ throw errors[0];
14
+ }
15
+ if (errors.length > 1) {
16
+ throw new AggregateError(errors, message);
17
+ }
18
+ }
19
+ /**
20
+ * sweep on w: the B of a default name in each of w's places 1 to 3 whose
21
+ * ancestors pass their check. A place or B that fails a check is passed
22
+ * over; nothing is made.
23
+ */
24
+ export function sweepIn(w) {
25
+ const errors = [];
26
+ for (const p of w.autoPlaces()) {
27
+ const real = realDir(p.path);
28
+ if (!real.ok || checkAncestors(real.value, false) !== null) {
29
+ continue;
30
+ }
31
+ const b = joinUnder(real.value, bName(p.kind));
32
+ errors.push(...sweepB(w, b, b, false));
33
+ }
34
+ throwAll(errors, "sweep: some directories could not be removed");
35
+ }
36
+ /**
37
+ * sweepBase on w: sweep for the B at base (as given to Options.base).
38
+ * Nothing when base, or its parent, does not exist; an argument error for a
39
+ * base of the wrong form; EPERM / ENOTDIR for a B or an ancestor that fails
40
+ * the check.
41
+ */
42
+ export function sweepBaseIn(w, base) {
43
+ if (!givenShapeOk(base)) {
44
+ throw invalidArgument("base", base, "must be an absolute path ending with a name");
45
+ }
46
+ const parts = splitPath(base);
47
+ if (parts === null) {
48
+ return;
49
+ }
50
+ const real = realDir(parts.dir);
51
+ if (!real.ok) {
52
+ if (real.code === "ENOENT") {
53
+ return;
54
+ }
55
+ throw systemError(real.code, "sweep", base);
56
+ }
57
+ const st = attempt(() => fs.statSync(real.value));
58
+ if (!st.ok) {
59
+ throw systemError(st.code, "sweep", base);
60
+ }
61
+ if (!st.value.isDirectory()) {
62
+ throw systemError("ENOTDIR", "sweep", base);
63
+ }
64
+ if (checkAncestors(real.value, false) !== null) {
65
+ throw systemError("EPERM", "sweep", base);
66
+ }
67
+ throwAll(sweepB(w, joinUnder(real.value, parts.name), base, true), "sweep: some directories could not be removed");
68
+ }
69
+ /**
70
+ * Removes the dead D in the B at real (named path in the errors): a
71
+ * directory of ours others cannot write to, opened without following a
72
+ * symlink. Nothing when it is not there. given makes a B that fails the
73
+ * check an error; otherwise it is passed over.
74
+ */
75
+ function sweepB(w, real, path, given) {
76
+ const failed = (code) => (given ? [systemError(code, "sweep", path)] : []);
77
+ const st = lstat(real);
78
+ if (!st.ok) {
79
+ return st.code === "ENOENT" ? [] : failed(st.code);
80
+ }
81
+ if (st.value.isSymbolicLink()) {
82
+ return failed("EPERM");
83
+ }
84
+ if (!st.value.isDirectory()) {
85
+ return failed("ENOTDIR");
86
+ }
87
+ const opened = attempt(() => fs.openSync(real, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW));
88
+ if (!opened.ok) {
89
+ return failed(opened.code);
90
+ }
91
+ const bfd = opened.value;
92
+ try {
93
+ const held = fstat(bfd);
94
+ if (!held.ok) {
95
+ return [systemError(held.code, "sweep", path)];
96
+ }
97
+ if (!isOurDir(held.value) || (modeBits(held.value) & 0o022) !== 0 || !sameId(held.value, st.value)) {
98
+ return failed("EPERM");
99
+ }
100
+ const b = { real, at: w.cfg.os === "linux" ? procAt(w.cfg.proc, bfd, held.value) : null };
101
+ const names = attempt(() => fs.readdirSync(entry(b, "."), { encoding: "utf8" }));
102
+ if (!names.ok) {
103
+ return [systemError(names.code, "sweep", path)];
104
+ }
105
+ const errors = [];
106
+ for (const n of names.value) {
107
+ const code = sweepD(w, b, n);
108
+ if (code !== null) {
109
+ errors.push(systemError(code, "sweep", joinUnder(real, n)));
110
+ }
111
+ }
112
+ return errors;
113
+ }
114
+ finally {
115
+ closeQuietly(bfd);
116
+ }
117
+ }
118
+ /**
119
+ * Removes the entry name of B when it is a D whose process has ended
120
+ * (SPEC-routes "D と E"): named as a D is, a directory of ours, on which an
121
+ * exclusive lock can be taken at once (a live process holds a shared one),
122
+ * still named name once locked, and holding nothing but symlinks. The
123
+ * symlinks go, then D. Anything else is left alone. The errno of a dead D
124
+ * that could not be removed; null otherwise.
125
+ */
126
+ function sweepD(w, b, name) {
127
+ if (!isRandomName(name)) {
128
+ return null;
129
+ }
130
+ const at = entry(b, name);
131
+ const st = lstat(at);
132
+ if (!st.ok || !isOurDir(st.value)) {
133
+ return null;
134
+ }
135
+ const locked = openLocked(at, w.cfg.lock, "exclusive");
136
+ if (!locked.ok) {
137
+ return null;
138
+ }
139
+ const dfd = locked.fd;
140
+ try {
141
+ const held = fstat(dfd);
142
+ const now = lstat(at);
143
+ if (!held.ok || !isOurDir(held.value) || !now.ok || !sameId(now.value, held.value)) {
144
+ return null;
145
+ }
146
+ const d = { real: joinUnder(b.real, name), at: w.cfg.os === "linux" ? procAt(w.cfg.proc, dfd, held.value) : null };
147
+ const entries = attempt(() => fs.readdirSync(entry(d, "."), { encoding: "utf8" }));
148
+ if (!entries.ok) {
149
+ return entries.code;
150
+ }
151
+ for (const e of entries.value) {
152
+ const est = lstat(entry(d, e));
153
+ if (!est.ok || !est.value.isSymbolicLink()) {
154
+ return null;
155
+ }
156
+ }
157
+ for (const e of entries.value) {
158
+ const r = attempt(() => fs.unlinkSync(entry(d, e)));
159
+ if (!r.ok && r.code !== "ENOENT") {
160
+ return r.code;
161
+ }
162
+ }
163
+ const r = attempt(() => fs.rmdirSync(at));
164
+ if (!r.ok && r.code !== "ENOENT" && r.code !== "ENOTEMPTY" && r.code !== "EEXIST") {
165
+ return r.code;
166
+ }
167
+ return null;
168
+ }
169
+ finally {
170
+ closeQuietly(dfd);
171
+ }
172
+ }
@@ -0,0 +1,100 @@
1
+ import type { Skip } from "./errors.ts";
2
+ export type { Skip } from "./errors.ts";
3
+ /** What the `*Ex` functions and the resolves take besides the path. */
4
+ export interface Options {
5
+ /**
6
+ * Ask for a spelling a peer of another uid can follow: a B where B and
7
+ * every directory on the way to it let others search them, and no /proc
8
+ * spelling. Only the binds look at it. Whether it was met shows in the
9
+ * result's `spelling`.
10
+ */
11
+ readonly usableCrossUid?: boolean;
12
+ /**
13
+ * The path of B itself (a place the application manages, such as
14
+ * `/tmp/app-1000/sockat`): B is made there instead of in /tmp,
15
+ * $XDG_RUNTIME_DIR or $TMPDIR, and a check that fails is an error rather
16
+ * than a fall back to those places. Absolute, ending with a name.
17
+ */
18
+ readonly base?: string;
19
+ }
20
+ /**
21
+ * What the spelling of a bind is good for afterwards: the spelling the
22
+ * kernel keeps for the socket, which code may later unlink or look up.
23
+ * Branch on it rather than on the diagnostics.
24
+ */
25
+ export type Spelling =
26
+ /** The path itself, absolute. */
27
+ {
28
+ readonly kind: "Original";
29
+ }
30
+ /** The path itself, relative: after a change of the cwd it names another place. */
31
+ | {
32
+ readonly kind: "CwdRelative";
33
+ }
34
+ /** Through B, D and E, naming the same place as the path. */
35
+ | {
36
+ readonly kind: "Linked";
37
+ /** Unlinking the spelling removes the socket file (false: it removes the E only). */
38
+ readonly removable: boolean;
39
+ /** How long the spelling can be followed: until the process ends, or until the cleanup. */
40
+ readonly until: "Process" | "Cleanup";
41
+ /** A peer of another uid can follow it. */
42
+ readonly usableCrossUid: boolean;
43
+ /** A peer can follow it even when either side has a /tmp of its own (systemd's PrivateTmp). */
44
+ readonly usableWithPrivateTmp: boolean;
45
+ }
46
+ /** Through an E already removed: it names nothing. */
47
+ | {
48
+ readonly kind: "Dangling";
49
+ };
50
+ /** Removes a bound socket file, and the E its spelling goes through. */
51
+ export interface SocketFile {
52
+ /**
53
+ * Removes the socket file, only while its path still names the file bound
54
+ * (the same (st_dev, st_ino)), then does what `cleanup` does. It does not
55
+ * close the listener. Call it before closing the listener.
56
+ */
57
+ remove(): void;
58
+ /** Removes the E the spelling goes through (B and D stay). Do not use the spelling afterwards. */
59
+ cleanup(): void;
60
+ }
61
+ /** What a bind reports besides the listener (SPEC `Bound`). */
62
+ export interface Bound<S> {
63
+ readonly socket: S;
64
+ readonly file: SocketFile;
65
+ readonly spelling: Spelling;
66
+ /** The route taken. For diagnostics: not a promise. */
67
+ readonly route: string;
68
+ /** Which B the spelling goes through (`proc`, `tmp`, `runtime`, `tmpdir`, `sockdir`, `given`); null for none. */
69
+ readonly base: string | null;
70
+ /** The routes found unusable before `route`, in the order tried. */
71
+ readonly skipped: Skip[];
72
+ }
73
+ /** What a connect reports besides the socket (SPEC `Connected`). */
74
+ export interface Connected<S> {
75
+ readonly socket: S;
76
+ readonly route: string;
77
+ readonly skipped: Skip[];
78
+ }
79
+ /** A spelling of a path to bind by yourself (SPEC `ForBind`). */
80
+ export interface ForBind {
81
+ /** The spelling to hand to the standard in place of the path. */
82
+ readonly path: string;
83
+ readonly spelling: Spelling;
84
+ readonly route: string;
85
+ readonly base: string | null;
86
+ readonly skipped: Skip[];
87
+ /** Removes the E the spelling goes through. */
88
+ cleanup(): void;
89
+ /** Call after binding `path` yourself (and before closing it): records the socket file for its removal. */
90
+ socketFile(): SocketFile;
91
+ }
92
+ /** A spelling of a path to connect to by yourself (SPEC `ForConnect`). */
93
+ export interface ForConnect {
94
+ /** The spelling to hand to the standard in place of the path, as many times as you like. */
95
+ readonly path: string;
96
+ readonly route: string;
97
+ readonly skipped: Skip[];
98
+ /** Removes the E the spelling goes through. */
99
+ cleanup(): void;
100
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,198 @@
1
+ import type { Config } from "./config.ts";
2
+ import { type CallSite, Unusable } from "./errors.ts";
3
+ import { type FileId, type HeldDir, type Result } from "./fsx.ts";
4
+ /** The kinds of B, which are also the diagnostics' base values for a real-path spelling. */
5
+ export type BaseKind = "tmp" | "runtime" | "tmpdir" | "sockdir" | "given";
6
+ /** A D: held open with a shared lock for the life of the process (never closed). */
7
+ export interface ProcD extends HeldDir {
8
+ readonly fd: number;
9
+ readonly name: string;
10
+ readonly id: FileId;
11
+ }
12
+ /** A B the world holds, by its fd (never closed). */
13
+ export interface Base extends HeldDir {
14
+ readonly fd: number;
15
+ readonly id: FileId;
16
+ readonly kind: BaseKind;
17
+ /** Every directory on the way to B lets others search it (mode & 0o001), as seen when B was first held. */
18
+ readonly ancestorsX: boolean;
19
+ /**
20
+ * B itself lets others search it. Remembered when true; when false it is
21
+ * looked at again (crossOf), since a process making B at the same time may
22
+ * have opened it between its mkdir (0700) and its chmod (0711).
23
+ */
24
+ selfX: boolean;
25
+ /** The place before its real path was resolved, or B's real path, goes through a private /tmp's directory. */
26
+ readonly tmpPath: boolean;
27
+ /** This process's D in B, made at most once (ownD). */
28
+ d: ProcD | null;
29
+ /** The name of the next resolve E (base 36). */
30
+ nextE: number;
31
+ }
32
+ /** An E this process made in its D of a B. */
33
+ export interface Link {
34
+ readonly base: Base;
35
+ readonly d: ProcD;
36
+ readonly name: string;
37
+ }
38
+ /** Somewhere B may be made: its kind and its path as configured. */
39
+ interface Place {
40
+ readonly kind: BaseKind;
41
+ readonly path: string;
42
+ }
43
+ /**
44
+ * Whether a spelling through a B of the kind, whose real path is real,
45
+ * can fit: the estimate before B is made (no B is made where it cannot).
46
+ */
47
+ export type Fits = (kind: BaseKind, real: string) => boolean;
48
+ /** D as a directory held, through which its E are named. */
49
+ export declare function dHeld(b: Base, d: ProcD): HeldDir;
50
+ /** E's real path, for nothing but its removal's error. */
51
+ export declare function linkEntry(e: Link): string;
52
+ /** Unlinks E; a missing E is no error (removed already). */
53
+ export declare function removeLink(e: Link): Result<void>;
54
+ /**
55
+ * Checks every directory from the root down to real, a real path
56
+ * (SPEC-routes "B の作り方" step 2): each is owned by root or the effective
57
+ * uid, and others cannot write to it (group included) unless it is sticky.
58
+ * With otherX, each must also let others search it. null when all pass;
59
+ * otherwise the failing path and EPERM, or the lstat's errno.
60
+ */
61
+ export declare function checkAncestors(real: string, otherX: boolean): {
62
+ code: string;
63
+ path: string;
64
+ } | null;
65
+ /** The form of Options.base (SPEC "エラー"): absolute and ending with a name. */
66
+ export declare function givenShapeOk(b: string): boolean;
67
+ /**
68
+ * What a process keeps across calls: the B it made, each held by its fd, and
69
+ * the places whose ancestors passed their check. A B that could be made is
70
+ * kept and used by every later call; one that could not is not remembered.
71
+ */
72
+ export declare class World {
73
+ readonly cfg: Config;
74
+ /** The B of the places 1 to 3 (/tmp, $XDG_RUNTIME_DIR, $TMPDIR). */
75
+ auto: Base | null;
76
+ /** The B of a usableCrossUid bind; auto itself when it is such a B. */
77
+ autoCross: Base | null;
78
+ /** The B of the place 4, per socket's directory. */
79
+ readonly sockdir: Map<string, Base>;
80
+ /** The B of Options.base, by its (st_dev, st_ino). */
81
+ readonly given: Map<string, Base>;
82
+ /** The real paths of the places whose ancestors passed the check (once per process). */
83
+ readonly checked: Set<string>;
84
+ constructor(cfg: Config);
85
+ /** Every B the world holds, each once. */
86
+ bases(): Base[];
87
+ /** The places 1 to 3 in order; the last two only when set to an absolute path. */
88
+ autoPlaces(): Place[];
89
+ /**
90
+ * The world's B of the places 1 to 3 (cross: one others can follow): the
91
+ * first place in order where B is or can be made, whatever the length of
92
+ * the path, so every process of the user finds its B in the same place.
93
+ * Before B is made there, fits estimates the spelling through it: where it
94
+ * cannot fit, nothing is made and the next place is not tried.
95
+ */
96
+ autoBase(cross: boolean, fits: Fits): Base | Unusable;
97
+ /**
98
+ * Forgets the B of the places 1 to 3 when it was removed, so this call
99
+ * makes B again (an old systemd-tmpfiles, macOS's cleaning of $TMPDIR, or
100
+ * a hand may remove it).
101
+ *
102
+ * Design rationale: the fds of a B (and its D) forgotten are left open,
103
+ * not closed: an E handed out through it (SocketFile's cleanup) is still
104
+ * unlinked through D's fd on Linux, which a closed and reused fd number
105
+ * would point elsewhere.
106
+ */
107
+ private dropGoneAuto;
108
+ /** b, or the B already held at the same (st_dev, st_ino) (b's fd then closed). */
109
+ private known;
110
+ /** Whether the directories down to real pass checkAncestors, checked once per process. */
111
+ ancestorsPass(real: string): boolean;
112
+ /**
113
+ * Checks Options.base before any route is tried, at every call, making
114
+ * nothing (SPEC-routes "B の作り方"): its parent exists (ENOENT) and is a
115
+ * directory (ENOTDIR), every ancestor passes checkAncestors (EPERM), and B
116
+ * itself, when there, is a directory of ours others cannot write to (a
117
+ * symlink is EPERM, anything else ENOTDIR). With cross, every one of them
118
+ * must let others search it (EPERM): looked at now while the world does not
119
+ * hold the B yet, and taken from when it was first held once it does.
120
+ * The form (absolute, ending with a name) was checked before.
121
+ */
122
+ checkGiven(b: string, cross: boolean, site: CallSite): void;
123
+ /**
124
+ * The world's B at b (Options.base, checked by checkGiven), made when there
125
+ * is none there yet. Where the spelling is estimated not to fit, nothing is
126
+ * made and the route is unusable. Otherwise an error making or opening it
127
+ * is thrown, with EPERM for what is not a private directory of ours.
128
+ */
129
+ givenBase(b: string, fits: Fits, site: CallSite): Base | Unusable;
130
+ /**
131
+ * The world's B in the socket's directory (real, its real path; id, its
132
+ * (st_dev, st_ino)), made when there is none yet: the place 4. null when
133
+ * it cannot be made.
134
+ */
135
+ sockdirBase(real: string, id: FileId): Base | null;
136
+ /**
137
+ * Makes (or opens) B in the place p, whose real path is real (SPEC-routes
138
+ * "B の作り方" steps 2 to 5). B is named sockat-<euid> (sockat under
139
+ * $XDG_RUNTIME_DIR, .sockat.<random> in the socket's directory); one
140
+ * already there that fails the check is passed over for
141
+ * sockat-<euid>.<random>, except for Options.base (given), whose failure is
142
+ * returned.
143
+ */
144
+ private makeBase;
145
+ /**
146
+ * The parent of a B (a checked real path) as a directory held: on Linux
147
+ * with /proc, opened O_PATH and named through /proc/self/fd (as mkdirat(2)
148
+ * on its fd would); otherwise by its real path, which nobody else can
149
+ * replace (its ancestors passed their check).
150
+ */
151
+ private holdParent;
152
+ /** Makes a directory named prefix + random characters in parent, as openMade does. */
153
+ private makeFresh;
154
+ /**
155
+ * Whether p goes through a directory a private /tmp replaces: component by
156
+ * component one of cfg.privateTmps or below it, or below its real path.
157
+ */
158
+ throughPrivateTmp(p: string): boolean;
159
+ /**
160
+ * The process's D in b, made the first time and made again when the D held
161
+ * was removed (its fd left open, as a forgotten B's). null when it cannot
162
+ * be made (not remembered: the next call tries again).
163
+ */
164
+ ownD(b: Base): ProcD | null;
165
+ /**
166
+ * Makes a D in b (SPEC-routes "D と E" steps 1 to 4): mkdir 0700 under a
167
+ * random name, set to 0711, opened without following a symlink with a
168
+ * shared lock taken (openLocked) and checked to be a directory of ours, and
169
+ * its name looked up again. A D taken away before it was locked (another
170
+ * process's sweep saw it unlocked: the chmod or the open finds nothing,
171
+ * the lock is busy, or the name names another) is "takenAway", and the
172
+ * next name is tried; what this call made of it is removed first.
173
+ */
174
+ private makeOwnD;
175
+ /**
176
+ * Makes a resolve E in d (b's D) pointing to target, named by b's counter
177
+ * in base 36 (D is this process's alone, so a short counter is unique). A
178
+ * name taken is passed over for the next. null when none could be made.
179
+ */
180
+ resolveE(b: Base, d: ProcD, target: string): Link | null;
181
+ }
182
+ /** The name of B in a place of kind: sockat-<euid>, sockat under $XDG_RUNTIME_DIR. */
183
+ export declare function bName(kind: BaseKind): string;
184
+ /**
185
+ * Whether others can follow a real-path spelling through b: every directory
186
+ * on the way and B itself let them search (SPEC-routes "実体の置き場"). B's own
187
+ * mode is looked at again by its fd while it was found without it.
188
+ */
189
+ export declare function crossOf(b: Base): boolean;
190
+ /** The process's world: the public API's calls share its B and D. */
191
+ export declare function defaultWorld(): World;
192
+ /**
193
+ * Points the public API at w instead of the process's environment. For the
194
+ * tests only (not exported from the package): they keep the public API away
195
+ * from the real /tmp/sockat-<uid>.
196
+ */
197
+ export declare function setDefaultWorld(w: World): void;
198
+ export {};