@kawaz/sockat 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yoshiaki Kawazu (@kawaz)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README-ja.md ADDED
@@ -0,0 +1,202 @@
1
+ # sockat (TypeScript)
2
+
3
+ > [English](./README.md) | 日本語
4
+
5
+ `@kawaz/sockat` は、`sun_path` の上限 (macOS 104・Linux 108 バイト) を超えるパスでも Unix domain socket を bind / connect できるようにする TypeScript の package (Node.js 22 以上と Bun)。標準が受け付ける長さのパスは標準にそのまま渡し、長いパスだけを同じ所を指す短い綴りにして標準に渡す。native の部品は持たない。
6
+
7
+ - 振る舞いの正本 (言語によらない仕様): [kawaz/sockat の SPEC](https://github.com/kawaz/sockat/blob/main/docs/SPEC-ja.md)
8
+ - 他の言語の実装: [kawaz/sockat](https://github.com/kawaz/sockat)
9
+
10
+ ## 使い方
11
+
12
+ node:net (Node と Bun):
13
+
14
+ ```ts
15
+ import { bind, bindEx, connect } from "@kawaz/sockat";
16
+
17
+ const server = await bind(path); // listening になってから返る net.Server
18
+ server.on("connection", (s) => s.end("hi"));
19
+ const socket = await connect(path); // connect が終わってから返る net.Socket
20
+ ```
21
+
22
+ Bun の `Bun.listen` / `Bun.connect` (Bun 以外で呼ぶとすぐエラー):
23
+
24
+ ```ts
25
+ import { connect, listen } from "@kawaz/sockat/bun";
26
+
27
+ const listener = listen({ unix: path, socket: { data(s, d) { s.write(d); } } });
28
+ const socket = await connect({ unix: path, socket: { data() {} } });
29
+ ```
30
+
31
+ | 関数 | 返す物 |
32
+ |---|---|
33
+ | `bind(path)` / `connect(path)` | `net.Server` / `net.Socket` (Promise) |
34
+ | `bindEx(path, options?)` / `connectEx(path, options?)` | `Bound<net.Server>` / `Connected<net.Socket>` |
35
+ | `listen(options)` / `connect(options)` (`/bun`) | `Bun.UnixSocketListener` (同期) / `Bun.Socket` (Promise) |
36
+ | `listenEx(options, sockatOptions?)` / `connectEx(options, sockatOptions?)` (`/bun`) | `Bound<…>` / `Connected<…>` |
37
+ | `resolveForBind(path, options?)` / `resolveForConnect(path, options?)` | `ForBind` / `ForConnect` (同期) |
38
+ | `sweep()` / `sweepBase(path)` | 無し |
39
+
40
+ - 空のパスと、先頭以外に NUL を含むパスは `TypeError` (`code` は `ERR_INVALID_ARG_VALUE`)。Linux では先頭が NUL のパス (abstract) を標準にそのまま渡す
41
+ - node:net は数値に読める文字列 (`"0"`・`"8080"`・`"1e3"`・空白だけ 等) を TCP のポートとみなす。sockat は、スラッシュを含まずそう読める綴りに `./` を付けて渡す (同じファイル。`Spelling` は `CwdRelative` のまま、`address()` は渡したパス)。`./` を付けて標準に渡す長さを超える時は長いパスとして扱う
42
+ - OS のエラーは Node の形 (`code`・`errno`・`syscall`・`path`。`path` は渡したパス)。`*Ex` と resolve のエラーには `route` (実際に bind / connect して失敗した経路、無ければ `null`) と `skipped` が付く
43
+
44
+ ### ソケットのファイルを消す (`bindEx` と `file`)
45
+
46
+ ```ts
47
+ const b = await bindEx(path); // b.socket, b.file, b.spelling, b.route, b.base, b.skipped
48
+ // …
49
+ b.file.remove(); // ソケットのファイルを消す (listener は閉じない)。閉じる前に呼ぶ
50
+ b.socket.close();
51
+ ```
52
+
53
+ - `b.file` は bind した直後にソケットのファイルの realpath と `(st_dev, st_ino)` を覚え、`remove()` はそのパスが今も同じファイルの時だけ消す。覚えられなければ `bindEx` はエラーにする (綴りの symlink を先に消してから listener を閉じるので、置き換わった物は消さない。短いパスは閉じると標準がパスを unlink する)
54
+ - 最後の要素が symlink の時 (macOS・NetBSD の bind はそれを辿る) は、辿った先のソケットを覚えて消し、symlink は消さない
55
+ - `remove()` は `cleanup()` もする。`cleanup()` は綴りが通る symlink (E) だけを消す。成功した後の呼び出しは何もせず、失敗した後の呼び出しはやり直す
56
+ - 開いている間だけ置き換えを見分けられる。閉じた後に作り直された物は `(st_dev, st_ino)` を使い回すファイルシステムで見分けられない
57
+
58
+ ### 綴りの性質 (`Spelling`)
59
+
60
+ 長いパスでは、カーネルが覚えるアドレス (他の言語の相手の `getpeername`、`ss -x`・`lsof` 等) は渡したパスでなく bind の綴りになる。`spelling` はその綴りを後で使えるかを返す。分岐はこれで書く。
61
+
62
+ | `kind` | 綴り |
63
+ |---|---|
64
+ | `Original` | 元の絶対パス (abstract の名前も) |
65
+ | `CwdRelative` | 元の相対パス (`./` を付けた物も)。cwd を変えると別の所を指す |
66
+ | `Linked` | 置き場の B・D・E を通り、元のパスと同じ所を指す |
67
+ | `Dangling` | どこにも届かない (sockat-ts では生まれない) |
68
+
69
+ `Linked` の属性:
70
+
71
+ | 属性 | 意味 |
72
+ |---|---|
73
+ | `removable` | 綴りで unlink すると実体が消えるか。link-dir は true、link-file は false (symlink だけが消える) |
74
+ | `until` | `Process` (`/proc/<pid>/fd/…` を通る綴り: プロセスが終われば辿れない)、`Cleanup` (B の実パスの綴り: `cleanup()` まで) |
75
+ | `usableCrossUid` | 別の uid の相手が辿れるか |
76
+ | `usableWithPrivateTmp` | 自分か相手が `/tmp` を隔離していても (systemd の `PrivateTmp` 等) 辿れるか。`/proc` を通る綴りは true、`/tmp`・`/var/tmp` を通る綴りは false |
77
+
78
+ listener の `address()` (node:net) と `unix` (`Bun.listen`) は綴りでなく渡したパスを返す。
79
+
80
+ ### `Options`
81
+
82
+ | 項目 | 意味 |
83
+ |---|---|
84
+ | `usableCrossUid` | 別の uid の相手も辿れる綴りを求める (bind 系だけが見る)。満たせなければ満たさない綴りに落とさず、他の経路へ進む (sockat-ts では `ENAMETOOLONG` になりうる) |
85
+ | `base` | B そのもののパス (アプリが管理する場所。例 `/tmp/app-1000/sockat`)。確かめに外れたらエラーで、自動の置き場に落とさない。B は sockat 専用で、中に他の物を置かない |
86
+
87
+ ### resolve
88
+
89
+ 綴りを自分で標準 (`net.Server.listen`、`Bun.serve({ unix })`、`fetch(url, { unix })` 等) に渡したい時に使う。
90
+
91
+ ```ts
92
+ const f = resolveForBind(path); // 長いパスは Linked の綴り。届かない長さは ENAMETOOLONG
93
+ const server = net.createServer().listen(f.path);
94
+ // listening の後・閉じる前に
95
+ const file = f.socketFile();
96
+ // …
97
+ file.remove();
98
+ ```
99
+
100
+ ```ts
101
+ const f = resolveForConnect(path);
102
+ const socket = net.connect({ path: f.path }); // 何度でも
103
+ f.cleanup(); // 要らなくなったら
104
+ ```
105
+
106
+ ### 置き場に残る物と `sweep`
107
+
108
+ 長いパスの綴りは、利用者ごとの置き場 B の中の、プロセスごとのディレクトリ D と symlink E を通る。**B・D・E はアプリの置き場の外に増える。**
109
+
110
+ | | B | D | E |
111
+ |---|---|---|---|
112
+ | 場所 | `/tmp/sockat-<uid>` → `$XDG_RUNTIME_DIR/sockat` → `$TMPDIR/sockat-<uid>` → ソケットのディレクトリの `.sockat.<乱数>` の順で最初に作れた所。`options.base` を渡せばそこ | B の中の乱数 10 文字 | resolve と bind の E は D の中。既定の connect の E は B の直下で、connect の後すぐ消す |
113
+ | 生きている間 | 消さない | プロセスが共有ロックを掛けて持ち続ける | `cleanup()` まで残る |
114
+ | 片付け | sockat はしない | 死んだプロセスの D は OS の一時ディレクトリの掃除で消える。`sweep()` を呼んだ時だけ、ロックの外れた D を消す | `cleanup()` / `remove()` |
115
+
116
+ - `/tmp/sockat-<uid>` 等の中は、プロセスごとの D (乱数 10 文字) と、その中の綴り用の symlink だけ。生きている D を消しても、綴りが辿れなくなるだけで無関係なファイルには当たらない
117
+ - 既定の `bind` / `listen` は `file` を返さないので、E はプロセスが終わるまで残る。**長いパスに何度も bind する長命のプロセス (セッションごとにソケットを作る daemon 等) は `bindEx` を使い、要らなくなったら `remove()` か `cleanup()` で片付ける**
118
+ - **試験を繰り返す環境 (CI 等) では `sweep()` を呼ぶ**と死んだ D が溜まらない。`sweepBase(base)` は `options.base` の B の分。どちらも自動では呼ばれない
119
+ - **ソケットのディレクトリの B (`.sockat.<乱数>`) と、確かめに外れて落とした B (`sockat-<uid>.<乱数>`) は、`sweep` でも OS の掃除でも消えずに残りうる**
120
+ - **生きている D が消されうる環境**: systemd v242 より古い Linux (RHEL 8 等。`/tmp` の D を 10 日で消す) と、B が macOS の `$TMPDIR` にある時 (dirhelper が 3 日で消しうる)。綴りが辿れなくなるだけ
121
+ - **`PrivateTmp` の相手**: 相手の `/tmp` が隔離されていると、`/tmp` を通る綴りを相手は辿れない。辿れるかは `usableWithPrivateTmp` で分かる
122
+ - **片付けた後の綴りは使わない**。`/tmp` の B は消えた後に他人が同じ名前で作り直しうる
123
+
124
+ ## 使ってはいけない書き方
125
+
126
+ 無関係なファイルを消したり、消し損ねたりする書き方 ([SPEC の「使ってはいけない書き方」](https://github.com/kawaz/sockat/blob/main/docs/SPEC-ja.md#使ってはいけない書き方))。避け方のコードは [test/readme.test.ts](./test/readme.test.ts) で動かしている。
127
+
128
+ | 書き方 | なぜいけないか | 代わりに |
129
+ |---|---|---|
130
+ | `spelling` を見ずに、カーネルが返す綴りでソケットのファイルを `fs.unlinkSync` / `fs.statSync` する (他の言語の相手の `getpeername`、`lsof` の出力等) | link-file の綴りでは symlink が消えるだけでファイルは残る | 渡したパスを持っておいて使う。`b.file.remove()` |
131
+ | `cleanup()` の後やプロセスが終わった後に、古い綴り (`f.path`) を使う | 片付けた後の `/tmp` の B は他人が作り直しうる。`until: "Process"` の綴りはプロセスが終われば辿れない | 綴りは `until` の間だけ使う |
132
+ | 相対パスで bind し、`process.chdir` の後にその相対パスで `fs.unlinkSync` する | 別の場所のファイルに当たる (`CwdRelative`) | bind の前に `path.resolve` で絶対パスにする。`b.file.remove()` |
133
+ | `server.close()` / `listener.stop()` だけでソケットのファイルが消えると当てにする | 閉じると綴りを unlink するので、link-file の綴りでは symlink だけが消えてファイルは残る | `b.file.remove()` か、渡したパスで消す |
134
+ | `b.file.remove()` で listener も閉じると当てにする | `remove()` はファイルを消すだけ | listener は自分で閉じる |
135
+ | `server.close()` の後に `b.file.remove()` を呼ぶ | 閉じた後に作り直された別のファイルを見分けられないことがある | 閉じる前に呼ぶ |
136
+ | `/proc` を通る綴りや `usableCrossUid` が false の綴りを、別の uid の相手に辿らせる | 辿れない | `{ usableCrossUid: true }` を渡し、結果の `spelling` を確かめる |
137
+ | `route`・`base`・`skipped` の文字列で分岐する | 診断用で中身を約束しない | `spelling` で分岐する |
138
+
139
+ ```ts
140
+ // 絶対パスで bind し、閉じる前に remove する
141
+ const b = await bindEx(nodePath.resolve(relative));
142
+ try {
143
+ // …
144
+ } finally {
145
+ b.file.remove();
146
+ b.socket.close();
147
+ }
148
+
149
+ // 別の uid の相手に辿らせる綴りは、満たせたかを確かめる
150
+ const f = resolveForBind(path, { usableCrossUid: true });
151
+ if (f.spelling.kind === "Linked" && !f.spelling.usableCrossUid) {
152
+ throw new Error("no spelling another uid can follow");
153
+ }
154
+ ```
155
+
156
+ ## 長いパスへの届き方
157
+
158
+ 標準にそのまま渡す長さは、Linux は Node 108・Bun 107 バイト、他は 103 (illumos は 107) バイトまで。それを超えるパスは、まずソケットのディレクトリを引き (無ければ `ENOENT`、ディレクトリでなければ `ENOTDIR`。`..` や `.` は文字列で畳まず OS に引かせる)、次の経路を左から試す。経路が実際に bind / connect して失敗したら、そのエラーを返して次を試さない。
159
+
160
+ native の部品が要る経路は作らず、使えない経路として `skipped` に入れて次へ進む (理由は `no native code in sockat-ts`)。
161
+
162
+ | OS | bind | connect |
163
+ |---|---|---|
164
+ | Linux / Android | link-dir (`/proc` を通す綴り → B の実パス) → thread-cwd (作らない) | proc-direct (`/proc` が無ければ relative) → thread-cwd-direct (作らない) → link-file |
165
+ | macOS | link-dir → link-file → thread-cwd (作らない) | relative → widened (作らない) → thread-cwd-direct (作らない) → link-file |
166
+ | FreeBSD | link-dir → at (作らない) | at-direct (作らない) → link-file |
167
+ | NetBSD | link-dir → link-file | relative → link-file |
168
+ | OpenBSD・illumos | link-dir | relative → link-file |
169
+
170
+ - **link-dir**: D の中にソケットのディレクトリを指す E を作り、`B/D/E/<ファイル名>` で bind する。`removable`
171
+ - **link-file**: D の中にソケットのファイルを指す E を作り、`B/D/E` で bind する (bind が symlink を辿る OS だけ)。既定の connect は B の直下の E を通し、connect の後すぐ消す。ファイル名の長さによらず届く
172
+ - **proc-direct**: `/proc/self/fd/<ディレクトリの fd>/<ファイル名>` で connect する
173
+ - **relative**: cwd からの相対パスで connect する (cwd は変えない)
174
+ - D のロック: macOS と BSD は `O_SHLOCK` で開く、Linux は `flock(1)` (util-linux / busybox) に fd を継がせる。**Linux で `flock(1)` が無いと、長いパスの bind と resolve は `ENAMETOOLONG`** (既定の connect は届く)。illumos はロックの手段が無く同じ
175
+
176
+ ### どこから届かなくなるか
177
+
178
+ ディレクトリが標準に渡す長さを超えるほど深い時に、届くファイル名の長さ (バイト。置き場は OS の既定):
179
+
180
+ | OS | bind (`bind`・`bindEx`・`listen`・`resolveForBind`) | connect (`connect`・`resolveForConnect`) |
181
+ |---|---|---|
182
+ | Linux / Android | およそ 76 (`/proc` を通す綴りはおよそ 70) | 255 まで |
183
+ | macOS | 255 まで (link-file) | 255 まで |
184
+ | FreeBSD・OpenBSD | およそ 72 | 255 まで |
185
+ | NetBSD | 255 まで (link-file) | 255 まで |
186
+ | illumos | 届かない (D をロックできない) | 255 まで |
187
+
188
+ B を作れない環境 (置き場が全部書けない等) では、B を通る経路が使えず、connect は proc-direct・relative の分だけ届く。
189
+
190
+ Linux で `/proc` が見えない環境 (空の tmpfs を被せた等) では、Bun 自体が起動時に `abort()` で落ちる (Bun 1.4.4・1.4.5 で確認。sockat を使わない `bun -e 'console.log(1)'` も同じ)。Node はそのまま動き、connect は relative を使う。
191
+
192
+ ## SPEC から外れる点
193
+
194
+ - 作らない経路 (上の表) でしか届かない所に届かない
195
+ - **`bindEx` / `listenEx` の listener も、閉じると綴りを unlink する** (SPEC は「`_ex` の listener は閉じても消さない」。runtime に止める口が無い)。`file.remove()` は閉じる前に呼ぶ
196
+ - `bindEx` / `listenEx` がファイルを覚えられなかった時、短いパスは listener を閉じる時に標準がパスを unlink するので、その間に置き換わった物も消える
197
+ - DGRAM と SEQPACKET は無い (Node と Bun の標準に無い)
198
+ - 短いパスのエラーは標準のまま (Node の listen は無いディレクトリに `EACCES` を返す)。長いパスは SPEC の errno (`ENOENT`)
199
+
200
+ ## ライセンス
201
+
202
+ MIT
package/README.md CHANGED
@@ -1,3 +1,202 @@
1
- # Temporary Holding Version
1
+ # sockat (TypeScript)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > English | [日本語](./README-ja.md)
4
+
5
+ `@kawaz/sockat` lets TypeScript (Node.js 22 or later, and Bun) bind and connect Unix domain sockets at paths longer than `sun_path` (104 bytes on macOS, 108 on Linux). A path the standard library takes goes to it as it is; only a longer one is spelt shorter, naming the same place, and handed to the standard library. No native code.
6
+
7
+ - The behaviour (the language-independent specification): [kawaz/sockat's SPEC](https://github.com/kawaz/sockat/blob/main/docs/SPEC.md)
8
+ - The implementations in other languages: [kawaz/sockat](https://github.com/kawaz/sockat)
9
+
10
+ ## Usage
11
+
12
+ node:net (Node and Bun):
13
+
14
+ ```ts
15
+ import { bind, bindEx, connect } from "@kawaz/sockat";
16
+
17
+ const server = await bind(path); // a net.Server, once it is listening
18
+ server.on("connection", (s) => s.end("hi"));
19
+ const socket = await connect(path); // a net.Socket, once it is connected
20
+ ```
21
+
22
+ Bun's `Bun.listen` / `Bun.connect` (throws at once without Bun):
23
+
24
+ ```ts
25
+ import { connect, listen } from "@kawaz/sockat/bun";
26
+
27
+ const listener = listen({ unix: path, socket: { data(s, d) { s.write(d); } } });
28
+ const socket = await connect({ unix: path, socket: { data() {} } });
29
+ ```
30
+
31
+ | function | returns |
32
+ |---|---|
33
+ | `bind(path)` / `connect(path)` | `net.Server` / `net.Socket` (Promise) |
34
+ | `bindEx(path, options?)` / `connectEx(path, options?)` | `Bound<net.Server>` / `Connected<net.Socket>` |
35
+ | `listen(options)` / `connect(options)` (`/bun`) | `Bun.UnixSocketListener` (sync) / `Bun.Socket` (Promise) |
36
+ | `listenEx(options, sockatOptions?)` / `connectEx(options, sockatOptions?)` (`/bun`) | `Bound<…>` / `Connected<…>` |
37
+ | `resolveForBind(path, options?)` / `resolveForConnect(path, options?)` | `ForBind` / `ForConnect` (sync) |
38
+ | `sweep()` / `sweepBase(path)` | nothing |
39
+
40
+ - An empty path, and a path with a NUL other than a leading one, are a `TypeError` (`code` `ERR_INVALID_ARG_VALUE`). On Linux a path with a leading NUL (abstract) goes to the standard library as it is
41
+ - node:net reads a string that looks like a number (`"0"`, `"8080"`, `"1e3"`, blanks, ...) as a TCP port. sockat puts `./` in front of such a spelling without a `/` (the same file; `Spelling` stays `CwdRelative`, `address()` is the path given). When `./` takes it over the standard length, it is a long path
42
+ - An OS error has Node's shape (`code`, `errno`, `syscall`, `path`; `path` is the path given). The errors of `*Ex` and the resolves also carry `route` (the route that bound / connected and failed, or `null`) and `skipped`
43
+
44
+ ### Removing the socket file (`bindEx` and `file`)
45
+
46
+ ```ts
47
+ const b = await bindEx(path); // b.socket, b.file, b.spelling, b.route, b.base, b.skipped
48
+ // ...
49
+ b.file.remove(); // removes the socket file (does not close the listener); call it before closing
50
+ b.socket.close();
51
+ ```
52
+
53
+ - `b.file` records the socket file's real path and `(st_dev, st_ino)` right after the bind; `remove()` removes it only while the path still names that file. When it cannot be recorded, `bindEx` fails (it removes the spelling's symlink before closing the listener, so what replaced the file stays; for a short path the standard library unlinks the path on close)
54
+ - When the last component is a symlink (bind follows it on macOS and NetBSD), the socket it leads to is recorded and removed; the symlink stays
55
+ - `remove()` also does `cleanup()`, which removes only the symlink (E) the spelling goes through. After a success, calls do nothing; after a failure, the next call tries again
56
+ - A replacement is told apart only while the listener is open: a file removed and made again after the close may get the same `(st_dev, st_ino)`
57
+
58
+ ### What a spelling is good for (`Spelling`)
59
+
60
+ For a long path, the address the kernel keeps (a peer's `getpeername` in another language, `ss -x`, `lsof`, ...) is the spelling bound, not the path given. `spelling` says what it is good for afterwards. Branch on it.
61
+
62
+ | `kind` | spelling |
63
+ |---|---|
64
+ | `Original` | the absolute path itself (an abstract name too) |
65
+ | `CwdRelative` | the relative path itself (with `./` in front too); another place once the cwd changes |
66
+ | `Linked` | through B, D and E in a place, naming the same place as the path |
67
+ | `Dangling` | names nothing (never made by sockat-ts) |
68
+
69
+ `Linked`'s fields:
70
+
71
+ | field | meaning |
72
+ |---|---|
73
+ | `removable` | unlinking the spelling removes the file: true for link-dir, false for link-file (only the symlink goes) |
74
+ | `until` | `Process` (through `/proc/<pid>/fd/…`: until the process ends), `Cleanup` (through B's real path: until `cleanup()`) |
75
+ | `usableCrossUid` | a peer of another uid can follow it |
76
+ | `usableWithPrivateTmp` | a peer can follow it even when either side has a /tmp of its own (systemd's `PrivateTmp`): true through `/proc`, false through `/tmp` or `/var/tmp` |
77
+
78
+ The listener's `address()` (node:net) and `unix` (`Bun.listen`) return the path given, not the spelling.
79
+
80
+ ### `Options`
81
+
82
+ | field | meaning |
83
+ |---|---|
84
+ | `usableCrossUid` | ask for a spelling a peer of another uid can follow (binds only). Where there is none, it does not fall back to one they cannot follow (sockat-ts may then be `ENAMETOOLONG`) |
85
+ | `base` | the path of B itself (a place the application manages, such as `/tmp/app-1000/sockat`). A check that fails is an error, with no fall back to the automatic places. B is sockat's alone: put nothing else in it |
86
+
87
+ ### resolve
88
+
89
+ To hand the spelling to a standard library yourself (`net.Server.listen`, `Bun.serve({ unix })`, `fetch(url, { unix })`, ...):
90
+
91
+ ```ts
92
+ const f = resolveForBind(path); // a Linked spelling for a long path; ENAMETOOLONG where none fits
93
+ const server = net.createServer().listen(f.path);
94
+ // after it listens, before it is closed
95
+ const file = f.socketFile();
96
+ // ...
97
+ file.remove();
98
+ ```
99
+
100
+ ```ts
101
+ const f = resolveForConnect(path);
102
+ const socket = net.connect({ path: f.path }); // as many times as you like
103
+ f.cleanup(); // once done
104
+ ```
105
+
106
+ ### What is left in the places, and `sweep`
107
+
108
+ The spelling of a long path goes through a directory of the user's, B, a directory of the process in it, D, and a symlink, E. **B, D and E grow outside the application's own places.**
109
+
110
+ | | B | D | E |
111
+ |---|---|---|---|
112
+ | where | the first of `/tmp/sockat-<uid>`, `$XDG_RUNTIME_DIR/sockat`, `$TMPDIR/sockat-<uid>`, `.sockat.<random>` in the socket's directory where it can be made; `options.base` when given | 10 random characters in B | in D for resolves and binds; right in B for the default connect, removed right after the connect |
113
+ | while alive | stays | the process holds it with a shared lock | stays until `cleanup()` |
114
+ | cleaned by | not sockat | the system's cleaning of temporary directories once the process has ended; `sweep()` removes unlocked D when called | `cleanup()` / `remove()` |
115
+
116
+ - What is in `/tmp/sockat-<uid>` and the like: one D (10 random characters) per process, and the spellings' symlinks in it. Removing a live D only makes its spellings name nothing; they never reach an unrelated file
117
+ - The default `bind` / `listen` gives no `file`, so its E stays until the process ends. **A long-lived process that binds long paths again and again (a daemon making a socket per session) uses `bindEx` and `remove()` or `cleanup()` once a socket is no longer needed**
118
+ - **Where tests run again and again (CI), call `sweep()`** so dead D do not pile up. `sweepBase(base)` does it for `options.base`'s B. Neither is called for you
119
+ - **A B in the socket's directory (`.sockat.<random>`) and a B fallen back to (`sockat-<uid>.<random>`) may stay, through `sweep` and the system's cleaning alike**
120
+ - **Where a live D may be removed**: Linux with systemd older than v242 (RHEL 8: `/tmp` after 10 days) and a B in macOS's `$TMPDIR` (dirhelper, after 3 days). Its spellings then name nothing
121
+ - **A peer with `PrivateTmp`**: a peer whose `/tmp` is its own cannot follow a spelling through `/tmp`. `usableWithPrivateTmp` tells
122
+ - **Do not use a spelling after its cleanup**: a B in `/tmp` may be made again by someone else once gone
123
+
124
+ ## Ways not to use it
125
+
126
+ Ways that remove an unrelated file or fail to remove one ([SPEC's "使ってはいけない書き方"](https://github.com/kawaz/sockat/blob/main/docs/SPEC.md)). The code that avoids them runs in [test/readme.test.ts](./test/readme.test.ts).
127
+
128
+ | way | why not | instead |
129
+ |---|---|---|
130
+ | `fs.unlinkSync` / `fs.statSync` of the spelling the kernel gives (a peer's `getpeername`, `lsof`'s output, ...) without looking at `spelling` | for a link-file spelling only the symlink goes and the file stays | keep the path given and use it; `b.file.remove()` |
131
+ | use an old spelling (`f.path`) after `cleanup()` or after the process has ended | a B in `/tmp` may be made again by someone else; an `until: "Process"` spelling ends with the process | use a spelling only within its `until` |
132
+ | bind a relative path, `process.chdir`, then `fs.unlinkSync` the relative path | it names a file elsewhere (`CwdRelative`) | make it absolute with `path.resolve` before the bind; `b.file.remove()` |
133
+ | count on `server.close()` / `listener.stop()` to remove the socket file | closing unlinks the spelling: for a link-file spelling only the symlink goes | `b.file.remove()`, or remove the path given |
134
+ | count on `b.file.remove()` to close the listener | it only removes the file | close the listener yourself |
135
+ | call `b.file.remove()` after `server.close()` | a file made again after the close may not be told apart | call it before closing |
136
+ | hand a `/proc` spelling, or one whose `usableCrossUid` is false, to a peer of another uid | it cannot follow it | pass `{ usableCrossUid: true }` and check the resulting `spelling` |
137
+ | branch on `route`, `base` or `skipped` | for diagnostics; not a promise | branch on `spelling` |
138
+
139
+ ```ts
140
+ // bind an absolute path, and remove before closing
141
+ const b = await bindEx(nodePath.resolve(relative));
142
+ try {
143
+ // ...
144
+ } finally {
145
+ b.file.remove();
146
+ b.socket.close();
147
+ }
148
+
149
+ // check that a spelling for a peer of another uid was met
150
+ const f = resolveForBind(path, { usableCrossUid: true });
151
+ if (f.spelling.kind === "Linked" && !f.spelling.usableCrossUid) {
152
+ throw new Error("no spelling another uid can follow");
153
+ }
154
+ ```
155
+
156
+ ## How a long path is reached
157
+
158
+ The standard length is 108 bytes for Node and 107 for Bun on Linux, 103 elsewhere (107 on illumos). A longer path first has its directory looked up (`ENOENT` when missing, `ENOTDIR` when not a directory; `..` and `.` are never folded as a string, the system looks them up), then the routes are tried from the left. A route that binds / connects and fails returns its error; no later route is tried.
159
+
160
+ A route that needs native code is not made: it is passed over as unusable and named in `skipped` (reason `no native code in sockat-ts`).
161
+
162
+ | system | bind | connect |
163
+ |---|---|---|
164
+ | Linux / Android | link-dir (through `/proc`, then B's real path), thread-cwd (not made) | proc-direct (relative without `/proc`), thread-cwd-direct (not made), link-file |
165
+ | macOS | link-dir, link-file, thread-cwd (not made) | relative, widened (not made), thread-cwd-direct (not made), link-file |
166
+ | FreeBSD | link-dir, at (not made) | at-direct (not made), link-file |
167
+ | NetBSD | link-dir, link-file | relative, link-file |
168
+ | OpenBSD, illumos | link-dir | relative, link-file |
169
+
170
+ - **link-dir**: an E in D pointing to the socket's directory; binds `B/D/E/<name>`. `removable`
171
+ - **link-file**: an E in D pointing to the socket file; binds `B/D/E` (only where bind follows a symlink). The default connect goes through an E right in B and removes it right after. Reaches any file name length
172
+ - **proc-direct**: connects `/proc/self/fd/<the directory's fd>/<name>`
173
+ - **relative**: connects the path relative to the cwd (the cwd is not changed)
174
+ - D is locked by opening it `O_SHLOCK` on macOS and the BSDs, and by `flock(1)` (util-linux / busybox) on an fd handed to it on Linux. **On a Linux without `flock(1)`, the bind of a long path and the resolves are `ENAMETOOLONG`** (the default connect still reaches it); so on illumos, which has no way to lock
175
+
176
+ ### Where it stops reaching
177
+
178
+ The longest file name reached (bytes) when the directory alone is over the standard length, the places as the system has them:
179
+
180
+ | system | bind (`bind`, `bindEx`, `listen`, `resolveForBind`) | connect (`connect`, `resolveForConnect`) |
181
+ |---|---|---|
182
+ | Linux / Android | about 76 (about 70 through `/proc`) | 255 |
183
+ | macOS | 255 (link-file) | 255 |
184
+ | FreeBSD, OpenBSD | about 72 | 255 |
185
+ | NetBSD | 255 (link-file) | 255 |
186
+ | illumos | none (D cannot be locked) | 255 |
187
+
188
+ Where no B can be made (no place can be written to), the routes through B cannot be used, and a connect reaches only what proc-direct and relative reach.
189
+
190
+ On a Linux where `/proc` is not visible (an empty tmpfs mounted over it, for example), Bun itself aborts at startup (seen with Bun 1.4.4 and 1.4.5; a plain `bun -e 'console.log(1)'` without sockat does the same). Node runs, and its connect uses relative.
191
+
192
+ ## Where it departs from SPEC
193
+
194
+ - What only the routes not made (above) reach is not reached
195
+ - **The listener of `bindEx` / `listenEx` too unlinks its spelling when closed** (SPEC: "the listener of `_ex` removes nothing when closed"; the runtimes give no way to stop it). Call `file.remove()` before closing it
196
+ - When `bindEx` / `listenEx` cannot record the file of a short path, the standard library unlinks the path as the listener is closed, so whatever replaced the socket goes too
197
+ - No DGRAM and no SEQPACKET (the standard libraries of Node and Bun have none)
198
+ - The errors of a short path are the standard library's (Node's listen says `EACCES` for a missing directory); a long path's are SPEC's errno (`ENOENT`)
199
+
200
+ ## License
201
+
202
+ MIT
package/dist/bind.d.ts ADDED
@@ -0,0 +1,54 @@
1
+ import { type CallSite, type Trace, Unusable } from "./errors.ts";
2
+ import { type Outcome, type RouteName, type SocketDir, type StandardSpelling } from "./route.ts";
3
+ import type { Options, Spelling } from "./types.ts";
4
+ import { type Base, type Link, type World } from "./world.ts";
5
+ /** What a bind produced besides the listener. */
6
+ export interface BindResult {
7
+ readonly route: RouteName;
8
+ readonly spelling: Spelling;
9
+ /** The diagnostics' base; null for a spelling through no B. */
10
+ readonly base: string | null;
11
+ /** The E kept for the spelling (link-dir, link-file), which SocketFile cleans up. */
12
+ readonly link: Link | null;
13
+ /** The spelling handed to the standard. */
14
+ readonly spelt: string;
15
+ }
16
+ /** One bind, or one resolve, of a long path. */
17
+ export interface BindCall {
18
+ readonly w: World;
19
+ readonly path: string;
20
+ readonly dir: SocketDir;
21
+ readonly opts: Options;
22
+ readonly site: CallSite;
23
+ /** The B in which D could not be made during this call (not tried again in it). */
24
+ readonly noD: Set<Base>;
25
+ }
26
+ /** Looks up the socket's directory (lookUpDir) and starts a bind call. */
27
+ export declare function newBindCall(w: World, path: string, opts: Options, site: CallSite): BindCall;
28
+ /** A spelling through a resolve E. */
29
+ export interface Linked {
30
+ readonly spelling: string;
31
+ readonly link: Link;
32
+ readonly sp: Spelling;
33
+ readonly base: string;
34
+ }
35
+ /**
36
+ * link-dir's spelling <B>/<D>/<E>/<name>, E a symlink to the socket's
37
+ * directory (its real path), B spelt by procB (Linux with /proc, not for
38
+ * usableCrossUid) or its real path, the first that fits.
39
+ */
40
+ export declare function linkDirSpelling(c: BindCall): Linked | Unusable;
41
+ /**
42
+ * link-file's spelling <B>/<D>/<E>, E a symlink to target (the socket file),
43
+ * B spelt by procB when useProc (a connect's resolve) or its real path.
44
+ */
45
+ export declare function linkFileSpelling(c: BindCall, target: string, useProc: boolean): Linked | Unusable;
46
+ /**
47
+ * The bind of path, as the steps the standard takes: yields each spelling to
48
+ * bind (and listen) and gets what the standard did with it. A path the
49
+ * standard takes, and an abstract name, are yielded as they are; their
50
+ * failure is the standard's own error. A long path takes the bind order; a
51
+ * route that bound and failed removes its E and throws the standard's errno
52
+ * with the caller's path. ENAMETOOLONG when no route can be used.
53
+ */
54
+ export declare function bindSteps(w: World, path: string, opts: Options, trace: Trace, syscall: string, spell: StandardSpelling): Generator<string, BindResult, Outcome>;