sigelo-contact 0.1.14 → 0.1.21
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/README.md +13 -10
- package/call.mjs +831 -0
- package/carrier.mjs +1013 -112
- package/control.mjs +81 -22
- package/device.mjs +1 -1
- package/enrol.mjs +214 -35
- package/gen-carrier.mjs +4 -4
- package/gen-device.mjs +2 -2
- package/gen-envelope.mjs +3 -3
- package/gen-invite.mjs +3 -3
- package/gen-short.mjs +3 -3
- package/group.mjs +28 -9
- package/invite.mjs +63 -13
- package/kdf.mjs +1 -1
- package/link.mjs +1 -1
- package/package.json +34 -7
- package/page.mjs +1018 -81
- package/photo.mjs +37 -0
- package/platform-node.mjs +110 -13
- package/prekeys.mjs +10 -2
- package/public.mjs +93 -0
- package/relays.mjs +1 -1
- package/restore.mjs +3 -3
- package/rtc-web.mjs +109 -0
- package/short.mjs +19 -3
- package/store.mjs +126 -10
- package/test-carrier.mjs +121 -18
- package/test-device.mjs +1 -1
- package/test-enrol.mjs +123 -8
- package/test-envelope.mjs +16 -3
- package/test-file.mjs +5 -5
- package/test-group.mjs +48 -7
- package/test-invite.mjs +15 -2
- package/test-link.mjs +6 -6
- package/test-platform.mjs +5 -5
- package/test-presence.mjs +5 -5
- package/test-push.mjs +136 -0
- package/test-relay-lane.mjs +323 -0
- package/test-short.mjs +35 -12
- package/test-tier.mjs +6 -6
- package/test-transfer-web.mjs +313 -0
- package/test-transfer.mjs +51 -11
- package/test-voice.mjs +161 -0
- package/test-ws.mjs +5 -5
- package/transfer-engine.mjs +858 -0
- package/transfer-node.mjs +254 -641
- package/transfer-web.mjs +80 -0
- package/transfer.mjs +25 -6
- package/voice-web.mjs +113 -0
- package/voice.mjs +70 -0
- package/words-lock.mjs +25 -10
|
@@ -0,0 +1,858 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Transfers, the part every host shares (design/transfer.md §4, §10; apps/agent/TRANSFER.md): the
|
|
3
|
+
// records, the consent and the accept rule, the verbs and the Engine, with the disk, the file sent and
|
|
4
|
+
// Tor behind `io`. Node: transfer-node.mjs (fs, a tor daemon). The phone: transfer-web.mjs (the bridge
|
|
5
|
+
// holds the bytes; no Tor). The protocol is transfer.mjs's; the carrier is carrier.mjs's, in both.
|
|
6
|
+
//
|
|
7
|
+
// const io = { lock(fn), read() → text | null, write(text), the records file, under its lock
|
|
8
|
+
// have: { read(id) → bytes | null, write(id, bits) }, list: { read(id, side), write(id, side, bytes), drop(id, side) },
|
|
9
|
+
// part: { open(id) → { write(bytes, pos), flush(), close() }, drop(id), sha256(id) → hex, exists?(id) },
|
|
10
|
+
// free() → bytes free (sync; Infinity: unknown), land(r, c) → the place it was saved (a path, a content URI),
|
|
11
|
+
// prepare({ path | doc }) → { file, name, size, mtimeMs, hashes, whole }, source(r) → { read(i), close() },
|
|
12
|
+
// changed(r) → true when the file sent is not the one hashed (size or modification time moved),
|
|
13
|
+
// tor: null | { caps(), serve(engine, side, r, a), connect(engine, side, r, x, a), close(a) },
|
|
14
|
+
// flushEach: chunks between flushes (Node 8; the phone 1: the bitmap saved after every chunk) }
|
|
15
|
+
//
|
|
16
|
+
// The records file: { v, out: { id: sender's record }, in: { id: receiver's record }, direct: { DID: true|false },
|
|
17
|
+
// auto: { DID: MB (0: always ask) }, settings: { tor, prefer, auto_mb, keep_location } }.
|
|
18
|
+
//
|
|
19
|
+
// The accept rule (design §10.2, decided 2026-11-13): a file lands without a question up to the size set
|
|
20
|
+
// (settings.auto_mb, default 25 MB; per contact auto[DID]) from own agents and own contacts (tier own,
|
|
21
|
+
// ours) and from friends whose four words were compared (compared(did), the page's), when the disk has
|
|
22
|
+
// room; larger, or from anyone else (words not compared, a public-code joiner, quiet), it is asked. The
|
|
23
|
+
// direct switch picks the lane, not the yes (2026-11-25): off, it comes over Tor or the relay lane.
|
|
24
|
+
//
|
|
25
|
+
// The relay lane (0.1.19): a file of at most RELAY_MAX (8 MiB, send-file's) to an own agent or contact, or to a friend
|
|
26
|
+
// whose words were compared, that cannot go direct (no path, no Tor: the end no_path) or whose channel dropped and did
|
|
27
|
+
// not come back within fallbackMs (20 s), goes over sigelo-file/0 instead, once, without a question (Engine.relay): the
|
|
28
|
+
// receiver is told `end relay` first (its record: relayed, the partial dropped) and, where a page runs, its record is
|
|
29
|
+
// done once the file comes (Engine.superseded). Larger, or to anyone else: as before; the page offers Retry (retry) or,
|
|
30
|
+
// up to 8 MiB, Send over the relay. A channel that moves no byte for stallMs (30 s) counts as dropped; a receiver's
|
|
31
|
+
// record active with nothing for STALE_S (10 minutes) is listed as interrupted, and resume takes it again.
|
|
32
|
+
//
|
|
33
|
+
// "Always relay my media" (design/calls.md §6, 2026-11-26): policy() "relay" (the page's setting) or env
|
|
34
|
+
// SIGELO_ICE_POLICY=relay: the direct lane only through the relay's TURN (iceTransportPolicy relay, relayed candidates
|
|
35
|
+
// only in the SDP: rtc-web.mjs, apps/transfer/rtc.mjs); with no TURN to be had the direct lane is left out at once
|
|
36
|
+
// (RELAY_ONLY, reason relay_only on the receiver's record) and the file goes over Tor or the relay lane as without one.
|
|
37
|
+
// A record's `relayed` (true | false) says whether the direct lane's selected candidate pair was relayed (getStats, as
|
|
38
|
+
// the call screen's "Via relay").
|
|
39
|
+
import { concatBytes } from '@noble/hashes/utils.js';
|
|
40
|
+
import { TRANSFER_SEND } from './carrier.mjs';
|
|
41
|
+
import { FILE_LABEL, MAX_FILE, safeName, sha256Hex } from './file.mjs';
|
|
42
|
+
import { MsgError, fail } from './kdf.mjs';
|
|
43
|
+
import { RELAY_ONLY } from './call.mjs';
|
|
44
|
+
import {
|
|
45
|
+
ANSWER_WAIT, AUTO_MB, CHUNK, DAY, GATHER_MS, ICE_MS, MANIFEST_TTL, MAX_SIZE, Have, Pull, Serve, TRANSFER_LABEL, WAIT_ALL, WAIT_CONTACT,
|
|
46
|
+
acceptRule, channelLabel, checkMessage, listOf, manifest, noPath, pathOrder, torRoles,
|
|
47
|
+
} from './transfer.mjs';
|
|
48
|
+
|
|
49
|
+
export const FILE_V = 'sigelo-transfers/1';
|
|
50
|
+
export { TRANSFER_LABEL };
|
|
51
|
+
export { RELAY_ONLY };
|
|
52
|
+
const KEPT = 30 * DAY, RETRIES_AUTO = 3, RETRY_MS = 5000, STUN_PORT = 3478;
|
|
53
|
+
export const FREE_MARGIN = 64 * CHUNK;
|
|
54
|
+
export const RELAY_MAX = MAX_FILE, FALLBACK_MS = 20_000, STALL_MS = 30_000, STALE_S = 600;
|
|
55
|
+
export const STATES_LIVE_IN = ['accepted', 'offering', 'active'], STATES_LIVE_OUT = ['active', 'relaying'];
|
|
56
|
+
const ENDED = ['done', 'declined', 'cancelled', 'failed', 'expired', 'relayed'];
|
|
57
|
+
const nowS = (carrier) => (carrier?.clock ? carrier.clock() : Math.floor(Date.now() / 1000));
|
|
58
|
+
const later = (f) => setTimeout(f, 0);
|
|
59
|
+
|
|
60
|
+
// ---------------------------------------------------------------- the records
|
|
61
|
+
|
|
62
|
+
/** Load, purge, change (fn), save, under the file's lock. → fn's result. */
|
|
63
|
+
export function state(io, now, fn = () => undefined) {
|
|
64
|
+
return io.lock(() => {
|
|
65
|
+
let s = { v: FILE_V, out: {}, in: {}, direct: {}, auto: {}, settings: {} };
|
|
66
|
+
const text = io.read();
|
|
67
|
+
if (text !== null) {
|
|
68
|
+
try { s = JSON.parse(text); } catch (e) { fail('transfer_file', `the transfers file does not parse (${e.message}): delete it to drop the transfers in progress`); }
|
|
69
|
+
if (s?.v !== FILE_V || typeof s.out !== 'object' || typeof s.in !== 'object') fail('transfer_file', `the transfers file is not a ${FILE_V} file`);
|
|
70
|
+
s.direct ??= {}; s.settings ??= {}; s.auto ??= {};
|
|
71
|
+
}
|
|
72
|
+
const before = JSON.stringify(s);
|
|
73
|
+
for (const side of ['out', 'in']) for (const [k, r] of Object.entries(s[side])) if (ENDED.includes(r.state) && r.at + KEPT < now) delete s[side][k];
|
|
74
|
+
const out = fn(s);
|
|
75
|
+
if (JSON.stringify(s) !== before) io.write(JSON.stringify(s, null, 2));
|
|
76
|
+
return out;
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The live contact named (DID or name), or not_contact. */
|
|
81
|
+
export function contactOf(carrier, who) {
|
|
82
|
+
const cs = carrier.contacts().contacts.filter((c) => !c.revoked);
|
|
83
|
+
const hit = typeof who === 'string' && who.startsWith('did:sigelo:') ? cs.filter((c) => c.did === who || c.chain?.includes(who)) : cs.filter((c) => c.name === who);
|
|
84
|
+
if (hit.length === 0) fail('not_contact', `${JSON.stringify(who)} is not a contact`);
|
|
85
|
+
if (hit.length > 1) fail('name', `${hit.length} contacts are named ${JSON.stringify(who)}: use the DID`);
|
|
86
|
+
return hit[0];
|
|
87
|
+
}
|
|
88
|
+
const own = (c) => c.tier === 'own' || c.ours === true;
|
|
89
|
+
/** May this contact learn this agent's addresses (direct)? true, false, or null: not asked yet (never for own). */
|
|
90
|
+
export const directFor = (s, c) => (Object.hasOwn(s.direct, c.did) ? s.direct[c.did] : own(c) ? true : null);
|
|
91
|
+
const decideDirect = (s, c, direct) => {
|
|
92
|
+
if (direct === true || direct === false) { s.direct[c.did] = direct; return direct; }
|
|
93
|
+
const d = directFor(s, c);
|
|
94
|
+
if (d === null) fail('direct_ask', `direct shows ${c.name} this device's public and local addresses; say once whether it may (direct on or off for ${c.name}); off: Tor only`);
|
|
95
|
+
return d;
|
|
96
|
+
};
|
|
97
|
+
/** How far a contact is known (the accept rule): own, compared (a friend whose words were compared), or other. */
|
|
98
|
+
export function trustOf(c, compared = () => false) {
|
|
99
|
+
if (own(c)) return 'own';
|
|
100
|
+
if (c.tier === 'quiet' || (c.via !== undefined && c.via !== null)) return 'other';
|
|
101
|
+
return compared(c.did) ? 'compared' : 'other';
|
|
102
|
+
}
|
|
103
|
+
export const autoDefault = (s) => (Number.isFinite(s.settings.auto_mb) && s.settings.auto_mb >= 0 ? s.settings.auto_mb : AUTO_MB);
|
|
104
|
+
const settingsOf = (s) => ({ tor: s.settings.tor !== false, prefer: s.settings.prefer === 'private' ? 'private' : 'fast', auto_mb: autoDefault(s), keep_location: s.settings.keep_location === true });
|
|
105
|
+
const sendMsg = (carrier, to, content, local) => carrier.send(to, content, { label: TRANSFER_LABEL, internal: TRANSFER_SEND, local });
|
|
106
|
+
|
|
107
|
+
// ---------------------------------------------------------------- the verbs
|
|
108
|
+
|
|
109
|
+
/** The sender: the file hashed (io.prepare), its manifest sent. group: the gid of a group's fan-out (kept here only). */
|
|
110
|
+
export async function send({ carrier, io, to, path, doc, via = 'auto', direct, local = false, group = null }) {
|
|
111
|
+
if (via !== 'auto' && via !== 'tor') fail('usage', 'via: auto or tor');
|
|
112
|
+
const c = contactOf(carrier, to);
|
|
113
|
+
state(io, nowS(carrier), (s) => decideDirect(s, c, direct));
|
|
114
|
+
return sendTo({ carrier, io, to: c.did, f: await io.prepare({ path, doc }), via, direct, local, group });
|
|
115
|
+
}
|
|
116
|
+
/** The file sent, hashed once: → { file, name, size, mtimeMs, hashes, whole } (sendTo, fanOut take it). */
|
|
117
|
+
export const prepare = ({ io, path, doc }) => io.prepare({ path, doc });
|
|
118
|
+
/** A file prepared, offered to one contact (the direct switch settled first). */
|
|
119
|
+
export async function sendTo({ carrier, io, to, f, via = 'auto', direct, local = false, group = null }) {
|
|
120
|
+
if (via !== 'auto' && via !== 'tor') fail('usage', 'via: auto or tor');
|
|
121
|
+
const c = contactOf(carrier, to), now = nowS(carrier);
|
|
122
|
+
state(io, now, (s) => decideDirect(s, c, direct));
|
|
123
|
+
return sendPrepared({ carrier, io, c, f, via, local, group, now });
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* A group's file (design §10.3): one transfer per member this side is paired with, the file hashed once
|
|
127
|
+
* (f); members reached only through the creator are listed unpaired (they get the preview alone).
|
|
128
|
+
* members: [{ did, name, contact }] (the others; contact: paired here). Before anything is sent, a member
|
|
129
|
+
* whose direct switch is not set and no direct given: direct_ask naming them. → { sent, unpaired, failed }.
|
|
130
|
+
*/
|
|
131
|
+
export async function fanOut({ carrier, io, members, f, direct, via = 'auto', local = false, group }) {
|
|
132
|
+
const paired = [], unpaired = [];
|
|
133
|
+
for (const m of members) {
|
|
134
|
+
let c = null;
|
|
135
|
+
if (m.contact) { try { c = contactOf(carrier, m.did); } catch {} }
|
|
136
|
+
(c ? paired : unpaired).push(c ? { did: c.did, name: c.name, c } : { did: m.did, name: m.name });
|
|
137
|
+
}
|
|
138
|
+
if (direct !== true && direct !== false) {
|
|
139
|
+
const ask = state(io, nowS(carrier), (s) => paired.filter((p) => directFor(s, p.c) === null).map((p) => p.name));
|
|
140
|
+
if (ask.length) fail('direct_ask', `direct shows ${ask.join(', ')} this device's public and local addresses; say once whether they may (direct on or off); off: Tor only`);
|
|
141
|
+
}
|
|
142
|
+
const sent = [], failed = [];
|
|
143
|
+
for (const p of paired) {
|
|
144
|
+
try { const r = await sendTo({ carrier, io, to: p.did, f, via, direct: direct ?? undefined, local, group }); sent.push({ did: p.did, name: p.name, id: r.id }); }
|
|
145
|
+
catch (e) { failed.push({ did: p.did, name: p.name, check: e.check ?? 'send', detail: e.message }); }
|
|
146
|
+
}
|
|
147
|
+
return { sent, unpaired: unpaired.map(({ did, name }) => ({ did, name })), failed };
|
|
148
|
+
}
|
|
149
|
+
/** A file hashed once, offered to contact c (a group's members share one f). */
|
|
150
|
+
export async function sendPrepared({ carrier, io, c, f, via = 'auto', local = false, group = null, now = nowS(carrier) }) {
|
|
151
|
+
if (f.size > MAX_SIZE) fail('transfer_too_large', `${f.size} bytes: at most ${MAX_SIZE} (16 GiB) a file`);
|
|
152
|
+
const m = manifest({ name: safeName(f.name), size: f.size, sha256: f.whole, hashes: f.hashes, now });
|
|
153
|
+
io.list.write(m.id, 'out', f.hashes);
|
|
154
|
+
const rec = { id: m.id, to: c.did, contact: c.name, file: f.file, name: m.name, size: m.size, mtimeMs: f.mtimeMs, sha256: m.sha256, chunks: m.chunks, list: m.list, exp: m.exp, via, state: 'offered', attempt: 0, at: now, sent: 0, ...(group && { group }) };
|
|
155
|
+
state(io, now, (s) => { s.out[m.id] = rec; });
|
|
156
|
+
try { await sendMsg(carrier, c.did, m, local); } catch (e) {
|
|
157
|
+
state(io, now, (s) => { s.out[m.id].state = 'failed'; s.out[m.id].reason = e.check ?? 'send'; s.out[m.id].detail = e.message; });
|
|
158
|
+
throw e;
|
|
159
|
+
}
|
|
160
|
+
return rec;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const recIn = (s, id) => s.in[id] ?? fail('transfer_unknown', `no transfer ${id} offered here`);
|
|
164
|
+
/** Either side's record: → { side, r }. */
|
|
165
|
+
const either = (s, id) => (s.in[id] ? { side: 'in', r: s.in[id] } : s.out[id] ? { side: 'out', r: s.out[id] } : fail('transfer_unknown', `no transfer ${id}`));
|
|
166
|
+
const haveOf = (io, r) => { const b = io.have.read(r.id); try { return new Have(r.chunks, b ?? undefined); } catch { return new Have(r.chunks); } };
|
|
167
|
+
/** Free disk for a record (in s), or disk_full. */
|
|
168
|
+
const room = (io, r, promised = 0) => {
|
|
169
|
+
const need = r.size - haveOf(io, r).bytes(r.size), free = io.free();
|
|
170
|
+
if (free < need + promised + FREE_MARGIN) fail('disk_full', `${r.name} needs ${need} bytes more here, ${free} are free${promised ? ` (${promised} promised to files accepted before)` : ''}`);
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
/** The receiver's yes to a manifest (or a resume of one that stopped): free disk checked, the direct switch settled. */
|
|
174
|
+
export function accept({ carrier, io, id, direct, via }) {
|
|
175
|
+
const now = nowS(carrier);
|
|
176
|
+
return state(io, now, (s) => {
|
|
177
|
+
const r = recIn(s, id);
|
|
178
|
+
if (!['asked', 'interrupted', 'failed'].includes(r.state) || (r.state === 'failed' && !['no_path', 'cancelled', 'ice_timeout', 'tor', 'land'].includes(r.reason))) fail('transfer_state', `transfer ${id} is ${r.state}${r.reason ? ` (${r.reason})` : ''}`);
|
|
179
|
+
if (r.exp <= now) fail('transfer_expired', `the offer of ${r.name} expired`);
|
|
180
|
+
const c = contactOf(carrier, r.from);
|
|
181
|
+
decideDirect(s, c, direct);
|
|
182
|
+
room(io, r);
|
|
183
|
+
if (via === 'tor' || via === 'auto') r.via = via;
|
|
184
|
+
r.state = 'accepted'; r.auto = 0; r.at = now; delete r.reason; delete r.detail;
|
|
185
|
+
return { ...r };
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* The receiver's resume: accept's, and also a transfer that is accepted, offering or active but stuck (the channel
|
|
190
|
+
* went and nothing came back, 0.1.19: it answered "is active (drop)" and did nothing): offered again (restart: the
|
|
191
|
+
* engine drops what it holds of it first); only the chunks missing are asked.
|
|
192
|
+
*/
|
|
193
|
+
export function resume({ carrier, io, id, direct, via }) {
|
|
194
|
+
const now = nowS(carrier);
|
|
195
|
+
const live = state(io, now, (s) => STATES_LIVE_IN.includes(recIn(s, id).state));
|
|
196
|
+
if (!live) return accept({ carrier, io, id, direct, via });
|
|
197
|
+
return state(io, now, (s) => {
|
|
198
|
+
const r = recIn(s, id);
|
|
199
|
+
if (r.exp <= now) fail('transfer_expired', `the offer of ${r.name} expired`);
|
|
200
|
+
decideDirect(s, contactOf(carrier, r.from), direct);
|
|
201
|
+
if (via === 'tor' || via === 'auto') r.via = via;
|
|
202
|
+
Object.assign(r, { state: 'accepted', restart: true, auto: 0, at: now });
|
|
203
|
+
delete r.reason; delete r.detail; delete r.retryAt;
|
|
204
|
+
return { ...r };
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
/** Stuck: active with no byte for STALE_S (an offer unanswered lapses on its own, ANSWER_WAIT). */
|
|
208
|
+
const stale = (r, now) => r.state === 'active' && now - Math.max(r.last ?? 0, r.offerAt ?? 0, r.at ?? 0) > STALE_S;
|
|
209
|
+
const staleDetail = () => `nothing came for over ${STALE_S / 60} minutes: resume it`;
|
|
210
|
+
/**
|
|
211
|
+
* The sender's Retry: the transfer ended here or there (failed, expired, a drop), so the file is offered afresh: the
|
|
212
|
+
* old one cancelled (the receiver told), the file read again (it must still be there), a new manifest. → the new record.
|
|
213
|
+
*/
|
|
214
|
+
export async function retry({ carrier, io, id, local = false, engine = null }) {
|
|
215
|
+
const now = nowS(carrier);
|
|
216
|
+
const r = state(io, now, (s) => {
|
|
217
|
+
const x = s.out[id] ?? fail('transfer_unknown', `no transfer ${id} sent from here`);
|
|
218
|
+
if (['done', 'relaying', 'cancelled', 'declined'].includes(x.state)) fail('transfer_state', `transfer ${id} is ${x.state}`);
|
|
219
|
+
return { ...x };
|
|
220
|
+
});
|
|
221
|
+
const f = await io.prepare({ path: r.file, doc: r.file });
|
|
222
|
+
engine?.drop(id, 'cancelled');
|
|
223
|
+
state(io, now, (s) => { if (s.out[id]) Object.assign(s.out[id], { state: 'cancelled', at: now, retried: true }); });
|
|
224
|
+
await sendMsg(carrier, r.to, { typ: 'end', id, reason: 'cancelled' }, local).catch(() => {});
|
|
225
|
+
const c = contactOf(carrier, r.to);
|
|
226
|
+
return sendPrepared({ carrier, io, c, f, via: r.via ?? 'auto', local, group: r.group ?? null, now });
|
|
227
|
+
}
|
|
228
|
+
/** The receiver's no: the sender is told declined; nothing was written. */
|
|
229
|
+
export async function decline({ carrier, io, id, local = false }) {
|
|
230
|
+
const now = nowS(carrier);
|
|
231
|
+
const r = state(io, now, (s) => {
|
|
232
|
+
const x = recIn(s, id);
|
|
233
|
+
if (x.state !== 'asked') fail('transfer_state', `transfer ${id} is ${x.state}`);
|
|
234
|
+
x.state = 'declined'; x.at = now;
|
|
235
|
+
return { ...x };
|
|
236
|
+
});
|
|
237
|
+
await sendMsg(carrier, r.from, { typ: 'end', id, reason: 'declined' }, local).catch(() => {});
|
|
238
|
+
return r;
|
|
239
|
+
}
|
|
240
|
+
/** Either side stops a transfer: the other is told cancelled; the receiver's partials go. */
|
|
241
|
+
export async function cancel({ carrier, io, id, local = false, engine = null }) {
|
|
242
|
+
const now = nowS(carrier);
|
|
243
|
+
const { side, r } = state(io, now, (s) => {
|
|
244
|
+
const x = either(s, id);
|
|
245
|
+
if (['done', 'declined', 'cancelled', 'expired'].includes(x.r.state)) fail('transfer_state', `transfer ${id} is ${x.r.state}`);
|
|
246
|
+
x.r.state = 'cancelled'; x.r.at = now;
|
|
247
|
+
return { side: x.side, r: { ...x.r } };
|
|
248
|
+
});
|
|
249
|
+
engine?.drop(id, 'cancelled');
|
|
250
|
+
if (side === 'in') dropPartial(io, id);
|
|
251
|
+
await sendMsg(carrier, side === 'in' ? r.from : r.to, { typ: 'end', id, reason: 'cancelled' }, local).catch(() => {});
|
|
252
|
+
return r;
|
|
253
|
+
}
|
|
254
|
+
/** A finished, failed or unwanted record and its partials gone, here only. */
|
|
255
|
+
export function forget({ carrier, io, id, engine = null }) {
|
|
256
|
+
const now = nowS(carrier);
|
|
257
|
+
const r = state(io, now, (s) => {
|
|
258
|
+
const x = either(s, id);
|
|
259
|
+
if (x.side === 'in' && STATES_LIVE_IN.includes(x.r.state)) fail('transfer_state', `transfer ${id} is ${x.r.state}: cancel it first`);
|
|
260
|
+
delete s[x.side][id];
|
|
261
|
+
return x.r;
|
|
262
|
+
});
|
|
263
|
+
engine?.drop(id, 'cancelled');
|
|
264
|
+
dropPartial(io, id);
|
|
265
|
+
io.list.drop(id, 'out');
|
|
266
|
+
return r;
|
|
267
|
+
}
|
|
268
|
+
export function dropPartial(io, id) { io.part.drop(id); io.have.write(id, null); io.list.drop(id, 'in'); }
|
|
269
|
+
|
|
270
|
+
/** Both sides' records, newest first, with what the engine of this process knows live. */
|
|
271
|
+
export function list({ carrier, io, engine = null }) {
|
|
272
|
+
const now = nowS(carrier);
|
|
273
|
+
return state(io, now, (s) => {
|
|
274
|
+
const live = (r) => ({ ...r, ...(engine?.progress(r.id) ?? {}) });
|
|
275
|
+
const sort = (a, b) => b.at - a.at;
|
|
276
|
+
return {
|
|
277
|
+
out: Object.values(s.out).map((r) => { const { file: _f, ...x } = live(r); return x; }).sort(sort),
|
|
278
|
+
in: Object.values(s.in).map((r) => (stale(r, now) && !engine?.attempts.get(r.id)?.channel ? { ...live(r), state: 'interrupted', reason: 'stalled', detail: staleDetail(r) } : live(r))).sort(sort),
|
|
279
|
+
direct: { ...s.direct },
|
|
280
|
+
auto: { ...s.auto },
|
|
281
|
+
settings: settingsOf(s),
|
|
282
|
+
};
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
export function setDirect({ carrier, io, contact, on }) {
|
|
286
|
+
if (typeof on !== 'boolean') fail('usage', 'on: true or false');
|
|
287
|
+
const c = contactOf(carrier, contact);
|
|
288
|
+
return state(io, nowS(carrier), (s) => { s.direct[c.did] = on; return { did: c.did, name: c.name, direct: on }; });
|
|
289
|
+
}
|
|
290
|
+
const mbOk = (x) => Number.isFinite(x) && x >= 0 && x <= MAX_SIZE / 1e6;
|
|
291
|
+
/** A contact's own size for the accept rule: MB (0: always ask), or null: the default. */
|
|
292
|
+
export function setAuto({ carrier, io, contact, mb }) {
|
|
293
|
+
if (mb !== null && !mbOk(mb)) fail('usage', 'mb: 0 (always ask) to 17179, or null (the default)');
|
|
294
|
+
const c = contactOf(carrier, contact);
|
|
295
|
+
return state(io, nowS(carrier), (s) => {
|
|
296
|
+
if (mb === null) delete s.auto[c.did]; else s.auto[c.did] = mb;
|
|
297
|
+
return { did: c.did, name: c.name, auto_mb: mb };
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
/** The settings, patched: { tor: true|false, prefer: 'fast'|'private', auto_mb: MB (0: always ask), keep_location: camera photos keep their location tags (default false: removed) }. */
|
|
301
|
+
export function settings({ io, patch = {}, now = Math.floor(Date.now() / 1000) }) {
|
|
302
|
+
if (patch.tor !== undefined && typeof patch.tor !== 'boolean') fail('usage', 'tor: on or off');
|
|
303
|
+
if (patch.prefer !== undefined && patch.prefer !== 'fast' && patch.prefer !== 'private') fail('usage', 'prefer: fast or private');
|
|
304
|
+
if (patch.auto_mb !== undefined && !mbOk(patch.auto_mb)) fail('usage', 'auto_mb: 0 (always ask) to 17179');
|
|
305
|
+
if (patch.keep_location !== undefined && typeof patch.keep_location !== 'boolean') fail('usage', 'keep_location: true or false');
|
|
306
|
+
return state(io, now, (s) => {
|
|
307
|
+
for (const k of ['tor', 'prefer', 'auto_mb', 'keep_location']) if (patch[k] !== undefined) s.settings[k] = patch[k];
|
|
308
|
+
return settingsOf(s);
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
const hostOf = (relay) => (typeof relay === 'string' && relay ? relay.replace(/:\d+$/, '') : null);
|
|
313
|
+
/** The STUN servers for a transfer with contact c: env.SIGELO_STUN, else this agent's relay host and the contact's, port 3478. */
|
|
314
|
+
export function stunFor(carrier, c, env = {}) {
|
|
315
|
+
if (env.SIGELO_STUN !== undefined) return env.SIGELO_STUN.split(',').map((x) => x.trim()).filter(Boolean).map((x) => (/:\d+$/.test(x) ? x : `${x}:${STUN_PORT}`));
|
|
316
|
+
return [...new Set([hostOf(carrier.relay), hostOf(c?.relay)].filter(Boolean))].map((h) => `${h}:${STUN_PORT}`);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// ---------------------------------------------------------------- the engine
|
|
320
|
+
|
|
321
|
+
export class Engine {
|
|
322
|
+
/**
|
|
323
|
+
* carrier: started (it holds the session); io (above); rtc: () → the direct path's module ({ peer }) or null;
|
|
324
|
+
* stun: a list, or null for stunFor(env); turn: null (ask carrier.turnServer at each attempt; env.SIGELO_TURN=off: never), false (none),
|
|
325
|
+
* or a function → { urls, username, credential } | null; pro: () → whether this agent's pool is Pro; compared(did): the four
|
|
326
|
+
* words of that contact were compared (the accept rule); maxServe: transfers served at once (the rest wait,
|
|
327
|
+
* their offers kept); onEvent(e): {type: 'transfer', what, id, …}; fallbackMs: a drop not picked up again within it goes
|
|
328
|
+
* over the relay lane (up to 8 MiB, own and compared); stallMs: a channel with no byte for so long counts as dropped;
|
|
329
|
+
* policy: () → "relay" | "all" (the page's "Always relay my media"; env SIGELO_ICE_POLICY=relay says relay too).
|
|
330
|
+
*/
|
|
331
|
+
constructor({ carrier, io, rtc = async () => null, stun = null, turn = null, env = {}, pro = () => false, compared = () => false, maxServe = Infinity, onEvent = () => {}, retryMs = RETRY_MS, torConnectMs = 120_000, timer = true,
|
|
332
|
+
fallbackMs = FALLBACK_MS, stallMs = STALL_MS, policy = () => 'all' }) {
|
|
333
|
+
Object.assign(this, { carrier, io, rtcLoad: rtc, stun, turn, env, pro, compared, maxServe, onEvent, retryMs, torConnectMs, fallbackMs, stallMs, policy });
|
|
334
|
+
this.relaying = new Set(); // ids going over the relay lane from this process (relay)
|
|
335
|
+
this.attempts = new Map(); // id → { role, attempt, peer, channel, proto, onion, server, got, sent, path }
|
|
336
|
+
this.held = []; // offers waiting for a free slot (maxServe)
|
|
337
|
+
this.chain = Promise.resolve(); this.again = false; this.running = false; this.closed = false;
|
|
338
|
+
this.timer = timer ? setInterval(() => this.kick(), 2000) : null; this.timer?.unref?.();
|
|
339
|
+
this.capsAt = 0; this.caps = null;
|
|
340
|
+
}
|
|
341
|
+
now() { return nowS(this.carrier); }
|
|
342
|
+
st(fn) { return state(this.io, this.now(), fn); }
|
|
343
|
+
emit(what, x) { try { this.onEvent({ type: 'transfer', what, ...x, at_ms: Date.now() }); } catch {} }
|
|
344
|
+
async rtc() { if (this.rtcMod === undefined) this.rtcMod = await this.rtcLoad(); return this.rtcMod; }
|
|
345
|
+
async torCaps() {
|
|
346
|
+
const on = this.st((s) => settingsOf(s).tor);
|
|
347
|
+
if (!on || !this.io.tor) return { serve: false, connect: false };
|
|
348
|
+
if (!this.caps || Date.now() - this.capsAt > 60_000) { this.caps = await this.io.tor.caps(); this.capsAt = Date.now(); }
|
|
349
|
+
return this.caps;
|
|
350
|
+
}
|
|
351
|
+
stunOf(c) { return this.stun ?? stunFor(this.carrier, c, this.env); }
|
|
352
|
+
/** The TURN server for an attempt starting now (relay/turn.mjs, fresh credentials), or null: STUN alone, as before.
|
|
353
|
+
* rtc: the direct path's module; only one with TURN_OK true gets one (werift: apps/transfer/rtc.mjs, with its DTLS checks). */
|
|
354
|
+
/** The ICE policy of an attempt starting now: "relay" when the setting or SIGELO_ICE_POLICY says so, else "all". */
|
|
355
|
+
policyNow() { let p = null; try { p = typeof this.policy === 'function' ? this.policy() : this.policy; } catch {} return p === 'relay' || this.env.SIGELO_ICE_POLICY === 'relay' ? 'relay' : 'all'; }
|
|
356
|
+
/** The direct lane's peer for an attempt, under the policy: { peer, turn } or { peer: null } (relay only, no TURN). */
|
|
357
|
+
async #peerFor(rtc, c) {
|
|
358
|
+
const policy = this.policyNow(), turn = await this.turnOf(rtc);
|
|
359
|
+
if (policy === 'relay' && turn === null) return { peer: null, turn: null };
|
|
360
|
+
return { peer: await rtc.peer({ stun: this.stunOf(c), turn, gatherMs: GATHER_MS, ...(policy === 'relay' && { policy }) }), turn };
|
|
361
|
+
}
|
|
362
|
+
/** The channel is open: whether its selected pair is relayed, in the record (`relayed`) and the attempt. */
|
|
363
|
+
async #opened(side, id, a) {
|
|
364
|
+
let v = null;
|
|
365
|
+
try { v = (await a.peer?.relayed?.()) ?? null; } catch {}
|
|
366
|
+
a.relayed = v;
|
|
367
|
+
this.st((s) => { const y = s[side][id]; if (y) { if (v === null) delete y.relayed; else y.relayed = v; } });
|
|
368
|
+
}
|
|
369
|
+
async turnOf(rtc) {
|
|
370
|
+
if (rtc?.TURN_OK !== true || this.turn === false || this.env.SIGELO_TURN === 'off') return null;
|
|
371
|
+
const f = typeof this.turn === 'function' ? this.turn : () => this.carrier.turnServer?.();
|
|
372
|
+
try { return (await f()) ?? null; } catch { return null; }
|
|
373
|
+
}
|
|
374
|
+
/** One round soon (a `transfer` event, a kick from a verb beside this process). */
|
|
375
|
+
kick() {
|
|
376
|
+
if (this.closed) return this.chain;
|
|
377
|
+
if (this.running) { this.again = true; return this.chain; }
|
|
378
|
+
this.running = true;
|
|
379
|
+
this.chain = this.chain.then(async () => { do { this.again = false; await this.round(); } while (this.again && !this.closed); }).catch((e) => this.emit('error', { detail: e.message })).finally(() => { this.running = false; });
|
|
380
|
+
return this.chain;
|
|
381
|
+
}
|
|
382
|
+
live() { return this.attempts.size > 0 || this.st((s) => Object.values(s.in).some((r) => STATES_LIVE_IN.includes(r.state)) || Object.values(s.out).some((r) => STATES_LIVE_OUT.includes(r.state))); }
|
|
383
|
+
/** Resolves true when nothing is live (busy: another test), false once ms passed. */
|
|
384
|
+
async idle(ms = Infinity, busy = () => this.live()) {
|
|
385
|
+
const until = Date.now() + ms;
|
|
386
|
+
while (Date.now() < until && !this.closed) {
|
|
387
|
+
await this.kick();
|
|
388
|
+
if (!busy()) return true;
|
|
389
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
390
|
+
}
|
|
391
|
+
return false;
|
|
392
|
+
}
|
|
393
|
+
progress(id) {
|
|
394
|
+
const a = this.attempts.get(id);
|
|
395
|
+
if (a) return { live: a.path ?? 'connecting', got: a.got, sent: a.sent, rate: a.rate ?? null };
|
|
396
|
+
return this.held.some((h) => h.r.id === id) ? { live: 'waiting', got: 0, sent: 0, rate: null } : null;
|
|
397
|
+
}
|
|
398
|
+
/** An attempt of this process stopped (cancel, forget). */
|
|
399
|
+
drop(id, reason) { this.held = this.held.filter((h) => h.r.id !== id); const a = this.attempts.get(id); if (!a) return; this.attempts.delete(id); a.stopped = reason; try { a.proto?.stop(reason); } catch {} this.closeAttempt(a); }
|
|
400
|
+
async close() {
|
|
401
|
+
this.closed = true;
|
|
402
|
+
if (this.timer) clearInterval(this.timer);
|
|
403
|
+
await this.chain.catch(() => {});
|
|
404
|
+
for (const [id, a] of [...this.attempts]) {
|
|
405
|
+
this.attempts.delete(id);
|
|
406
|
+
a.stopped = 'closed';
|
|
407
|
+
try { a.proto?.stop('cancelled'); } catch {}
|
|
408
|
+
this.closeAttempt(a);
|
|
409
|
+
// Stopped here, not refused there: the receiver may resume it later.
|
|
410
|
+
this.st((s) => { const r = s.in[id] ?? s.out[id]; if (r && r.state === 'active') r.state = s.in[id] ? 'interrupted' : 'offered'; });
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
closeAttempt(a) {
|
|
414
|
+
try { a.channel?.close(); } catch {}
|
|
415
|
+
try { a.peer?.close(); } catch {}
|
|
416
|
+
try { this.io.tor?.close(a); } catch {}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
async round(pick) {
|
|
420
|
+
for (const m of this.carrier.takeTransfers(pick)) {
|
|
421
|
+
try { await this.#onMessage(m); } catch (e) {
|
|
422
|
+
if (!(e instanceof MsgError)) throw e;
|
|
423
|
+
this.emit('refused', { from: m.from, check: e.check, detail: e.message });
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
const now = this.now(), relay = [];
|
|
427
|
+
const todo = this.st((s) => {
|
|
428
|
+
const out = [];
|
|
429
|
+
for (const r of Object.values(s.in)) {
|
|
430
|
+
if (r.state === 'asked' && r.exp <= now) { r.state = 'expired'; r.at = now; }
|
|
431
|
+
if (r.state === 'accepted' && (!this.attempts.has(r.id) || r.restart)) { delete r.restart; out.push(r.id); }
|
|
432
|
+
// Stuck for STALE_S (an attempt this process holds that moves nothing, or none): interrupted, resume says so.
|
|
433
|
+
if (stale(r, now) && !this.attempts.get(r.id)?.channel) { this.drop(r.id, 'stalled'); Object.assign(r, { state: 'interrupted', reason: 'stalled', detail: staleDetail(r), last: now }); }
|
|
434
|
+
if ((r.state === 'offering' || r.state === 'active') && !this.attempts.has(r.id)) { r.state = 'interrupted'; r.reason = 'drop'; r.retryAt = 0; }
|
|
435
|
+
if (r.state === 'offering' && r.offerAt + ANSWER_WAIT < now) { r.state = 'interrupted'; r.reason = 'lapsed'; r.detail = 'no answer within 10 minutes: is the sender online? transfer resume'; this.drop(r.id, 'lapsed'); }
|
|
436
|
+
if (r.state === 'interrupted' && r.reason === 'drop' && (r.auto ?? 0) < RETRIES_AUTO && !this.attempts.has(r.id) && (r.retryAt ?? 0) <= Date.now()) { r.auto = (r.auto ?? 0) + 1; r.state = 'accepted'; out.push(r.id); }
|
|
437
|
+
if (['interrupted', 'failed', 'cancelled'].includes(r.state) && (r.last ?? r.at) + MANIFEST_TTL < now && (this.io.part.exists?.(r.id) ?? true)) { dropPartial(this.io, r.id); r.state = 'expired'; }
|
|
438
|
+
}
|
|
439
|
+
for (const r of Object.values(s.out)) {
|
|
440
|
+
if (r.state === 'offered' && r.exp <= now) { r.state = 'expired'; r.at = now; }
|
|
441
|
+
if (r.state === 'active' && !this.attempts.has(r.id)) { r.state = 'offered'; if (!pick) r.dropAt ??= Date.now(); }
|
|
442
|
+
// Over the relay lane when a process went mid-way: said, the page offers it again.
|
|
443
|
+
if (!pick && r.state === 'relaying' && !this.relaying.has(r.id)) Object.assign(r, { state: 'failed', reason: 'relay', detail: 'stopped while it went over the relay: send it over the relay again', at: now });
|
|
444
|
+
if (!pick && r.state === 'offered' && r.dropAt && Date.now() - r.dropAt >= this.fallbackMs && !this.attempts.has(r.id)) relay.push(r.id);
|
|
445
|
+
}
|
|
446
|
+
return out;
|
|
447
|
+
});
|
|
448
|
+
if (pick) return; // intake: no session here
|
|
449
|
+
for (const id of relay) this.fallback(id);
|
|
450
|
+
// A channel that moves nothing for stallMs: dropped here (not stopped: the other side is not told cancelled).
|
|
451
|
+
for (const [id, a] of [...this.attempts]) {
|
|
452
|
+
if (!a.channel || Date.now() - (a.moved ?? Date.now()) < this.stallMs) continue;
|
|
453
|
+
this.attempts.delete(id); a.stopped = 'stalled'; this.closeAttempt(a);
|
|
454
|
+
if (a.role === 'in') this.interrupt(id, 'drop', `nothing came for ${Math.round(this.stallMs / 1000)} s: resumed with a new offer`);
|
|
455
|
+
else { this.st((s) => { const r = s.out[id]; if (r?.state === 'active') Object.assign(r, { state: 'offered', dropAt: Date.now() }); }); this.emit('interrupted', { id, side: 'out' }); }
|
|
456
|
+
}
|
|
457
|
+
// Offers held for a free slot (maxServe), oldest first.
|
|
458
|
+
while (this.held.length && this.serving() < this.maxServe) { const h = this.held.shift(); void this.#onOffer(h.r, h.x, h.m).catch((e) => this.emit('error', { id: h.r.id, detail: e.message })); }
|
|
459
|
+
for (const id of todo) await this.#offer(id).catch((e) => this.fail('in', id, e.check ?? 'offer', e.message));
|
|
460
|
+
}
|
|
461
|
+
serving() { let n = 0; for (const a of this.attempts.values()) if (a.role === 'out') n++; return n; }
|
|
462
|
+
|
|
463
|
+
fail(side, id, reason, detail) {
|
|
464
|
+
this.st((s) => { const r = s[side][id]; if (r && !['done', 'cancelled', 'declined', 'relayed', 'relaying'].includes(r.state)) Object.assign(r, { state: 'failed', reason, detail, at: this.now() }); });
|
|
465
|
+
this.emit('failed', { id, side, reason, detail });
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
async #onMessage(m) {
|
|
469
|
+
const x = checkMessage(m.content), now = this.now();
|
|
470
|
+
if (x.typ === 'manifest') {
|
|
471
|
+
let c = null;
|
|
472
|
+
try { c = contactOf(this.carrier, m.from); } catch {}
|
|
473
|
+
const trust = c ? trustOf(c, this.compared) : 'other';
|
|
474
|
+
const r = this.st((s) => {
|
|
475
|
+
if (s.in[x.id]) return null; // seen
|
|
476
|
+
if (x.exp <= now) return null;
|
|
477
|
+
const waiting = Object.values(s.in).filter((y) => y.state === 'asked');
|
|
478
|
+
if (waiting.length >= WAIT_ALL || waiting.filter((y) => y.from === m.from).length >= WAIT_CONTACT) return 'busy';
|
|
479
|
+
const rec = { id: x.id, from: m.from, contact: m.name, name: safeName(x.name), size: x.size, sha256: x.sha256, chunks: x.chunks, list: x.list, exp: x.exp, state: 'asked', attempt: 0, at: now, got: 0 };
|
|
480
|
+
s.in[x.id] = rec;
|
|
481
|
+
// The accept rule: a yes given by the rule, when the disk has room. Whatever the direct switch: off (or not
|
|
482
|
+
// asked yet), #offer leaves direct out and the file comes over Tor, else the sender's relay lane (no_path).
|
|
483
|
+
// Only when one of those lanes can carry it: direct on, or Tor on here, or within the relay lane's 8 MiB;
|
|
484
|
+
// else it is asked (Accept asks the direct question), never accepted to fail no_path unseen.
|
|
485
|
+
const mb = Object.hasOwn(s.auto, m.from) ? s.auto[m.from] : null;
|
|
486
|
+
const lane = c && (directFor(s, c) === true || x.size <= RELAY_MAX || (settingsOf(s).tor && !!this.io.tor));
|
|
487
|
+
// The rule's yeses still coming count as waiting ones do (WAIT_CONTACT a contact, WAIT_ALL in all), and the disk
|
|
488
|
+
// must hold them all: a sender past the 8 a batch, or many at once, is asked.
|
|
489
|
+
const live = Object.values(s.in).filter((y) => y.by === 'rule' && y.id !== rec.id && ['accepted', 'offering', 'active', 'interrupted'].includes(y.state));
|
|
490
|
+
const fits = live.length < WAIT_ALL && live.filter((y) => y.from === m.from).length < WAIT_CONTACT;
|
|
491
|
+
if (lane && fits && acceptRule({ size: x.size, trust, limitMb: mb, defaultMb: autoDefault(s) }) === 'auto') {
|
|
492
|
+
const promised = live.reduce((t, y) => t + Math.max(0, y.size - haveOf(this.io, y).bytes(y.size)), 0);
|
|
493
|
+
try { room(this.io, rec, promised); rec.state = 'accepted'; rec.auto = 0; rec.by = 'rule'; } catch {}
|
|
494
|
+
}
|
|
495
|
+
return { ...rec };
|
|
496
|
+
});
|
|
497
|
+
if (r === 'busy') { await sendMsg(this.carrier, m.from, { typ: 'end', id: x.id, reason: 'busy' }, false).catch(() => {}); return; }
|
|
498
|
+
if (r) this.emit(r.state === 'accepted' ? 'landing' : 'asked', { id: r.id, from: r.from, contact: r.contact, name: r.name, size: r.size });
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
// Any other: only from the contact the transfer is with.
|
|
502
|
+
const { side, r } = this.st((s) => (s.out[x.id]?.to === m.from ? { side: 'out', r: { ...s.out[x.id] } } : s.in[x.id]?.from === m.from ? { side: 'in', r: { ...s.in[x.id] } } : { side: null, r: null }));
|
|
503
|
+
if (!r) fail('transfer_unknown', `a ${x.typ} for a transfer this agent has with no such contact`);
|
|
504
|
+
if (x.typ === 'end') return this.#onEnd(side, r, x);
|
|
505
|
+
// Detached: ICE (30 s) and a Tor connection (up to 2 minutes) must not hold the next message.
|
|
506
|
+
const bg = (p) => { void p.catch((e) => this.emit('error', { id: r.id, detail: e.message })); };
|
|
507
|
+
if (side === 'out' && x.typ === 'offer') {
|
|
508
|
+
// Every slot busy: the offer waits here (it lives 10 minutes there).
|
|
509
|
+
if (this.serving() >= this.maxServe && !this.attempts.has(r.id)) { this.held = this.held.filter((h) => h.r.id !== r.id); this.held.push({ r, x, m }); this.emit('waiting', { id: r.id }); return; }
|
|
510
|
+
return bg(this.#onOffer(r, x, m));
|
|
511
|
+
}
|
|
512
|
+
if (side === 'in' && x.typ === 'answer') return bg(this.#onAnswer(r, x));
|
|
513
|
+
if (x.typ === 'onion') return bg(this.io.tor ? this.io.tor.connect(this, side, r, x, this.attempts.get(r.id)) : Promise.resolve());
|
|
514
|
+
fail('transfer_message', `a ${x.typ} on the ${side === 'in' ? 'receiving' : 'sending'} side`);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
async #onEnd(side, r, x) {
|
|
518
|
+
const a = this.attempts.get(r.id);
|
|
519
|
+
if (x.reason === 'try_tor') {
|
|
520
|
+
if (side !== 'out' || !a || a.attempt !== x.attempt || !this.io.tor) return;
|
|
521
|
+
return this.io.tor.serve(this, side, r, a);
|
|
522
|
+
}
|
|
523
|
+
if (x.reason === 'done' && side === 'out') {
|
|
524
|
+
this.st((s) => { if (s.out[r.id]) Object.assign(s.out[r.id], { state: 'done', at: this.now(), sent: r.size }); });
|
|
525
|
+
if (a) { this.attempts.delete(r.id); this.closeAttempt(a); }
|
|
526
|
+
this.emit('done', { id: r.id, side, name: r.name });
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
if (x.reason === 'relay') {
|
|
530
|
+
// The sender sends it over sigelo-file/0 instead: this record stops, no ghost left active.
|
|
531
|
+
if (side !== 'in') return;
|
|
532
|
+
if (a) { this.attempts.delete(r.id); a.stopped = 'relay'; this.closeAttempt(a); }
|
|
533
|
+
this.st((s) => { const y = s.in[r.id]; if (y && y.state !== 'done') { Object.assign(y, { state: 'relayed', at: this.now(), detail: `${y.name} comes over the relay lane (sigelo-file/0) instead` }); delete y.reason; } });
|
|
534
|
+
dropPartial(this.io, r.id);
|
|
535
|
+
this.emit('relayed', { id: r.id, side, name: r.name });
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
if (a && x.attempt !== undefined && x.attempt !== a.attempt) return;
|
|
539
|
+
if (a) { this.attempts.delete(r.id); a.stopped = x.reason; try { a.proto?.stop(x.reason); } catch {} this.closeAttempt(a); }
|
|
540
|
+
this.held = this.held.filter((h) => h.r.id !== r.id);
|
|
541
|
+
const st = x.reason === 'declined' ? 'declined' : x.reason === 'cancelled' ? 'cancelled' : 'failed';
|
|
542
|
+
this.st((s) => { const y = s[side][r.id]; if (y && !['done', 'relaying', 'relayed'].includes(y.state)) Object.assign(y, { state: st, ...(st === 'failed' && { reason: x.reason, detail: x.reason === 'no_path' ? noPath(y.contact) : `the other side ended it: ${x.reason}` }), at: this.now() }); });
|
|
543
|
+
if (side === 'in' && ['cancelled', 'chunk_hash', 'file_changed'].includes(x.reason)) dropPartial(this.io, r.id);
|
|
544
|
+
this.emit(st, { id: r.id, side, reason: x.reason });
|
|
545
|
+
if (side === 'out' && x.reason === 'no_path') this.fallback(r.id);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// ---- the relay lane (0.1.19)
|
|
549
|
+
/** May transfer id (sent from here) go over the relay lane by itself: at most 8 MiB, not yet, to own or compared. */
|
|
550
|
+
relayable(r) {
|
|
551
|
+
if (!r || r.size > RELAY_MAX || r.relay || ['done', 'relaying', 'cancelled', 'declined'].includes(r.state)) return false;
|
|
552
|
+
let c;
|
|
553
|
+
try { c = contactOf(this.carrier, r.to); } catch { return false; }
|
|
554
|
+
return trustOf(c, this.compared) !== 'other';
|
|
555
|
+
}
|
|
556
|
+
/** The direct lane failed or dropped: over the relay lane, once, when relayable. */
|
|
557
|
+
fallback(id) {
|
|
558
|
+
const r = this.st((s) => (s.out[id] ? { ...s.out[id] } : null));
|
|
559
|
+
if (!this.relayable(r)) return false;
|
|
560
|
+
void this.relay(id).catch((e) => this.emit('error', { id, detail: e.message }));
|
|
561
|
+
return true;
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Transfer id, sent from here, over sigelo-file/0 (carrier.sendFile, at most 8 MiB): the receiver told `end relay`
|
|
565
|
+
* first, the file read whole and checked against the manifest's SHA-256. manual: the page's "Send over the relay"
|
|
566
|
+
* (any contact, and again after a failure). → the record (done, path_used relay), or failed with reason relay.
|
|
567
|
+
*/
|
|
568
|
+
async relay(id, { manual = false } = {}) {
|
|
569
|
+
const now = this.now();
|
|
570
|
+
const r = this.st((s) => {
|
|
571
|
+
const x = s.out[id] ?? fail('transfer_unknown', `no transfer ${id} sent from here`);
|
|
572
|
+
if (['done', 'relaying', 'cancelled', 'declined'].includes(x.state)) fail('transfer_state', `transfer ${id} is ${x.state}`);
|
|
573
|
+
if (x.size > RELAY_MAX) fail('file_too_large', `${x.name} is ${x.size} bytes: the relay lane carries at most ${RELAY_MAX} (8 MiB)`);
|
|
574
|
+
if (!manual && x.relay) return null;
|
|
575
|
+
Object.assign(x, { state: 'relaying', relay: (x.relay ?? 0) + 1, at: now });
|
|
576
|
+
delete x.reason; delete x.detail; delete x.dropAt;
|
|
577
|
+
return { ...x };
|
|
578
|
+
});
|
|
579
|
+
if (!r) return null;
|
|
580
|
+
this.relaying.add(id);
|
|
581
|
+
const a = this.attempts.get(id);
|
|
582
|
+
if (a) { this.attempts.delete(id); a.stopped = 'relay'; this.closeAttempt(a); }
|
|
583
|
+
this.held = this.held.filter((h) => h.r.id !== id);
|
|
584
|
+
try {
|
|
585
|
+
await sendMsg(this.carrier, r.to, { typ: 'end', id, reason: 'relay' }, false).catch(() => {});
|
|
586
|
+
if (await this.io.changed(r)) fail('file_changed', `${r.name} changed or went since it was offered: send it again`);
|
|
587
|
+
const src = await this.io.source(r), parts = [];
|
|
588
|
+
try { for (let i = 0; i < r.chunks; i++) parts.push(await src.read(i)); } finally { await src.close().catch(() => {}); }
|
|
589
|
+
const bytes = concatBytes(...parts);
|
|
590
|
+
if (sha256Hex(bytes) !== r.sha256) fail('file_changed', `${r.name} is not the file offered any more: send it again`);
|
|
591
|
+
const x = await this.carrier.sendFile(r.to, { bytes, name: r.name });
|
|
592
|
+
const done = this.st((s) => { const y = s.out[id]; if (y) Object.assign(y, { state: 'done', path_used: 'relay', relay_status: x.status, sent: r.size, at: this.now() }); return y ? { ...y } : null; });
|
|
593
|
+
this.emit('done', { id, side: 'out', name: r.name, via: 'relay' });
|
|
594
|
+
return done;
|
|
595
|
+
} catch (e) {
|
|
596
|
+
this.st((s) => { const y = s.out[id]; if (y && y.state === 'relaying') Object.assign(y, { state: 'failed', reason: e.check === 'file_changed' ? 'file_changed' : 'relay', detail: `over the relay: ${e.message}`, at: this.now() }); });
|
|
597
|
+
this.emit('failed', { id, side: 'out', reason: 'relay', detail: e.message });
|
|
598
|
+
throw e;
|
|
599
|
+
} finally { this.relaying.delete(id); }
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* A file that came over sigelo-file/0 (an inbox item: from, sha256, path): a transfer of the same file from the same
|
|
603
|
+
* contact is done by it (it went over the relay instead), its partial and attempt dropped. → the ids superseded.
|
|
604
|
+
*/
|
|
605
|
+
superseded(item) {
|
|
606
|
+
if (!item || item.type !== 'file' || item.transfer || typeof item.sha256 !== 'string') return [];
|
|
607
|
+
const ids = this.st((s) => {
|
|
608
|
+
const hit = Object.values(s.in).filter((r) => r.from === item.from && r.sha256 === item.sha256 && r.state !== 'done');
|
|
609
|
+
for (const r of hit) { Object.assign(r, { state: 'done', got: r.size, at: this.now(), saved: item.path ?? null, path_used: 'relay' }); delete r.reason; delete r.detail; }
|
|
610
|
+
return hit.map((r) => r.id);
|
|
611
|
+
});
|
|
612
|
+
for (const id of ids) { this.drop(id, 'relay'); dropPartial(this.io, id); this.emit('done', { id, side: 'in', via: 'relay', path: item.path ?? null }); }
|
|
613
|
+
return ids;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// ---- the receiver: an attempt is an offer
|
|
617
|
+
async #offer(id) {
|
|
618
|
+
const now = this.now();
|
|
619
|
+
const prev = this.attempts.get(id);
|
|
620
|
+
if (prev) { this.attempts.delete(id); this.closeAttempt(prev); }
|
|
621
|
+
const r = this.st((s) => ({ ...s.in[id], directOk: directFor(s, contactOf(this.carrier, s.in[id].from)) === true, pro: this.pro(), prefer: settingsOf(s).prefer }));
|
|
622
|
+
// Every chunk here already (it came whole, then could not be saved): saved again, no network.
|
|
623
|
+
if (r.chunks > 0 && haveOf(this.io, r).done()) return this.#land(r, null);
|
|
624
|
+
const c = contactOf(this.carrier, r.from), tor = await this.torCaps(), rtc = await this.rtc();
|
|
625
|
+
// The paths this attempt may take, in order; Tor here means this side can play either part.
|
|
626
|
+
let order = pathOrder({ pro: r.pro, prefer: r.prefer, via: r.via === 'tor' ? 'tor' : 'auto', direct: r.directOk && rtc !== null, tor: tor.serve || tor.connect });
|
|
627
|
+
// Relay only and no TURN to be had: the direct lane left out at once (no host candidate gathered), the rest as ever.
|
|
628
|
+
let direct = null;
|
|
629
|
+
if (order[0] === 'direct') {
|
|
630
|
+
direct = await this.#peerFor(rtc, c);
|
|
631
|
+
if (!direct.peer) { order = order.filter((x) => x !== 'direct'); this.emit('no_direct', { id, detail: RELAY_ONLY }); }
|
|
632
|
+
}
|
|
633
|
+
if (order.length === 0) {
|
|
634
|
+
if (direct && !direct.peer) this.fail('in', id, 'relay_only', RELAY_ONLY);
|
|
635
|
+
else this.fail('in', id, 'no_path', r.directOk ? noPath(c.name) : `direct is off for ${c.name} and Tor is not on here: ${noPath(c.name)}`);
|
|
636
|
+
await sendMsg(this.carrier, r.from, { typ: 'end', id, reason: 'no_path' }, false).catch(() => {});
|
|
637
|
+
return;
|
|
638
|
+
}
|
|
639
|
+
const attempt = (r.attempt ?? 0) + 1, a = { role: 'in', attempt, order, tor, got: 0, sent: 0 };
|
|
640
|
+
this.attempts.set(id, a);
|
|
641
|
+
let sdp = null;
|
|
642
|
+
if (order[0] === 'direct') {
|
|
643
|
+
a.turn = direct.turn !== null;
|
|
644
|
+
a.peer = direct.peer;
|
|
645
|
+
sdp = await a.peer.offer(channelLabel(id, attempt));
|
|
646
|
+
} else direct?.peer?.close();
|
|
647
|
+
this.st((s) => Object.assign(s.in[id], { state: 'offering', attempt, offerAt: this.now(), path: order[0] }));
|
|
648
|
+
await sendMsg(this.carrier, r.from, { typ: 'offer', id, attempt, sdp, tor, ...(order[0] === 'tor' && { via: 'tor' }) }, false);
|
|
649
|
+
this.emit('offered', { id, attempt, path: order[0] });
|
|
650
|
+
}
|
|
651
|
+
async #onAnswer(r, x) {
|
|
652
|
+
const a = this.attempts.get(r.id);
|
|
653
|
+
if (!a || a.attempt !== x.attempt || a.answered) return;
|
|
654
|
+
a.answered = true; a.peerTor = x.tor;
|
|
655
|
+
// Active again: the reason of an earlier drop goes (0.1.19: "active: drop" stayed for good).
|
|
656
|
+
this.st((s) => { const y = s.in[r.id]; if (y) { y.state = 'active'; y.last = this.now(); delete y.reason; delete y.detail; } });
|
|
657
|
+
if (a.order[0] === 'direct' && x.sdp !== null && a.peer) {
|
|
658
|
+
try {
|
|
659
|
+
await a.peer.accept(x.sdp);
|
|
660
|
+
a.path = 'direct';
|
|
661
|
+
const ch = await a.peer.open(ICE_MS);
|
|
662
|
+
if (this.attempts.get(r.id) !== a) { ch.close(); return; }
|
|
663
|
+
await this.#opened('in', r.id, a);
|
|
664
|
+
if (this.attempts.get(r.id) !== a) { ch.close(); return; }
|
|
665
|
+
return this.pull(r, a, ch);
|
|
666
|
+
} catch (e) { if (this.attempts.get(r.id) !== a) return; a.peer?.close(); a.peer = null; this.emit('no_direct', { id: r.id, detail: e.message }); }
|
|
667
|
+
}
|
|
668
|
+
return this.#nextPath(r, a, a.order[0] === 'direct' ? 1 : 0);
|
|
669
|
+
}
|
|
670
|
+
// The receiver, after the direct path failed (or was not offered): Tor if both sides can, else the next attempt or no path.
|
|
671
|
+
async #nextPath(r, a, k) {
|
|
672
|
+
const rest = a.order.slice(k);
|
|
673
|
+
const who = torRoles(a.peerTor, a.tor);
|
|
674
|
+
if (rest[0] === 'tor' && who && this.io.tor) {
|
|
675
|
+
a.path = 'tor';
|
|
676
|
+
if (who === 'receiver') return this.io.tor.serve(this, 'in', r, a);
|
|
677
|
+
await sendMsg(this.carrier, r.from, { typ: 'end', id: r.id, reason: 'try_tor', attempt: a.attempt }, false);
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
// Tor first (Pro private) and it cannot: direct as a new attempt.
|
|
681
|
+
if (rest[0] === 'tor' && rest.includes('direct') && a.order[0] === 'tor') {
|
|
682
|
+
this.st((s) => { s.in[r.id].via = 'auto'; s.in[r.id].state = 'accepted'; });
|
|
683
|
+
this.attempts.delete(r.id); this.closeAttempt(a);
|
|
684
|
+
return this.kick();
|
|
685
|
+
}
|
|
686
|
+
this.attempts.delete(r.id); this.closeAttempt(a);
|
|
687
|
+
const c = contactOf(this.carrier, r.from);
|
|
688
|
+
this.fail('in', r.id, 'no_path', noPath(c.name, a.turn === true));
|
|
689
|
+
await sendMsg(this.carrier, r.from, { typ: 'end', id: r.id, reason: 'no_path', attempt: a.attempt }, false).catch(() => {});
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
// ---- the sender: an offer is answered
|
|
693
|
+
async #onOffer(r0, x, m) {
|
|
694
|
+
// The record as it is now (a held offer waited).
|
|
695
|
+
const r = this.st((s) => (s.out[r0.id] ? { ...s.out[r0.id] } : null));
|
|
696
|
+
if (!r) return;
|
|
697
|
+
// Gone over the relay lane: said again (an offer of the receiver's that crossed the end relay).
|
|
698
|
+
if (r.state === 'relaying' || r.path_used === 'relay') { await sendMsg(this.carrier, m.from, { typ: 'end', id: r.id, reason: 'relay' }, false).catch(() => {}); return; }
|
|
699
|
+
if (['done', 'cancelled', 'declined', 'expired'].includes(r.state)) { await sendMsg(this.carrier, m.from, { typ: 'end', id: r.id, reason: r.state === 'done' ? 'done' : 'cancelled' }, false).catch(() => {}); return; }
|
|
700
|
+
if (x.attempt <= (r.attempt ?? 0)) return;
|
|
701
|
+
const prev = this.attempts.get(r.id);
|
|
702
|
+
if (prev) { this.attempts.delete(r.id); this.closeAttempt(prev); }
|
|
703
|
+
// Read in place: the file must be the one hashed (size and modification time).
|
|
704
|
+
if (await this.io.changed(r)) {
|
|
705
|
+
this.fail('out', r.id, 'file_changed', `${r.name} changed or went since it was offered: send it again`);
|
|
706
|
+
await sendMsg(this.carrier, m.from, { typ: 'end', id: r.id, reason: 'file_changed' }, false).catch(() => {});
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
const c = contactOf(this.carrier, r.to), tor = await this.torCaps(), rtc = await this.rtc();
|
|
710
|
+
const directOk = this.st((s) => directFor(s, c) === true) && r.via !== 'tor' && x.via !== 'tor' && x.sdp !== null && rtc !== null;
|
|
711
|
+
const a = { role: 'out', attempt: x.attempt, tor, peerTor: x.tor, got: 0, sent: 0 };
|
|
712
|
+
this.attempts.set(r.id, a);
|
|
713
|
+
this.st((s) => Object.assign(s.out[r.id], { state: 'active', attempt: x.attempt }));
|
|
714
|
+
let sdp = null;
|
|
715
|
+
if (directOk) {
|
|
716
|
+
// Relay only and no TURN: no answer SDP (the receiver goes on to Tor, or ends no_path and this side takes the relay lane).
|
|
717
|
+
const d = await this.#peerFor(rtc, c);
|
|
718
|
+
a.turn = d.turn !== null;
|
|
719
|
+
a.peer = d.peer;
|
|
720
|
+
if (d.peer) sdp = await a.peer.answer(x.sdp, channelLabel(r.id, x.attempt));
|
|
721
|
+
else this.emit('no_direct', { id: r.id, detail: RELAY_ONLY });
|
|
722
|
+
}
|
|
723
|
+
await sendMsg(this.carrier, m.from, { typ: 'answer', id: r.id, attempt: x.attempt, sdp, tor }, false);
|
|
724
|
+
if (!a.peer) return; // the receiver says what comes next: try_tor, an onion, or end
|
|
725
|
+
try {
|
|
726
|
+
a.path = 'direct';
|
|
727
|
+
const ch = await a.peer.open(ICE_MS);
|
|
728
|
+
if (this.attempts.get(r.id) !== a) { ch.close(); return; }
|
|
729
|
+
await this.#opened('out', r.id, a);
|
|
730
|
+
if (this.attempts.get(r.id) !== a) { ch.close(); return; }
|
|
731
|
+
this.serve(r, a, ch);
|
|
732
|
+
} catch { if (this.attempts.get(r.id) === a) { a.peer?.close(); a.peer = null; a.path = null; } }
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
// ---- the bytes
|
|
736
|
+
serve(r, a, ch) {
|
|
737
|
+
a.channel = ch; a.moved = Date.now();
|
|
738
|
+
this.st((s) => { if (s.out[r.id]) delete s.out[r.id].dropAt; });
|
|
739
|
+
const hashes = this.io.list.read(r.id, 'out');
|
|
740
|
+
let src = null;
|
|
741
|
+
const t0 = Date.now();
|
|
742
|
+
const read = async (i) => { src ??= await this.io.source(r); return src.read(i); };
|
|
743
|
+
this.emit('active', { id: r.id, side: 'out', path: a.path });
|
|
744
|
+
a.proto = new Serve({
|
|
745
|
+
m: { ...r }, hashes, channel: ch, read,
|
|
746
|
+
onProgress: (n) => { a.sent = n; a.moved = Date.now(); a.rate = n / 1e6 / Math.max(0.001, (Date.now() - t0) / 1000); },
|
|
747
|
+
onEnd: (reason, o) => {
|
|
748
|
+
void src?.close().catch(() => {});
|
|
749
|
+
if (this.attempts.get(r.id) !== a) return;
|
|
750
|
+
this.attempts.delete(r.id); this.closeAttempt(a);
|
|
751
|
+
if (reason === 'done' && o.remote) {
|
|
752
|
+
this.st((s) => { if (s.out[r.id]) Object.assign(s.out[r.id], { state: 'done', at: this.now(), sent: r.size, path_used: a.path }); });
|
|
753
|
+
this.emit('done', { id: r.id, side: 'out', name: r.name, via: a.path, rate: a.rate });
|
|
754
|
+
} else if (reason === 'chunk_hash' || reason === 'file_changed') {
|
|
755
|
+
this.fail('out', r.id, reason, `ended: ${reason}`);
|
|
756
|
+
} else {
|
|
757
|
+
// A drop or a stop on the channel: the receiver resumes with a new offer; a cancel comes as an end message.
|
|
758
|
+
this.st((s) => { if (s.out[r.id]?.state === 'active') Object.assign(s.out[r.id], { state: 'offered', dropAt: Date.now() }); });
|
|
759
|
+
this.emit('interrupted', { id: r.id, side: 'out' });
|
|
760
|
+
}
|
|
761
|
+
void this.kick(); // a slot is free: a held offer goes
|
|
762
|
+
},
|
|
763
|
+
});
|
|
764
|
+
a.proto.start();
|
|
765
|
+
}
|
|
766
|
+
pull(r, a, ch) {
|
|
767
|
+
a.channel = ch; a.moved = Date.now();
|
|
768
|
+
const io = this.io, id = r.id;
|
|
769
|
+
const have = haveOf(io, r);
|
|
770
|
+
let known = io.list.read(id, 'in');
|
|
771
|
+
if (known && listOf(known) !== r.list) known = null;
|
|
772
|
+
a.got = have.bytes(r.size);
|
|
773
|
+
const t0 = Date.now(), start = a.got;
|
|
774
|
+
let saved = Date.now(), part = null;
|
|
775
|
+
const opened = io.part.open(id).then((p) => { part = p; return p; });
|
|
776
|
+
this.emit('active', { id, side: 'in', path: a.path });
|
|
777
|
+
a.proto = new Pull({
|
|
778
|
+
m: { ...r, chunk: CHUNK }, have, hashes: known, channel: ch, flushEach: io.flushEach ?? 8,
|
|
779
|
+
write: async (i, bytes) => { await (await opened).write(bytes, i * CHUNK); },
|
|
780
|
+
flush: async () => {
|
|
781
|
+
await (await opened).flush();
|
|
782
|
+
// The bitmap once Pull has set the bits, after the bytes are on disk: a bit means checked and flushed.
|
|
783
|
+
later(() => {
|
|
784
|
+
if (!a.landed) { try { io.have.write(id, have.bits); } catch {} }
|
|
785
|
+
if (Date.now() - saved > 2000) { saved = Date.now(); this.st((s) => { if (s.in[id]) Object.assign(s.in[id], { got: a.got, last: this.now() }); }); }
|
|
786
|
+
});
|
|
787
|
+
},
|
|
788
|
+
onList: (h) => { try { io.list.write(id, 'in', h); } catch {} },
|
|
789
|
+
onProgress: (n) => { a.got += n; a.moved = Date.now(); a.rate = (a.got - start) / 1e6 / Math.max(0.001, (Date.now() - t0) / 1000); },
|
|
790
|
+
onEnd: (reason, o) => { void opened.then(() => this.#pulled(r, a, part, have, reason, o), (e) => this.#pulled(r, a, null, have, 'cancelled', { gone: true, error: e })); },
|
|
791
|
+
});
|
|
792
|
+
a.proto.start();
|
|
793
|
+
}
|
|
794
|
+
async #pulled(r, a, part, have, reason, o) {
|
|
795
|
+
const id = r.id, io = this.io, carrier = this.carrier;
|
|
796
|
+
try { io.have.write(id, have.bits); } catch {}
|
|
797
|
+
if (reason !== 'complete') {
|
|
798
|
+
try { await part?.close(); } catch {}
|
|
799
|
+
if (this.attempts.get(id) !== a) return;
|
|
800
|
+
this.attempts.delete(id); this.closeAttempt(a);
|
|
801
|
+
if (o.gone || (reason === 'cancelled' && !o.remote)) return this.interrupt(id, 'drop', 'the channel went: resumed with a new offer');
|
|
802
|
+
if (reason === 'cancelled') { this.st((s) => { if (s.in[id]) Object.assign(s.in[id], { state: 'cancelled', at: this.now() }); }); dropPartial(io, id); return; }
|
|
803
|
+
this.fail('in', id, reason, `ended: ${reason}`);
|
|
804
|
+
if (reason === 'chunk_hash' || reason === 'file_changed') dropPartial(io, id);
|
|
805
|
+
if (!o.remote) await sendMsg(carrier, r.from, { typ: 'end', id, reason, attempt: a.attempt }, false).catch(() => {});
|
|
806
|
+
return;
|
|
807
|
+
}
|
|
808
|
+
// Every chunk checked and flushed: the whole file read back from disk.
|
|
809
|
+
await part.flush(); await part.close();
|
|
810
|
+
if ((await io.part.sha256(id)) !== r.sha256) {
|
|
811
|
+
a.proto.finish('chunk_hash');
|
|
812
|
+
this.attempts.delete(id); this.closeAttempt(a);
|
|
813
|
+
dropPartial(io, id);
|
|
814
|
+
this.fail('in', id, 'chunk_hash', 'the file read back is not the manifest\'s: dropped');
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
return this.#land(r, a);
|
|
818
|
+
}
|
|
819
|
+
// A file read back whole: placed (io.land), one inbox item, the sender told done. Not placed (no room, no
|
|
820
|
+
// permission): said in the record (failed, land), the partial kept; resume tries again without the network.
|
|
821
|
+
async #land(r, a) {
|
|
822
|
+
const id = r.id, io = this.io, carrier = this.carrier;
|
|
823
|
+
if (!a && (await io.part.sha256(id)) !== r.sha256) {
|
|
824
|
+
dropPartial(io, id);
|
|
825
|
+
this.fail('in', id, 'chunk_hash', 'the file read back is not the manifest\'s: dropped');
|
|
826
|
+
return;
|
|
827
|
+
}
|
|
828
|
+
const c = contactOf(carrier, r.from);
|
|
829
|
+
let path;
|
|
830
|
+
try { path = await io.land(r, c); } catch (e) {
|
|
831
|
+
if (a) { this.attempts.delete(id); this.closeAttempt(a); }
|
|
832
|
+
this.fail('in', id, 'land', `${r.name} came whole but could not be saved: ${e.message}`);
|
|
833
|
+
return;
|
|
834
|
+
}
|
|
835
|
+
if (a) a.landed = true;
|
|
836
|
+
io.have.write(id, null); io.list.drop(id, 'in');
|
|
837
|
+
a?.proto.finish('done');
|
|
838
|
+
this.st((s) => { if (s.in[id]) Object.assign(s.in[id], { state: 'done', got: r.size, at: this.now(), saved: path, path_used: a?.path ?? s.in[id].path_used ?? null }); delete s.in[id]?.reason; delete s.in[id]?.detail; });
|
|
839
|
+
if (a) { this.attempts.delete(id); setTimeout(() => this.closeAttempt(a), 2000).unref?.(); }
|
|
840
|
+
carrier.deliver({ type: 'file', from: c.did, contact: c.name, current_did: c.current_did, label: FILE_LABEL, name: r.name, size: r.size, sha256: r.sha256, path, transfer: id, via: a?.path ?? null });
|
|
841
|
+
await sendMsg(carrier, r.from, { typ: 'end', id, reason: 'done', ...(a && { attempt: a.attempt }) }, false).catch(() => {});
|
|
842
|
+
this.emit('done', { id, side: 'in', name: r.name, path, via: a?.path ?? null, rate: a?.rate ?? null });
|
|
843
|
+
}
|
|
844
|
+
interrupt(id, reason, detail) {
|
|
845
|
+
this.st((s) => { const r = s.in[id]; if (r && STATES_LIVE_IN.includes(r.state)) Object.assign(r, { state: 'interrupted', reason, detail, retryAt: Date.now() + this.retryMs, last: this.now() }); });
|
|
846
|
+
this.emit('interrupted', { id, side: 'in', reason });
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/** Without an engine (a CLI inbox, transfer list): the manifests and ends the carrier kept, filed. → the files now asked. */
|
|
851
|
+
export async function intake({ carrier, io, compared }) {
|
|
852
|
+
const e = new Engine({ carrier, io, compared, timer: false });
|
|
853
|
+
const asked = [];
|
|
854
|
+
e.onEvent = (x) => { if (x.what === 'asked') asked.push(x); };
|
|
855
|
+
await e.round((m) => ['manifest', 'end'].includes(m?.content?.typ) && m.content.reason !== 'try_tor');
|
|
856
|
+
await e.close();
|
|
857
|
+
return asked;
|
|
858
|
+
}
|