diff --git a/CHANGELOG.md b/CHANGELOG.md index 87ee0ea..4c5dadb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,45 @@ All notable changes to the AVA1 crates and C library. The wire format is version 1 throughout; see [README](README.md#versions). +## Unreleased + +Fixes from an audit of what a peer can make a node do. The wire format and what is written on disk do +not change; a correct peer sees no difference. + +C library: + +- A FileRoot that arrives while a new manifest of the same job is being taken up waits for it. Before, + it could be written into a large-file state the job thread had just freed (a use-after-free). +- A download `JobOpen` starts over only a download of its id, and only this device's or one no session + drives. Before, it freed whatever job had the id: another device's upload, a copy, a send to another + console. Another kind of job under the id is refused with `ERR_PROTOCOL`, another device's running + download with `ERR_UNKNOWN_JOB`. +- An upload whose commit or end failed on an I/O error (a rename, a folder sync) resumes from its + journal. Before, the journaled `Done(ERR_IO)` answered every later `JobOpen` with "all done" and the + same failure. Only `OK`, `ERR_EXISTS` and `ERR_CROSS_DEVICE` end a job for good, as for a job still in + memory; journals written by older versions resume the same way. +- A sender's `JobMap` is read against the manifest: each done file once, durable ranges inside a file + and no more of them than it has groups. A map that names more ends the job with `ERR_PROTOCOL` + (before, the pages were stored as they came). +- A FileRoot, ManifestEnd or Resume waiting in a job's inbox is kept at its own size, not as the 64 KiB + frame it may come in. +- The download sender uses at most 64 MiB of window, whatever it is granted (its frames in flight stay + in memory until their `Received`). +- A device blocked by the `refused` hook stays blocked when its ClientInfo carries a token: only a + ticket this node holds for the key skips the device rules. +- A merge refuses (`ERR_PATH`) a manifest that names both a file `P` and `P.ava-part` in any letter + case: `P` is written through `P.ava-part`, so the two shared one file. Refused before the manifest is + stored or journaled. `ava1_mstore_part_clash`. + +Rust sender: + +- The receiver (`LocalSink`) refuses the same `P` + `P.ava-part` manifest in a merge, and runs the + manifest checks that need no disk (`Sink::check`, new, default none) before it writes the job's + journal and stored manifest. Before, a merge download of such a tree reported success with the two + files mixed, and a refused manifest was journaled first. `manifest::part_name_clash`, `PART_SUFFIX`. +- `Need::add_page_bounded` reads a map against the job's manifest, and the sender uses it; a `Durable` + naming files past the manifest ends the job with a protocol error. `RangeSet::len` and `is_empty`. + ## 1.0.12 Read-back progress, and no second read-back of a resumed file in the same process. The wire format gains one diff --git a/c/ava1_apply.c b/c/ava1_apply.c index 57e2cf9..0455237 100644 --- a/c/ava1_apply.c +++ b/c/ava1_apply.c @@ -736,6 +736,15 @@ int ava1_apply_bundle_pooled(ava1_job_t *j, uint8_t *owned, size_t owned_len, si int ava1_apply_root(ava1_job_t *j, uint32_t file_id, const uint8_t root[32]) { int rc = 0; pthread_mutex_lock(&j->mu); + /* A FileRoot that follows a ManifestEnd names the new manifest's ids, and while the job thread + * adopts it the old large-file states are moved and freed without j->mu (remap): wait until + * the new manifest is the job's. Frames are taken in order, so one sent before that ManifestEnd + * was applied before it was handed over (ev_end). */ + while ((j->ev_end || j->adopting || j->feed_hold) && !j->stopping) pthread_cond_wait(&j->cv, &j->mu); + if (j->stopping) { + pthread_mutex_unlock(&j->mu); + return 0; /* the job ends: the root goes with it */ + } if (file_id >= j->m.n || j->m.e[file_id].kind != AVA1_ENTRY_FILE) { rc = AVA1_E_PROTO; } else { @@ -3848,8 +3857,8 @@ static void commit_large(ava1_job_t *j, uint32_t id) { return; } } - if (rename(part, fin) != 0) { - int e = errno; + if ((err = ava1_apply_fault ? ava1_apply_fault(j, AVA1_HOOK_RENAMED, id) : 0) != 0 || rename(part, fin) != 0) { + int e = err ? err : errno; if (in_the_way(e)) commit_fail(j, AVA1_ERR_EXISTS, "something is already where the file goes", e, 1); else commit_fail(j, AVA1_ERR_IO, "rename into place failed", e, 1); return; diff --git a/c/ava1_apply.h b/c/ava1_apply.h index 2332c94..58df6c7 100644 --- a/c/ava1_apply.h +++ b/c/ava1_apply.h @@ -120,7 +120,8 @@ extern size_t ava1_test_pwrite_max; extern uint32_t ava1_test_chunk_delay_ms; extern void (*ava1_apply_hook)(ava1_job_t *j, int point, uint32_t id); /* Tests only (NULL in the payload): an errno to inject at a point instead of doing the work. - * Consulted at AVA1_HOOK_DIR_SYNCED of the staged tree's rename. */ + * Consulted at AVA1_HOOK_DIR_SYNCED of the staged tree's rename and at AVA1_HOOK_RENAMED of a large + * file's rename into place (before it). */ extern int (*ava1_apply_fault)(ava1_job_t *j, int point, uint32_t id); /* Tests only (NULL in the payload): JF_READBACK is about to read bytes [off, off + len) of file `id` back * through `fd` (its own descriptor, opened for writing too), `live` while the file still arrives, else in diff --git a/c/ava1_data.c b/c/ava1_data.c index 3ec1191..d3a6548 100644 --- a/c/ava1_data.c +++ b/c/ava1_data.c @@ -31,7 +31,7 @@ uint32_t ava1_data_test_map_delay_ms; int ava1_data_test_ack_fail; int ava1_data_test_feeder_fail; uint32_t ava1_data_test_feed_delay_ms; -uint32_t ava1_data_test_feed_check_delay_ms, ava1_data_test_reprep_delay_ms; +uint32_t ava1_data_test_feed_check_delay_ms, ava1_data_test_reprep_delay_ms, ava1_data_test_remap_delay_ms; int ava1_data_test_reserve_fail; int ava1_data_test_lane_alloc_fail; int ava1_data_test_fb_force; @@ -392,7 +392,7 @@ int ava1_data_start(const ava1_data_cfg_t *cfg) { D.admitted = 0; __atomic_store_n(&g_unswept_total, 0, __ATOMIC_RELAXED); /* a new data layer holds no job's log bytes */ ava1_data_test_open_delay_ms = ava1_data_test_map_delay_ms = ava1_data_test_feed_delay_ms = 0; - ava1_data_test_feed_check_delay_ms = ava1_data_test_reprep_delay_ms = 0; + ava1_data_test_feed_check_delay_ms = ava1_data_test_reprep_delay_ms = ava1_data_test_remap_delay_ms = 0; ava1_data_test_open_work_delay_ms = 0; ava1_data_test_ack_fail = ava1_data_test_feeder_fail = 0; ava1_data_test_reserve_fail = ava1_data_test_lane_alloc_fail = ava1_data_test_fb_force = 0; @@ -690,6 +690,7 @@ static void feed_done(ava1_job_t *j) { void ava1_data_feed_hold(ava1_job_t *j, int hold) { pthread_mutex_lock(&j->mu); j->feed_hold = hold; + if (!hold) pthread_cond_broadcast(&j->cv); /* a FileRoot waits for the end of a hold (ava1_apply_root) */ while (hold && j->feeding) pthread_cond_wait(&j->cv, &j->mu); pthread_mutex_unlock(&j->mu); } @@ -825,9 +826,37 @@ static void *feed_main(void *arg) { return NULL; } +/* A FileRoot, ManifestEnd or Resume has a fixed size, but its control frame may be 64 KiB: what + * waits in an inbox is the message re-encoded (unknown ext fields dropped, as the decoder drops + * them), not the frame. One that does not decode is kept empty: it fails to decode again where + * it is taken, as before. Other frames are kept as they came. */ +static size_t compact_ctl(uint8_t type, const uint8_t **body, size_t len, uint8_t *buf, size_t cap) { + ava1_w_t w; + int rc = -1; + ava1_w_init(&w, buf, cap); + if (type == AVA1_TYPE_FILE_ROOT) { + ava1_file_root_t r; + rc = ava1_file_root_decode(*body, len, &r) == 0 ? ava1_file_root_encode(&r, &w) : -1; + } else if (type == AVA1_TYPE_MANIFEST_END) { + ava1_manifest_end_t e; + rc = ava1_manifest_end_decode(*body, len, &e) == 0 ? ava1_manifest_end_encode(&e, &w) : -1; + } else if (type == AVA1_TYPE_RESUME) { + ava1_resume_t r; + rc = ava1_resume_decode(*body, len, &r) == 0 ? ava1_resume_encode(&r, &w) : -1; + } else { + return len; + } + *body = buf; + return rc == 0 ? w.len : 0; +} + static void inbox_add(ava1_job_t *j, uint8_t type, const uint8_t *body, size_t len) { - ava1_inframe_t *f = calloc(1, sizeof *f); - uint8_t *b = malloc(len ? len : 1); + uint8_t small[128]; + ava1_inframe_t *f; + uint8_t *b; + len = compact_ctl(type, &body, len, small, sizeof small); + f = calloc(1, sizeof *f); + b = malloc(len ? len : 1); if (!f || !b) { free(f); free(b); diff --git a/c/ava1_data.h b/c/ava1_data.h index dde4a99..779b4b6 100644 --- a/c/ava1_data.h +++ b/c/ava1_data.h @@ -174,6 +174,7 @@ extern int ava1_data_test_feeder_fail; /* a job's feeder thread "cannot star extern uint32_t ava1_data_test_feed_delay_ms; /* the feeder waits this long after taking lane frames */ extern uint32_t ava1_data_test_feed_check_delay_ms; /* ... and this long between checking one and queuing it */ extern uint32_t ava1_data_test_reprep_delay_ms; /* a new manifest's re-prepare waits this long first */ +extern uint32_t ava1_data_test_remap_delay_ms; /* ... and this long inside the remap, the old states freed */ extern int ava1_data_test_reserve_fail; /* ava1_apply_reserve "fails" for every lane frame */ extern int ava1_data_test_lane_alloc_fail; /* the lane frame's calloc "fails" */ extern int ava1_data_test_fb_force; /* every Received goes through the waiting-send fallback */ diff --git a/c/ava1_job.c b/c/ava1_job.c index 5edd602..f05f647 100644 --- a/c/ava1_job.c +++ b/c/ava1_job.c @@ -523,6 +523,19 @@ int ava1_job_retire_parked(ava1_job_t *j) { return rc; } +int ava1_job_unlist(ava1_job_t *j, int parked_only) { + int rc = 0; + pthread_mutex_lock(&T.mu); + if (!listed_locked(j)) rc = -2; + else if (parked_only && j->attached) rc = -1; /* `attached` is written under T.mu */ + else { + unlist(j); + j->refs--; /* the table's: the caller still holds one */ + } + pthread_mutex_unlock(&T.mu); + return rc; +} + void ava1_job_emit(ava1_job_t *j, uint8_t type, uint8_t flags, const uint8_t *body, size_t len) { ava1_emit_fn fn; pthread_mutex_lock(&j->cmu); diff --git a/c/ava1_job.h b/c/ava1_job.h index b8d9ebb..3823824 100644 --- a/c/ava1_job.h +++ b/c/ava1_job.h @@ -108,8 +108,9 @@ struct ava1_job { int attached, refs, stopping, finished, prepared; /* Under mu. feeding: the feeder is between its `prepared` check and the engine's queue (it reads * m and enqueues work against it); feed_hold: the job thread is about to replace m (a new manifest - * in the same session), so the feeder hands nothing more to the engine until it is done. */ - int feeding, feed_hold; + * in the same session), so the feeder hands nothing more to the engine until it is done. + * adopting: the job thread took a ManifestEnd and has not answered it yet (ava1_apply_root waits). */ + int feeding, feed_hold, adopting; int discard_parts; /* a cancelled local copy: destroy removes the .ava-part files this job itself was writing */ uint64_t parked_at_ms; uint64_t concluded_ms; /* an upload or download: when its end went out (our JobDone) or came in (the peer's), @@ -333,6 +334,10 @@ int ava1_job_retire(ava1_job_t *j); * caller's reference. 0 = retired; -1 = a session is attached to it; -2 = someone else holds * it for the moment or its files are still settling (try again). */ int ava1_job_retire_parked(ava1_job_t *j); +/* Unlists `j` itself (never another job that holds its id by then) and drops the table's + * reference; the caller's stays, and its ava1_job_put may free the job. parked_only: not while a + * session drives it. 0 = unlisted; -1 = a session is attached to it; -2 = it was no longer listed. */ +int ava1_job_unlist(ava1_job_t *j, int parked_only); void ava1_job_emit(ava1_job_t *j, uint8_t type, uint8_t flags, const uint8_t *body, size_t len); /* Control-frame bytes queued across all jobs (their inboxes and the frames behind a diff --git a/c/ava1_manifest.c b/c/ava1_manifest.c index d8e17ac..c348afc 100644 --- a/c/ava1_manifest.c +++ b/c/ava1_manifest.c @@ -396,3 +396,64 @@ void ava1_mstore_free(ava1_mstore_t *m) { free(m->arena); memset(m, 0, sizeof *m); } + +/* ---- part names (ava1_mstore_part_clash) ------------------------------------------- */ + +#define PART_SUFFIX ".ava-part" +#define PART_SUFFIX_LEN 9u + +static int lower(int c) { return c >= 'A' && c <= 'Z' ? c + 32 : c; } + +static uint32_t fnv_ci(const char *s, size_t n) { + uint32_t h = 2166136261u; + size_t i; + for (i = 0; i < n; i++) h = (h ^ (uint8_t)lower((uint8_t)s[i])) * 16777619u; + return h; +} + +static int eq_ci(const char *a, const char *b, size_t n) { + size_t i; + for (i = 0; i < n; i++) + if (lower((uint8_t)a[i]) != lower((uint8_t)b[i])) return 0; + return 1; +} + +int ava1_mstore_part_clash(const ava1_mstore_t *m, uint32_t *file, uint32_t *entry) { + uint32_t i, k = 0, cap = 1, *slot; + int found = 0; + /* Only the entries named like a part file go in the set: usually none at all. */ + for (i = 0; i < m->n; i++) { + const char *p = ava1_mstore_path(m, i); + size_t l = strlen(p); + if (l > PART_SUFFIX_LEN && eq_ci(p + l - PART_SUFFIX_LEN, PART_SUFFIX, PART_SUFFIX_LEN)) k++; + } + if (!k) return 0; + while (cap < 2u * k + 2u) cap *= 2; + if (!(slot = calloc(cap, sizeof *slot))) return -1; + for (i = 0; i < m->n; i++) { + const char *p = ava1_mstore_path(m, i); + size_t l = strlen(p); + uint32_t h; + if (l <= PART_SUFFIX_LEN || !eq_ci(p + l - PART_SUFFIX_LEN, PART_SUFFIX, PART_SUFFIX_LEN)) continue; + h = fnv_ci(p, l - PART_SUFFIX_LEN) & (cap - 1); + while (slot[h]) h = (h + 1) & (cap - 1); + slot[h] = i + 1; + } + for (i = 0; i < m->n && !found; i++) { + const char *p = ava1_mstore_path(m, i); + size_t l = strlen(p); + uint32_t h, q; + if (m->e[i].kind != AVA1_ENTRY_FILE) continue; + for (h = fnv_ci(p, l) & (cap - 1); (q = slot[h]) != 0; h = (h + 1) & (cap - 1)) { + const char *qp = ava1_mstore_path(m, q - 1); + if (strlen(qp) == l + PART_SUFFIX_LEN && eq_ci(qp, p, l)) { + *file = i; + *entry = q - 1; + found = 1; + break; + } + } + } + free(slot); + return found; +} diff --git a/c/ava1_manifest.h b/c/ava1_manifest.h index dc3a261..af09709 100644 --- a/c/ava1_manifest.h +++ b/c/ava1_manifest.h @@ -59,5 +59,9 @@ int ava1_mstore_walk_deny(ava1_mstore_t *m, const char *root, unsigned flags, in int ava1_open_read_safe(const char *path, int (*deny)(const char *abs)); int ava1_mstore_single(ava1_mstore_t *m, const char *file); /* JF_SINGLE_FILE */ void ava1_mstore_free(ava1_mstore_t *m); +/* In a merge (SPEC.md §11.6) a file `P` is written as `P.ava-part` beside it, so a manifest that + * also names `P.ava-part` (in any letter case: a drive may fold it) would have the two share a name. + * 1 with the file's id and the clashing entry's id, 0 when there is none, -1 out of memory. */ +int ava1_mstore_part_clash(const ava1_mstore_t *m, uint32_t *file, uint32_t *entry); #endif diff --git a/c/ava1_recv.c b/c/ava1_recv.c index 6f3ecd0..2e46585 100644 --- a/c/ava1_recv.c +++ b/c/ava1_recv.c @@ -301,6 +301,13 @@ static void drop_state(ava1_job_t *j) { j->have_manifest = j->replay_done = j->staged = j->dest_held = 0; } +/* The statuses that end a job for good, as for one still in memory (ava1_recv_open): done, or a + * destination the job must not touch. Any other (an I/O failure at a commit or at the end) is + * where its last run stopped, and a JobOpen takes it up again from its journal. */ +static int done_is_final(uint16_t status) { + return status == AVA1_STATUS_OK || status == AVA1_ERR_EXISTS || status == AVA1_ERR_CROSS_DEVICE; +} + /* Loads /manifest and replays /journal. 0 when a usable earlier job was found: * the journal opens for this job and root, and was written for exactly this manifest. */ static int load_from_disk(ava1_job_t *j) { @@ -327,6 +334,10 @@ static int load_from_disk(ava1_job_t *j) { return -1; } j->have_manifest = 1; + /* A journaled Done(ERR_IO) is not an answer: the map is the replayed state, and the commit or + * rename that failed runs again (reconcile finds a file whose rename went through). Before, a + * resume was told every file was done and got the same failure, every time. */ + if (j->replay_done && !done_is_final(j->replay_status)) j->replay_done = 0; /* Durable-by-log recovery (§4): the files the journal calls done but not yet swept are made again from * the pack log where a crash lost them, and swept, before anything is counted or answered. */ refs_prune(&r); @@ -624,6 +635,7 @@ ava1_job_t *ava1_recv_open(const ava1_recv_spec_t *s, ava1_job_open_ack_t *ack, ava1_mstore_free(&j->m_in); if (s->entries) (void)ava1_mstore_reserve(&j->m_in, s->entries); j->ev_end = j->ev_resume = 0; + pthread_cond_broadcast(&j->cv); /* a FileRoot waiting for that ManifestEnd (ava1_apply_root) */ /* The new sender starts from what is free now. Credit freed while detached is * already counted here, so it must not also be flushed as a Credit message. */ ack->credit = j->credit > j->outstanding ? j->credit - j->outstanding : 0; @@ -832,12 +844,17 @@ static int remap(ava1_job_t *j, ava1_mstore_t *in, ava1_bits_t *changed) { drop_path(p, 1, d, &nd); } } - /* Second step of the outboard renames; drop the outboards nobody carried. */ + /* Second step of the outboard renames; drop the outboards nobody carried. The states freed + * here are only safe to free because nothing else touches j->lf while the job thread + * re-prepares: the feeder hands no lane frame over (feed_hold) and a FileRoot waits for the + * new manifest (ava1_apply_root). */ for (i = 0; i < j->m.n; i++) { snprintf(a, sizeof a, "%s/%u.ob", j->dir, i); (void)unlink(a); free_lf(j, i, j->lf[i]); + j->lf[i] = NULL; } + if (ava1_data_test_remap_delay_ms) ava1_platform_sleep_ms(ava1_data_test_remap_delay_ms); for (i = 0; i < in->n; i++) if (nlf[i]) { snprintf(a, sizeof a, "%s/%u.ob.m", j->dir, i); @@ -1378,7 +1395,19 @@ static uint16_t adopt(ava1_job_t *j, ava1_mstore_t *in, const uint8_t hash[32], return AVA1_STATUS_OK; } +static void recv_events_take(ava1_job_t *j); + +/* `adopting` covers a ManifestEnd from the moment it is taken until its map is out: a FileRoot + * that follows it names the new manifest's ids, and remap frees the old large-file states. */ static void recv_events(ava1_job_t *j) { + recv_events_take(j); + pthread_mutex_lock(&j->mu); + j->adopting = 0; + pthread_cond_broadcast(&j->cv); + pthread_mutex_unlock(&j->mu); +} + +static void recv_events_take(ava1_job_t *j) { int end, res; ava1_mstore_t in; uint32_t efiles; @@ -1390,6 +1419,7 @@ static void recv_events(ava1_job_t *j) { end = j->ev_end; res = j->ev_resume; j->ev_end = j->ev_resume = 0; + if (end) j->adopting = 1; in = j->m_in; memset(&j->m_in, 0, sizeof j->m_in); efiles = j->end_files; @@ -1416,6 +1446,24 @@ static void recv_events(ava1_job_t *j) { emit_map(j, AVA1_ERR_PROTOCOL, "the manifest does not match its end"); return; } + /* A merge writes each file through `.ava-part` beside it: an entry of that name would share + * it with the file's part, and either one's bytes would land in the other. Refused before the + * manifest is stored or journaled (and for one an earlier version stored: it is checked again). */ + if (!j->staged && !(j->flags & AVA1_JF_SINGLE_FILE)) { + uint32_t pf, pe; + int c = ava1_mstore_part_clash(&in, &pf, &pe); + if (c != 0) { + if (c > 0) + snprintf(msg, sizeof msg, "%.48s is the name %.48s is written under until it is complete", + ava1_mstore_path(&in, pe), ava1_mstore_path(&in, pf)); + else snprintf(msg, sizeof msg, "out of memory"); + ava1_mstore_free(&in); + st = c > 0 ? AVA1_ERR_PATH : AVA1_ERR_INTERNAL; + emit_map(j, st, msg); + ava1_apply_fail(j, st, msg, 0, 0); + return; + } + } if (j->have_manifest && memcmp(hash, j->manifest_hash, 32) == 0) { ava1_mstore_free(&in); /* the same manifest: the replayed state stands */ } else { diff --git a/c/ava1_send.c b/c/ava1_send.c index 18e64f8..294606f 100644 --- a/c/ava1_send.c +++ b/c/ava1_send.c @@ -12,12 +12,17 @@ #include "ava1_apply.h" #include "ava1_b3.h" #include "ava1_events.h" +#include "ava1_internal.h" #include "ava1_data.h" #include "ava1_platform.h" #include "ava1_server.h" #include "ava1_thread.h" #define READ_AHEAD (32u << 20) +/* The most window the sender uses, whatever the receiver grants: frames in flight stay in memory + * until their Received, so the window is what bounds them. A version 1 receiver grants 64 MiB + * (SPEC.md §12.4); credit past this is left unused, never refused. */ +#define WINDOW_MAX (64ull << 20) static uint64_t now_us(void) { struct timespec t; @@ -199,6 +204,7 @@ typedef struct sframe { typedef struct { uint64_t credit, queued; + uint64_t map_ids, map_ranges; /* what the map's pages named so far: bounded by the manifest */ sframe_t *ready, *ready_tail, *inflight; uint32_t next_page; int pages_done, have_map, reading, stop, unsafe_read, single; @@ -343,6 +349,12 @@ typedef struct { } wctx2_t; static uint64_t sat_add(uint64_t a, uint64_t b) { return a > UINT64_MAX - b ? UINT64_MAX : a + b; } +/* Adds to the window, at most WINDOW_MAX: the bytes are peer-controlled (no wrap, no unbounded + * read-ahead in flight). */ +static uint64_t window_add(uint64_t a, uint64_t b) { + uint64_t v = sat_add(a, b); + return v > WINDOW_MAX ? WINDOW_MAX : v; +} static void unlink_inflight(snd_t *s, sframe_t *f) { sframe_t **pp; @@ -413,7 +425,7 @@ static int settle_locked(snd_t *s, sframe_t *f, int rc) { if (rc != 0) { /* Never delivered: the charge comes back here, and the frame goes again. */ unlink_inflight(s, f); - s->credit = sat_add(s->credit, f->len); + s->credit = window_add(s->credit, f->len); requeue_front(s, f); } else if (dead) { /* Sent on a lane that died meanwhile (the sweep left it to us): it may be on the @@ -641,17 +653,45 @@ static sframe_t *received_locked(ava1_job_t *j, snd_t *s, uint32_t seq) { } /* More window from the receiver (caller holds mu). Credit frames are incremental (R2); - * the bytes are peer-controlled, so the add saturates instead of wrapping. */ -static void credit_locked(snd_t *s, uint64_t n) { s->credit = sat_add(s->credit, n); } + * the bytes are peer-controlled, so the add saturates at WINDOW_MAX instead of wrapping. */ +static void credit_locked(snd_t *s, uint64_t n) { s->credit = window_add(s->credit, n); } + +/* One JobMap page against the manifest (caller holds mu): what a receiver may name is bounded by + * it, so pages cannot grow memory or work past it. A receiver's map names each done file once + * (disjoint runs) and, per unfinished file, disjoint durable ranges inside it that start on group + * boundaries: at most one per group. 0, or -1 for a map no receiver builds. */ +static int map_page_locked(ava1_job_t *j, snd_t *s, const ava1_job_map_t *m) { + ava1_r_t it; + ava1_file_run_t r; + ava1_file_range_t g; + int k; + ava1_r_init(&it, m->done, m->done_len); + while ((k = ava1_file_run_next(&it, &r)) == 1) { + uint64_t hi = (uint64_t)r.first + r.count, f; + if (hi > j->m.n || (s->map_ids += r.count) > j->m.n) return -1; + for (f = r.first; f < hi; f++) ava1_bits_set(&s->skip, (uint32_t)f); + } + if (k != 0) return -1; + ava1_r_init(&it, m->partial, m->partial_len); + while ((k = ava1_file_range_next(&it, &g)) == 1) { + uint64_t size, end; + if (g.file_id >= j->m.n || j->m.e[g.file_id].kind != AVA1_ENTRY_FILE) return -1; + size = j->m.e[g.file_id].size; + end = sat_add(g.offset, g.len); + if (end > size || ++s->map_ranges > j->m.bytes / AVA1_GROUP_LEN + j->m.n) return -1; + if (!s->durable[g.file_id]) s->durable[g.file_id] = calloc(1, sizeof(ava1_rset_t)); + if (!s->durable[g.file_id]) continue; /* no memory: the bytes are sent again */ + (void)ava1_rset_add(s->durable[g.file_id], g.offset, end); + if ((uint64_t)s->durable[g.file_id]->n > ava1_groups_of(size)) return -1; + } + return k == 0 ? 0 : -1; +} static int on_frame(ava1_job_t *j, uint8_t type, const uint8_t *body, size_t len) { snd_t *s = S_(j); switch (type) { case AVA1_TYPE_JOB_MAP: { ava1_job_map_t m; - ava1_r_t it; - ava1_file_run_t r; - ava1_file_range_t g; if (ava1_job_map_decode(body, len, &m) != 0) return 1; if (m.status != AVA1_STATUS_OK) { /* A reader-thread hook never ends a job itself (C4): the job thread does. */ @@ -666,16 +706,10 @@ static int on_frame(ava1_job_t *j, uint8_t type, const uint8_t *body, size_t len pthread_mutex_unlock(&j->mu); return 0; } - ava1_r_init(&it, m.done, m.done_len); - while (ava1_file_run_next(&it, &r) == 1) { - uint32_t f; - for (f = r.first; f < r.first + r.count && f < j->m.n; f++) ava1_bits_set(&s->skip, f); - } - ava1_r_init(&it, m.partial, m.partial_len); - while (ava1_file_range_next(&it, &g) == 1) { - if (g.file_id >= j->m.n) continue; - if (!s->durable[g.file_id]) s->durable[g.file_id] = calloc(1, sizeof(ava1_rset_t)); - if (s->durable[g.file_id]) (void)ava1_rset_add(s->durable[g.file_id], g.offset, g.offset + g.len); + if (map_page_locked(j, s, &m) != 0) { + pthread_mutex_unlock(&j->mu); + ava1_data_fail_soon(j, AVA1_ERR_PROTOCOL, "the receiver's map names files or bytes the manifest does not have"); + return 0; } if (m.last) s->have_map = 1; pthread_mutex_unlock(&j->mu); @@ -856,7 +890,29 @@ ava1_job_t *ava1_send_open(const ava1_job_open_t *o, const uint8_t peer[32], ava snprintf(msg, cap, "%s: %s", root, strerror(errno)); return NULL; } - ava1_job_free_one(o->job_id); /* a sender's state lives only in memory: start over */ + /* A sender's state lives only in memory: a download of this id starts over. Only a download, + * and only this device's or one no session drives (as an upload moves to another device, #444): + * any other job under the id (an upload, a copy, a send to another console, a download another + * session is running) is not this JobOpen's to end. */ + if ((j = ava1_job_find(o->job_id)) != NULL) { + int download, mine; + pthread_mutex_lock(&j->mu); + download = j->kind == AVA1_JOB_DOWNLOAD && !j->c2c; + mine = memcmp(j->owner, peer, 32) == 0; + pthread_mutex_unlock(&j->mu); + rc = download ? ava1_job_unlist(j, !mine) : 1; + ava1_job_put(j); + if (rc == 1) { + ack->status = AVA1_ERR_PROTOCOL; + snprintf(msg, cap, "another job is running under this id"); + return NULL; + } + if (rc == -1) { + ack->status = AVA1_ERR_UNKNOWN_JOB; + snprintf(msg, cap, "this job belongs to another device"); + return NULL; + } + } j = ava1_job_create(o->job_id, peer); s = j ? calloc(1, sizeof *s) : NULL; if (s) pthread_mutex_init(&s->pump_mu, NULL); @@ -879,7 +935,7 @@ ava1_job_t *ava1_send_open(const ava1_job_open_t *o, const uint8_t peer[32], ava s->t_open = now_us(); rc = s->single ? ava1_mstore_single(&j->m, root) : ava1_mstore_walk_deny(&j->m, root, AVA1_WALK_FOLLOW, cfg->refuse_link); s->walk_us = now_us() - s->t_open; - s->credit = o->has_credit ? o->credit : (16u << 20); + s->credit = window_add(0, o->has_credit ? o->credit : (16u << 20)); if (rc != 0 || ava1_bits_init(&s->skip, j->m.n) != 0 || !(s->durable = calloc((size_t)j->m.n + 1, sizeof *s->durable)) || !(j->lf = calloc((size_t)j->m.n + 1, sizeof *j->lf)) || ava1_bits_init(&j->done, j->m.n) != 0) { diff --git a/c/ava1_server.c b/c/ava1_server.c index b7e324f..e9edc86 100644 --- a/c/ava1_server.c +++ b/c/ava1_server.c @@ -1200,9 +1200,25 @@ static void run_control(conn_t *k, uint8_t *buf, size_t len) { (void)send_error(&k->io, AVA1_ERR_BUSY, "too many sessions"); goto out; } + /* Another console with a ticket for one job (SPEC.md §18). Only a ticket this console holds for + * this key counts: a token that is none is a device like any other, under the rules below (a + * blocked device must not get past `refused` by sending one). The ticket decides even for a + * key that is also paired: a console that dials with a ticket gets the ticket's session (its + * one job, as the ticket's owner), never a full paired one. */ + if (ci.has_token) { + pthread_mutex_lock(&mu); + ticket = ticket_take_locked(ns.rs, ci.token); + if (ticket >= 0) { + terms.restricted = 1; + memcpy(terms.r_job, tickets[ticket].job, 16); + memcpy(terms.r_owner, tickets[ticket].owner, 32); + snprintf(terms.r_root, sizeof terms.r_root, "%s", tickets[ticket].root); + } + pthread_mutex_unlock(&mu); + } /* The owner's rules for devices (admit_new / refused) decide before the pairing rules. A - * console with a ticket is not a device joining: its ticket decides below. */ - if (!ci.has_token && (S.cfg.admit_new || S.cfg.refused)) { + * console with a ticket is not a device joining: its ticket decided above. */ + if (ticket < 0 && (S.cfg.admit_new || S.cfg.refused)) { int trusted, verdict = 0; pthread_mutex_lock(&mu); trusted = ava1_peers_contains(&S.peers, ns.rs); @@ -1220,17 +1236,9 @@ static void run_control(conn_t *k, uint8_t *buf, size_t len) { pthread_mutex_lock(&mu); known = ava1_peers_contains(&S.peers, ns.rs); open = now_ms() < S.pairing_until_ms; - /* Another console with a ticket for one job (SPEC.md §18). The ticket decides even for a key - * that is also paired: a console that dials with a ticket gets the ticket's session (its one - * job, as the ticket's owner), never a full paired one. */ - if (ci.has_token) ticket = ticket_take_locked(ns.rs, ci.token); if (ticket >= 0) { known = 1; open = 0; - terms.restricted = 1; - memcpy(terms.r_job, tickets[ticket].job, 16); - memcpy(terms.r_owner, tickets[ticket].owner, 32); - snprintf(terms.r_root, sizeof terms.r_root, "%s", tickets[ticket].root); } /* Message 3 has just proved the client holds ns.rs: any session that key still has * is replaced, before the limits below. */ diff --git a/crates/ava1-ctest/csrc/test_shim.c b/crates/ava1-ctest/csrc/test_shim.c index 69a311e..996300b 100644 --- a/crates/ava1-ctest/csrc/test_shim.c +++ b/crates/ava1-ctest/csrc/test_shim.c @@ -145,6 +145,25 @@ size_t ava1_test_sizeof_pairlimit(void) { return sizeof(ava1_pairlimit_t); } size_t ava1_test_sizeof_opts(void) { return sizeof(ava1_test_opts_t); } +/* The key the server's `refused` hook blocks (ava1_test_refuse_key; all zero: none, which no + * peer's public key is). */ +static uint8_t g_refused_key[32]; +static pthread_mutex_t g_refused_mu = PTHREAD_MUTEX_INITIALIZER; +static int t_refused(const uint8_t key[32]) { + static const uint8_t zero[32]; + int r; + pthread_mutex_lock(&g_refused_mu); + r = memcmp(g_refused_key, zero, 32) != 0 && memcmp(g_refused_key, key, 32) == 0; + pthread_mutex_unlock(&g_refused_mu); + return r; +} +void ava1_test_refuse_key(const uint8_t *key) { + pthread_mutex_lock(&g_refused_mu); + if (key) memcpy(g_refused_key, key, 32); + else memset(g_refused_key, 0, 32); + pthread_mutex_unlock(&g_refused_mu); +} + int ava1_test_server_start(const uint8_t secret[32], const char *peers_path, const ava1_test_opts_t *o) { ava1_server_cfg_t cfg; int rc; @@ -181,6 +200,8 @@ int ava1_test_server_start(const uint8_t secret[32], const char *peers_path, con cfg.on_pair_request = on_pair; cfg.log = on_log; cfg.rpc = rpc; + cfg.refused = t_refused; + ava1_test_refuse_key(NULL); __atomic_store_n(&g_logs, 0, __ATOMIC_SEQ_CST); __atomic_store_n(&g_pair_requests, 0, __ATOMIC_SEQ_CST); __atomic_store_n(&g_last_code, 0, __ATOMIC_SEQ_CST); @@ -1426,6 +1447,7 @@ uint32_t ava1_test_apply_commits_inflight(void) { void ava1_test_apply_trace(int on) { __atomic_store_n(&g_trace, on, __ATOMIC_SEQ_CST); } static uint32_t g_fault_id = UINT32_MAX - 1; /* no file: no fault */ +static uint32_t g_rename_fail; /* file id + 1 whose next rename into place fails (EBUSY); 0 none */ static int g_sweep_fail_n; /* sweeps' file syncs fail with EIO this many times (-1: until cleared) */ int ava1_test_sweep_fail_left(void) { return __atomic_load_n(&g_sweep_fail_n, __ATOMIC_SEQ_CST); } void ava1_test_sweep_fail(int n) { __atomic_store_n(&g_sweep_fail_n, n, __ATOMIC_SEQ_CST); } @@ -1444,6 +1466,11 @@ static int t_fault(ava1_job_t *j, int point, uint32_t id) { } if (point == AVA1_HOOK_BATCH_ALLOC && __atomic_exchange_n(&g_batch_alloc_fail, 0, __ATOMIC_SEQ_CST)) return ENOMEM; if (point == AVA1_HOOK_PREALLOC && id == __atomic_load_n(&g_prealloc_fault, __ATOMIC_SEQ_CST)) return ENOSPC; + if (point == AVA1_HOOK_RENAMED && id != UINT32_MAX) { /* one-shot: knob rename_fail = file id + 1 */ + uint32_t want = id + 1; + if (__atomic_compare_exchange_n(&g_rename_fail, &want, 0, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) return EBUSY; + return 0; + } return point == AVA1_HOOK_DIR_SYNCED && id == __atomic_load_n(&g_fault_id, __ATOMIC_SEQ_CST) ? EIO : 0; } void ava1_test_apply_fail_dir_sync(uint32_t id) { __atomic_store_n(&g_fault_id, id, __ATOMIC_SEQ_CST); } @@ -2054,6 +2081,7 @@ int ava1_test_server_start_data(const uint8_t secret[32], const char *peers_path __atomic_store_n(&ava1_send_test_fail_sends, 0, __ATOMIC_SEQ_CST); /* the download sender's knobs */ __atomic_store_n(&ava1_send_test_fail_writer_starts, 0, __ATOMIC_SEQ_CST); __atomic_store_n(&g_fault_id, UINT32_MAX - 1, __ATOMIC_SEQ_CST); + __atomic_store_n(&g_rename_fail, 0, __ATOMIC_SEQ_CST); __atomic_store_n(&ava1_copy_test_crash_before_delete, 0, __ATOMIC_SEQ_CST); __atomic_store_n(&ava1_copy_test_delete_delay_ms, 0, __ATOMIC_SEQ_CST); __atomic_store_n(&ava1_copy_test_delete_active, 0, __ATOMIC_SEQ_CST); @@ -2329,6 +2357,8 @@ int ava1_test_data_knob(const char *name, uint32_t v) { else if (!strcmp(name, "feed_delay_ms")) ava1_data_test_feed_delay_ms = v; else if (!strcmp(name, "feed_check_delay_ms")) ava1_data_test_feed_check_delay_ms = v; else if (!strcmp(name, "reprep_delay_ms")) ava1_data_test_reprep_delay_ms = v; + else if (!strcmp(name, "remap_delay_ms")) ava1_data_test_remap_delay_ms = v; + else if (!strcmp(name, "rename_fail")) __atomic_store_n(&g_rename_fail, v, __ATOMIC_SEQ_CST); else if (!strcmp(name, "store_save_delay_ms")) __atomic_store_n(&ava1_store_test_save_delay_ms, v, __ATOMIC_SEQ_CST); else if (!strcmp(name, "reserve_fail")) ava1_data_test_reserve_fail = (int)v; diff --git a/crates/ava1-ctest/src/lib.rs b/crates/ava1-ctest/src/lib.rs index 13696ef..74b5b1f 100644 --- a/crates/ava1-ctest/src/lib.rs +++ b/crates/ava1-ctest/src/lib.rs @@ -246,6 +246,7 @@ pub mod ffi { pub fn ava1_pl_spent(p: *const u8) -> c_int; pub fn ava1_pl_welcome_allowed(p: *mut u8, ip: u32, now_ms: u64) -> c_int; pub fn ava1_test_pair_requests() -> u32; + pub fn ava1_test_refuse_key(key: *const u8); pub fn ava1_test_last_pair_code() -> u32; pub fn ava1_test_logs() -> u32; pub fn ava1_server_open_pairing(seconds: u32); @@ -943,6 +944,14 @@ impl CServer { unsafe { ffi::ava1_server_pair_guesses() } } + /// The key the server's `refused` hook blocks (a device the user blocked), or none. + pub fn refuse_key(&self, key: Option<[u8; 32]>) { + match key { + Some(k) => unsafe { ffi::ava1_test_refuse_key(k.as_ptr()) }, + None => unsafe { ffi::ava1_test_refuse_key(std::ptr::null()) }, + } + } + pub fn pair_requests(&self) -> (u32, u32) { unsafe { ( diff --git a/crates/ava1-ctest/tests/download.rs b/crates/ava1-ctest/tests/download.rs index 80be285..6f95f62 100644 --- a/crates/ava1-ctest/tests/download.rs +++ b/crates/ava1-ctest/tests/download.rs @@ -436,12 +436,18 @@ fn a_received_during_the_send_leaves_the_frame_to_the_writer() { ); } -/// Minor 5: Credit.bytes is peer-controlled; a plain += wraps and shrinks the window. +/// Minor 5: Credit.bytes is peer-controlled; a plain += wraps and shrinks the window. S4: and a +/// window past 64 MiB is not used (frames in flight stay in memory until their Received). #[test] -fn peer_credit_overflow_saturates_instead_of_wrapping() { +fn peer_credit_overflow_saturates_at_the_window_cap_instead_of_wrapping() { let w = CSendWindow::new(u64::MAX / 2); w.credit(u64::MAX); - assert_eq!(w.state().credit, u64::MAX); + assert_eq!(w.state().credit, 64 << 20); + drop(w); // one window at a time (it holds the C sender's test state) + let w = CSendWindow::new(0); + w.credit(40 << 20); + w.credit(40 << 20); + assert_eq!(w.state().credit, 64 << 20); } /// Minor 6: a front frame larger than the credit no longer blocks a frame behind it @@ -913,6 +919,147 @@ async fn a_job_map_after_the_last_page_changes_nothing() { .expect("the test hung"); } +/// S4: the opener's map names files and bytes of the manifest the C sender sent, and nothing +/// else. Pre-fix a run past the manifest was skipped silently and any number of pages of disjoint +/// ranges was stored as it came (memory without bound); now such a map ends the job. +#[tokio::test(flavor = "multi_thread")] +async fn a_map_past_the_manifest_ends_the_download() { + tokio::time::timeout(Duration::from_secs(90), async { + ava1_ctest::c_set_read_allowed(true); + let d = dir("dl-bad-map"); + let src = d.join("console/tree"); + std::fs::create_dir_all(&src).unwrap(); + std::fs::write(src.join("a.bin"), vec![0x11u8; (2 << 20) + 5]).unwrap(); // 3 groups + let (me, mine) = paired_client(&d.join("peers")); + let srv = CServer::start_data( + SECRET, + &d.join("peers"), + &d.join("jobs"), + 200, + 2000, + 2000, + 0, + ); + let s = connect(&srv.addr(), me, mine, "rust", calm()) + .await + .unwrap(); + let range = |offset, len| gen::FileRange { + file_id: 0, + offset, + len, + }; + let bad: Vec> = vec![ + vec![JobMap { + done: vec![gen::FileRun { first: 0, count: 2 }], + ..Default::default() + }], + vec![JobMap { + partial: vec![range(1 << 20, 2 << 20)], + ..Default::default() + }], + // four disjoint ranges of a three-group file, over two pages + vec![ + JobMap { + partial: vec![range(0, 1), range(10, 1)], + ..Default::default() + }, + JobMap { + partial: vec![range(20, 1), range(30, 1)], + ..Default::default() + }, + ], + ]; + for (i, pages) in bad.into_iter().enumerate() { + let job = [0x70 + i as u8; 16]; + let mut link = s.job(job); + link.control + .send(&JobOpen { + job_id: job, + kind: gen::JOB_DOWNLOAD, + root: src.to_str().unwrap().into(), + credit: Some(64 << 20), + ..Default::default() + }) + .await + .unwrap(); + let ack: JobOpenAck = next_control_of(&mut link, JobOpenAck::TYPE) + .await + .decode() + .unwrap(); + assert_eq!(ack.status, 0); + next_control_of(&mut link, ManifestEnd::TYPE).await; + let n = pages.len(); + for (k, mut p) in pages.into_iter().enumerate() { + p.job_id = job; + p.last = u8::from(k + 1 == n); + link.control.send(&p).await.unwrap(); + } + let done: gen::JobDone = next_control_of(&mut link, gen::JobDone::TYPE) + .await + .decode() + .unwrap(); + assert_eq!( + done.status, + gen::ERR_PROTOCOL, + "case {i}: {:?}", + done.message + ); + } + }) + .await + .expect("the test hung"); +} + +/// A merge download writes a file `x` through `x.ava-part` beside it, so a source tree holding both +/// `x` and `x.ava-part` would have the two share a file (the corruption of `x`). The Rust receiver +/// refuses such a manifest with ERR_PATH, before its journal and stored manifest are written. +#[tokio::test(flavor = "multi_thread")] +async fn a_merge_download_of_a_tree_naming_a_files_part_name_is_refused_and_writes_nothing() { + ava1_ctest::c_set_read_allowed(true); + let d = dir("dl-part-clash"); + let src = d.join("console/tree"); + std::fs::create_dir_all(&src).unwrap(); + std::fs::write(src.join("x"), vec![0x11u8; (2 << 20) + 5]).unwrap(); + std::fs::write(src.join("x.ava-part"), b"mine").unwrap(); + let got = d.join("got"); + std::fs::create_dir_all(&got).unwrap(); // a merge into an existing folder + let (me, mine) = paired_client(&d.join("peers")); + let srv = CServer::start_data( + SECRET, + &d.join("peers"), + &d.join("jobs"), + 200, + 2000, + 2000, + 0, + ); + let s = connect(&srv.addr(), me, mine, "rust", calm()) + .await + .unwrap(); + let job = [0x6e; 16]; + let mut link = s.job(job); + let sink = Arc::new(LocalSink::new(got.clone(), false)); + let r = download( + &mut link, + src.to_str().unwrap(), + 0, + sink, + ro(&d.join("ejobs"), false), + ) + .await; + assert!( + matches!(&r, Err(ava1::send::SendError::Refused { status, .. }) if *status == gen::ERR_PATH), + "{r:?}" + ); + let jdir = ava1::journal::job_dir(&d.join("ejobs"), &job); + assert!(!jdir.join("manifest").exists(), "the manifest was stored"); + assert!(!jdir.join("journal").exists(), "the journal was written"); + assert!( + std::fs::read_dir(&got).unwrap().next().is_none(), + "something was written" + ); +} + /// A read policy is a prefix check on the path it is given, so a source with a `..` component /// (or a relative one) could name a folder the policy never allowed. Downloads and /// console-to-console sends take the upload's rule: an absolute path with no `.`, `..` or empty diff --git a/crates/ava1-ctest/tests/server.rs b/crates/ava1-ctest/tests/server.rs index 379e9af..9c10f8c 100644 --- a/crates/ava1-ctest/tests/server.rs +++ b/crates/ava1-ctest/tests/server.rs @@ -1050,6 +1050,70 @@ async fn the_c_server_refuses_a_client_without_its_pairing_nonce() { assert_eq!(shown, 1); } +/// The handshake as `me`, its ClientInfo carrying `token`: the first sealed frame's type, and the +/// Error's code when it is one. +async fn hello_with_token(addr: &str, me: &Identity, token: Option<[u8; 16]>) -> (u8, u16) { + use ava1::wire::Message; + let stream = TcpStream::connect(addr).await.unwrap(); + let (rh, wh) = stream.into_split(); + let (mut r, mut w) = (FrameReader::new(rh), FrameWriter::new(wh)); + let mut hs = ava1::keys::Handshake::initiator(me).unwrap(); + let hello = gen::HelloInfo { + version_min: gen::PROTOCOL_VERSION, + version_max: gen::PROTOCOL_VERSION, + caps: 0, + }; + let noise = hs.write(&hello.to_bytes().unwrap()).unwrap(); + w.send_msg(0, &gen::Hs1 { noise }).await.unwrap(); + let m2: gen::Hs2 = r.recv().await.unwrap().decode().unwrap(); + hs.read(&m2.noise).unwrap(); + let ci = gen::ClientInfo { + nonce_c: [3; 16], + name: Some("blocked".into()), + token, + }; + let noise = hs.write(&ci.to_bytes().unwrap()).unwrap(); + w.send_msg(0, &gen::Hs3 { noise }).await.unwrap(); + let k = hs.finish(); + r.set_key(ava1::keys::control_key(&k.s2c)); + let f = tokio::time::timeout(Duration::from_secs(3), r.recv()) + .await + .expect("no answer to message 3") + .expect("the connection closed with no answer"); + let code = if f.ty == gen::Error::TYPE { + f.decode::().unwrap().code + } else { + 0 + }; + (f.ty, code) +} + +/// S5: a device the user blocked stays blocked when its ClientInfo carries a `token`. Pre-fix any +/// token skipped the `refused` hook (it was taken for another console's ticket), and a blocked +/// device still in the trust store got a full session. +#[tokio::test(flavor = "multi_thread")] +async fn a_blocked_device_sending_a_token_is_still_refused() { + let d = dir("blocked-token"); + let (me, peers) = paired_client(&d.join("peers")); + let srv = CServer::start_with(SECRET, &d.join("peers"), opts(0)); + // Paired and not blocked: it gets in, with or without a token that is no ticket. + connect(&srv.addr(), me.clone(), peers.clone(), "c", fast()) + .await + .unwrap(); + let (ty, _) = hello_with_token(&srv.addr(), &me, Some([9; 16])).await; + assert_eq!(ty, gen::Welcome::TYPE); + srv.refuse_key(Some(me.public())); + for token in [None, Some([9; 16])] { + let (ty, code) = hello_with_token(&srv.addr(), &me, token).await; + assert_eq!( + (ty, code), + (gen::Error::TYPE, gen::ERR_PAIRING_CLOSED), + "token {token:?}" + ); + } + srv.refuse_key(None); +} + #[tokio::test(flavor = "multi_thread")] async fn the_c_server_notifies_only_once_welcome_is_sent() { let d = dir("notify-after-welcome"); diff --git a/crates/ava1-ctest/tests/wire_upload.rs b/crates/ava1-ctest/tests/wire_upload.rs index 1af3513..f47eada 100644 --- a/crates/ava1-ctest/tests/wire_upload.rs +++ b/crates/ava1-ctest/tests/wire_upload.rs @@ -724,6 +724,347 @@ async fn a_lane_frame_checked_before_a_new_manifest_is_queued_before_it_replaces } } +/// S1: a FileRoot that arrives while a new manifest is being adopted waits for it. Pre-fix the +/// feeder applied it at once, into the large-file state remap had just freed (a use-after-free +/// ASan reports; without it the root was lost and the file never committed). +#[tokio::test(flavor = "multi_thread")] +async fn a_file_root_during_a_new_manifest_waits_for_it_and_lands_on_the_new_file() { + let d = dir("wire-remanifest-root"); + let peers = d.join("peers"); + let ids = paired_client(&peers); + let srv = CServer::start_data(SECRET, &peers, &d.join("jobs"), 200, 2000, 2000, 0); + let s = session(&srv, &ids).await; + let job = [0x5du8; 16]; + let old = big_data(2 << 20); + let a = Manifest { + entries: vec![file("a", old.len() as u64)], + }; + let root = d.join("dest"); + let mut link = s.job(job); + let ack = open(&mut link, job, &root).await; + assert_eq!(ack.status, 0); + send_manifest(&link, job, &a).await; + let map: JobMap = next_of(&mut link, JobMap::TYPE).await.decode().unwrap(); + assert_eq!(map.status, 0); + let lane = link.opener().unwrap().open().await.unwrap(); + let tx = link.lane(lane).unwrap().tx; + // Half of "a": the job holds a large-file state for it. + tx.send_raw(Chunk::TYPE, 0, 1, chunk(job, 0, 0, &old[..1 << 20])) + .await + .unwrap(); + let t = Instant::now(); + loop { + if srv.job_counts(job).0 >= 1 << 20 { + break; + } + assert!( + t.elapsed() < Duration::from_secs(10), + "the chunk never arrived" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } + tokio::time::sleep(Duration::from_millis(200)).await; + // A manifest without "a": remap frees its state, then takes its time. + let new = big_data((2 << 20) + 3); + let b = Manifest { + entries: vec![file("b", new.len() as u64)], + }; + srv.knob("remap_delay_ms", 1000); + send_manifest(&link, job, &b).await; + tokio::time::sleep(Duration::from_millis(400)).await; + link.control + .send(&FileRoot { + job_id: job, + file_id: 0, + root: *blake3::hash(&new).as_bytes(), + }) + .await + .unwrap(); + let map: JobMap = next_of(&mut link, JobMap::TYPE).await.decode().unwrap(); + srv.knob("remap_delay_ms", 0); + assert_eq!(map.status, 0, "{:?}", map.message); + // The root was kept for "b" (file 0 of the new manifest): its bytes alone finish the job. + tx.send_raw(Chunk::TYPE, 0, 2, chunk(job, 0, 0, &new[..1 << 20])) + .await + .unwrap(); + tx.send_raw(Chunk::TYPE, 0, 3, chunk(job, 0, 1 << 20, &new[1 << 20..])) + .await + .unwrap(); + let (_, done) = until_done(&mut link).await; + assert_eq!(done.status, 0, "{:?}", done.message); + assert_eq!(std::fs::read(root.join("b")).unwrap(), new); +} + +fn download_msg(job: [u8; 16], src: &Path) -> JobOpen { + JobOpen { + job_id: job, + kind: gen::JOB_DOWNLOAD, + root: src.to_str().unwrap().into(), + ..Default::default() + } +} + +/// S2: a download JobOpen starts over only a download of its id, and only the device's own or +/// one no session drives. Pre-fix it freed whatever job had the id: another device's upload or +/// running download. +#[tokio::test(flavor = "multi_thread")] +async fn a_download_open_never_ends_another_job_under_its_id() { + ava1_ctest::c_set_read_allowed(true); + let d = dir("wire-dl-id"); + let peers = d.join("peers"); + let a_ids = paired_client(&peers); + let b_ids = paired_client(&peers); + let src = d.join("console/src"); + std::fs::create_dir_all(&src).unwrap(); + std::fs::write(src.join("f"), b"data").unwrap(); + let srv = CServer::start_data(SECRET, &peers, &d.join("jobs"), 200, 2000, 2000, 0); + let a = session(&srv, &a_ids).await; + let b = session(&srv, &b_ids).await; + + // A's upload, mapped and waiting for its bytes. + let up = [0x5bu8; 16]; + let root = d.join("dest"); + let mut la = a.job(up); + assert_eq!(open(&mut la, up, &root).await.status, 0); + let m = Manifest { + entries: vec![file("x", 2)], + }; + send_manifest(&la, up, &m).await; + let map: JobMap = next_of(&mut la, JobMap::TYPE).await.decode().unwrap(); + assert_eq!(map.status, 0); + // B opens a download under the same id: refused, and A's upload is untouched. + let mut lb = b.job(up); + lb.control.send(&download_msg(up, &src)).await.unwrap(); + let ack: JobOpenAck = next_of(&mut lb, JobOpenAck::TYPE).await.decode().unwrap(); + assert_eq!(ack.status, gen::ERR_PROTOCOL, "{:?}", ack.message); + let lane = la.opener().unwrap().open().await.unwrap(); + la.lane(lane) + .unwrap() + .tx + .send_raw(Bundle::TYPE, 0, 1, bundle(up, 0, b"ok")) + .await + .unwrap(); + let (_, done) = until_done(&mut la).await; + assert_eq!(done.status, 0, "{:?}", done.message); + assert_eq!(std::fs::read(root.join("x")).unwrap(), b"ok"); + + // A's download, running on A's session: B cannot take it over... + let dl = [0x5au8; 16]; + let mut la = a.job(dl); + la.control.send(&download_msg(dl, &src)).await.unwrap(); + let ack: JobOpenAck = next_of(&mut la, JobOpenAck::TYPE).await.decode().unwrap(); + assert_eq!(ack.status, 0, "{:?}", ack.message); + let mut lb = b.job(dl); + lb.control.send(&download_msg(dl, &src)).await.unwrap(); + let ack: JobOpenAck = next_of(&mut lb, JobOpenAck::TYPE).await.decode().unwrap(); + assert_eq!(ack.status, gen::ERR_UNKNOWN_JOB, "{:?}", ack.message); + drop(lb); + // ... A itself starts it over from another session (a reconnect)... + let a2 = session(&srv, &a_ids).await; + let mut la2 = a2.job(dl); + la2.control.send(&download_msg(dl, &src)).await.unwrap(); + let ack: JobOpenAck = next_of(&mut la2, JobOpenAck::TYPE).await.decode().unwrap(); + assert_eq!(ack.status, 0, "{:?}", ack.message); + // ... and once no session drives it, B may take it over. + drop(la2); + drop(a2); + let t = Instant::now(); + loop { + let mut lb = b.job(dl); + lb.control.send(&download_msg(dl, &src)).await.unwrap(); + let ack: JobOpenAck = next_of(&mut lb, JobOpenAck::TYPE).await.decode().unwrap(); + if ack.status == 0 { + break; + } + assert!( + ack.status == gen::ERR_UNKNOWN_JOB || ack.status == gen::ERR_BUSY, + "{} {:?}", + ack.status, + ack.message + ); + assert!(t.elapsed() < Duration::from_secs(20), "never parked"); + drop(lb); + tokio::time::sleep(Duration::from_millis(100)).await; + } +} + +/// Every byte of file 0 (`big`) on `tx`, then its FileRoot. +async fn send_big(link: &JobLink, tx: &ava1::router::ConnTx, job: [u8; 16], seq0: u32, big: &[u8]) { + let mut seq = seq0; + let mut off = 0; + while off < big.len() { + let end = (off + (1 << 20)).min(big.len()); + tx.send_raw(Chunk::TYPE, 0, seq, chunk(job, 0, off, &big[off..end])) + .await + .unwrap(); + seq += 1; + off = end; + } + link.control + .send(&FileRoot { + job_id: job, + file_id: 0, + root: *blake3::hash(big).as_bytes(), + }) + .await + .unwrap(); +} + +/// S3: a commit that fails on a transient I/O error (here its rename into place) ends the job +/// with ERR_IO, and a JobOpen of the same job takes it up again: the commit runs again and the +/// job finishes. Pre-fix the journaled Done(ERR_IO) answered every resume with "all done" and the +/// same failure, so the upload could never finish. +#[tokio::test(flavor = "multi_thread")] +async fn a_commit_that_failed_on_io_is_taken_up_again_by_a_reopen() { + let d = dir("wire-commit-io"); + let peers = d.join("peers"); + let ids = paired_client(&peers); + let srv = CServer::start_data(SECRET, &peers, &d.join("jobs"), 200, 2000, 2000, 0); + let job = [0x59u8; 16]; + let big = big_data((2 << 20) + 3); + let m = Manifest { + entries: vec![file("big", big.len() as u64)], + }; + let root = d.join("dest"); + std::fs::create_dir_all(&root).unwrap(); // a merge: each large file is renamed into place + srv.knob("rename_fail", 1); // file 0's next rename into place answers EBUSY + { + let s = session(&srv, &ids).await; + let mut link = s.job(job); + assert_eq!(open(&mut link, job, &root).await.status, 0); + send_manifest(&link, job, &m).await; + let map: JobMap = next_of(&mut link, JobMap::TYPE).await.decode().unwrap(); + assert_eq!(map.status, 0); + let lane = link.opener().unwrap().open().await.unwrap(); + let tx = link.lane(lane).unwrap().tx; + send_big(&link, &tx, job, 1, &big).await; + let (_, done) = until_done(&mut link).await; + assert_eq!(done.status, gen::ERR_IO, "{:?}", done.message); + } + // The device tries again: the same job, a new session. + let s = session(&srv, &ids).await; + let mut link = s.job(job); + assert_eq!(open(&mut link, job, &root).await.status, 0); + send_manifest(&link, job, &m).await; + let map: JobMap = next_of(&mut link, JobMap::TYPE).await.decode().unwrap(); + assert_eq!(map.status, 0, "{:?}", map.message); + let lane = link.opener().unwrap().open().await.unwrap(); + let tx = link.lane(lane).unwrap().tx; + if map.done.is_empty() { + send_big(&link, &tx, job, 10, &big).await; // whatever the map still asks for, and the root again + } + let (_, done) = until_done(&mut link).await; + assert_eq!(done.status, 0, "{:?}", done.message); + assert_eq!(std::fs::read(root.join("big")).unwrap(), big); +} + +/// S4: a FileRoot is 52 bytes, but its control frame may carry 64 KiB of extension. Waiting for the +/// map in the job's inbox it is kept at its own size: pre-fix 600 of 60 KiB filled the inbox (32 +/// MiB) and the job ended; now they cost 52 bytes each and the job finishes. +#[tokio::test(flavor = "multi_thread")] +async fn file_roots_with_huge_extensions_waiting_for_the_map_are_kept_small() { + let d = dir("wire-huge-root"); + let peers = d.join("peers"); + let ids = paired_client(&peers); + let srv = CServer::start_data(SECRET, &peers, &d.join("jobs"), 200, 2000, 2000, 0); + let s = session(&srv, &ids).await; + let job = [0x58u8; 16]; + let big = big_data((2 << 20) + 3); + let m = Manifest { + entries: vec![file("big", big.len() as u64)], + }; + let root = d.join("dest"); + let mut link = s.job(job); + assert_eq!(open(&mut link, job, &root).await.status, 0); + srv.set_map_delay_ms(3000); // the FileRoots below wait in the inbox for the map + send_manifest(&link, job, &m).await; + let mut body = FileRoot { + job_id: job, + file_id: 0, + root: *blake3::hash(&big).as_bytes(), + } + .to_bytes() + .unwrap(); + // The encoder's empty extension block, replaced by one unknown extension of 60 KiB. + body.truncate(body.len() - 2); + body.extend_from_slice(&1u16.to_le_bytes()); + body.extend_from_slice(&0x7777u16.to_le_bytes()); + body.extend_from_slice(&(60u32 << 10).to_le_bytes()); + body.resize(body.len() + (60 << 10), 0xee); + for _ in 0..600 { + link.control + .send_raw(FileRoot::TYPE, 0, 0, body.clone()) + .await + .unwrap(); + } + let map: JobMap = next_of(&mut link, JobMap::TYPE).await.decode().unwrap(); + srv.set_map_delay_ms(0); + assert_eq!(map.status, 0, "{:?}", map.message); + let lane = link.opener().unwrap().open().await.unwrap(); + let tx = link.lane(lane).unwrap().tx; + let mut off = 0; + let mut seq = 1; + while off < big.len() { + let end = (off + (1 << 20)).min(big.len()); + tx.send_raw(Chunk::TYPE, 0, seq, chunk(job, 0, off, &big[off..end])) + .await + .unwrap(); + seq += 1; + off = end; + } + let (_, done) = until_done(&mut link).await; + assert_eq!(done.status, 0, "{:?}", done.message); + assert_eq!(std::fs::read(root.join("big")).unwrap(), big); +} + +/// A merge writes a file `x` through `x.ava-part` beside it: a manifest that also names `x.ava-part` +/// (in any case) is refused with ERR_PATH before it is stored or journaled. Pre-fix it was taken, +/// and `x`'s part file and the entry `x.ava-part` were one file. A staged upload has no such +/// names and takes it. +#[tokio::test(flavor = "multi_thread")] +async fn a_merge_manifest_naming_a_files_part_name_is_refused_before_it_is_stored() { + let d = dir("wire-part-clash"); + let peers = d.join("peers"); + let ids = paired_client(&peers); + let srv = CServer::start_data(SECRET, &peers, &d.join("jobs"), 200, 2000, 2000, 0); + let s = session(&srv, &ids).await; + let root = d.join("dest"); + std::fs::create_dir_all(&root).unwrap(); // a merge + for (k, part) in ["x.ava-part", "X.AVA-Part"].into_iter().enumerate() { + let job = [0x50 + k as u8; 16]; + let m = Manifest { + entries: vec![file("x", 2 << 20), file(part, 2)], + }; + let mut link = s.job(job); + assert_eq!(open(&mut link, job, &root).await.status, 0); + send_manifest(&link, job, &m).await; + let map: JobMap = next_of(&mut link, JobMap::TYPE).await.decode().unwrap(); + assert_eq!(map.status, gen::ERR_PATH, "{part}: {:?}", map.message); + let jdir = d.join("jobs").join(ava1::hex::encode(&job)); + assert!( + !jdir.join("manifest").exists(), + "{part}: the manifest was stored" + ); + assert!( + !root.join("x.ava-part").exists(), + "{part}: a part file was made" + ); + } + // Staged (a new destination): the part file is the file's own path in the staging tree. + let job = [0x4f; 16]; + let m = Manifest { + entries: vec![file("x", 2 << 20), file("x.ava-part", 2)], + }; + let mut link = s.job(job); + assert_eq!(open(&mut link, job, &d.join("fresh")).await.status, 0); + send_manifest(&link, job, &m).await; + let map: JobMap = next_of(&mut link, JobMap::TYPE).await.decode().unwrap(); + assert_eq!(map.status, 0, "{:?}", map.message); + // (and the job directory checked above is where a manifest is stored) + let jdir = d.join("jobs").join(ava1::hex::encode(&job)); + assert!(jdir.join("manifest").exists()); +} + /// A manifest need not list a file's parent folders (SPEC.md §15.1). In a merge, a folder of the /// destination that is a symbolic link must not lead the job's files out of it (§15.5): the map /// refuses the job with ERR_PATH, and nothing lands where the link points. diff --git a/crates/ava1/src/manifest.rs b/crates/ava1/src/manifest.rs index 66430a6..7c200e2 100644 --- a/crates/ava1/src/manifest.rs +++ b/crates/ava1/src/manifest.rs @@ -43,6 +43,38 @@ pub enum PathError { TooMany, } +/// What a merge receiver appends to a file's path for its part file (SPEC.md §11.6). +pub const PART_SUFFIX: &str = ".ava-part"; + +/// In a merge (SPEC.md §11.6) a file `P` is written as `P.ava-part` beside it, so a manifest that +/// also names `P.ava-part` (in any letter case: a drive may fold it) would have the two share a +/// name: one's bytes would land in the other. Returns the first such pair as (the file, the entry +/// at its part name), or `None`. Costs one pass, and a set only as large as the entries whose name +/// ends in the suffix. +pub fn part_name_clash(m: &Manifest) -> Option<(u32, u32)> { + let n = PART_SUFFIX.len(); + let parts: std::collections::HashMap = m + .entries + .iter() + .enumerate() + .filter(|(_, e)| { + e.path.len() > n + && e.path.is_char_boundary(e.path.len() - n) + && e.path[e.path.len() - n..].eq_ignore_ascii_case(PART_SUFFIX) + }) + .map(|(i, e)| (e.path[..e.path.len() - n].to_ascii_lowercase(), i as u32)) + .collect(); + if parts.is_empty() { + return None; + } + m.entries.iter().enumerate().find_map(|(i, e)| { + (e.kind == ENTRY_FILE) + .then(|| parts.get(&e.path.to_ascii_lowercase())) + .flatten() + .map(|&q| (i as u32, q)) + }) +} + /// Checks `p` against the manifest path rules of SPEC.md §11.2; a receiver runs it on /// every path before touching the filesystem. pub fn check_path(p: &str) -> Result<(), PathError> { @@ -286,6 +318,42 @@ pub fn single(src: &dyn Source, rel: &str) -> io::Result { #[cfg(test)] mod tests { use super::*; + + #[test] + fn a_files_part_name_in_the_same_manifest_is_found_in_any_case() { + let e = |kind, path: &str| Entry { + kind, + mode: 0o644, + size: 1, + mtime: 1, + path: path.into(), + root: None, + }; + let m = |es: Vec| Manifest { entries: es }; + assert_eq!( + part_name_clash(&m(vec![e(ENTRY_FILE, "a"), e(ENTRY_FILE, "b")])), + None + ); + assert_eq!( + part_name_clash(&m(vec![ + e(ENTRY_FILE, "d/x.ava-part"), + e(ENTRY_FILE, "d/x") + ])), + Some((1, 0)) + ); + assert_eq!( + part_name_clash(&m(vec![e(ENTRY_FILE, "x"), e(ENTRY_DIR, "X.AVA-PART")])), + Some((0, 1)) + ); + // A folder has no part file; a bare ".ava-part" names no file's part. + assert_eq!( + part_name_clash(&m(vec![e(ENTRY_DIR, "x"), e(ENTRY_FILE, "x.ava-part")])), + None + ); + assert_eq!(part_name_clash(&m(vec![e(ENTRY_FILE, ".ava-part")])), None); + // Not UTF-8 safe to slice blindly: a multi-byte name ending just short of the suffix. + assert_eq!(part_name_clash(&m(vec![e(ENTRY_FILE, "éava-part")])), None); + } use crate::source::LocalSource; fn e(path: &str, size: u64) -> Entry { diff --git a/crates/ava1/src/ranges.rs b/crates/ava1/src/ranges.rs index a0f03bb..ffb311e 100644 --- a/crates/ava1/src/ranges.rs +++ b/crates/ava1/src/ranges.rs @@ -38,6 +38,16 @@ impl RangeSet { self.v.iter().copied() } + /// How many disjoint ranges the set holds. + pub fn len(&self) -> usize { + self.v.len() + } + + /// Whether the set holds no range. + pub fn is_empty(&self) -> bool { + self.v.is_empty() + } + /// The number of bytes the set covers. pub fn covered(&self) -> u64 { self.v.iter().map(|r| r.1 - r.0).sum() @@ -104,6 +114,14 @@ pub fn from_runs(runs: &[FileRun]) -> BTreeSet { .collect() } +/// What the pages of one map named so far ([`Need::add_page_bounded`]). +#[derive(Debug, Clone, Default)] +pub struct MapSeen { + ids: u64, + ranges: u64, + range_cap: u64, +} + /// A receiver's answer to "what do you have": done files and durable ranges of the rest. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Need { @@ -163,7 +181,75 @@ impl Need { } } + /// [`Need::add_page`] for a map of the job whose manifest is `manifest`, as a sender reads + /// it: a receiver's pages can then hold no more than the manifest does. A receiver names each + /// done file once (disjoint runs, ids of the manifest) and, per unfinished file, disjoint + /// durable ranges inside it that start on group boundaries, so at most one per group; a page + /// past that is refused (`Err`), never stored. `seen` carries the count across the pages of + /// one map. + pub fn add_page_bounded( + &mut self, + m: &gen::JobMap, + manifest: &crate::manifest::Manifest, + seen: &mut MapSeen, + ) -> Result<(), String> { + let n = manifest.entries.len() as u64; + if seen.range_cap == 0 { + seen.range_cap = manifest + .entries + .iter() + .filter(|e| e.kind == gen::ENTRY_FILE) + .map(|e| crate::verify::groups(e.size)) + .fold(0u64, u64::saturating_add) + .saturating_add(1); + } + if let Some(h) = m.held { + self.held = self.held.max(h); + } + for r in &m.done { + let end = r.first as u64 + r.count as u64; + seen.ids += r.count as u64; + if end > n || seen.ids > n { + return Err(format!( + "the map names files {}..{end} past the manifest's {n} entries", + r.first + )); + } + self.done.extend(r.first..end as u32); + } + for r in &m.partial { + let Some(e) = manifest + .entry(r.file_id) + .filter(|e| e.kind == gen::ENTRY_FILE) + else { + return Err(format!( + "the map has durable bytes for {}, which is not a file of the manifest", + r.file_id + )); + }; + let end = r.offset.saturating_add(r.len); + seen.ranges += 1; + if end > e.size || seen.ranges > seen.range_cap { + return Err(format!( + "the map has durable bytes {}..{end} of file {} ({} bytes)", + r.offset, r.file_id, e.size + )); + } + let set = self.partial.entry(r.file_id).or_default(); + set.insert(r.offset, end); + if set.len() as u64 > crate::verify::groups(e.size) { + return Err(format!( + "the map has more durable ranges of file {} than it has groups", + r.file_id + )); + } + } + Ok(()) + } + /// Merges one JobMap page into this answer. `held` keeps the largest value any page reported. + /// Nothing bounds what it stores but the page: a sender reading a peer's map uses + /// [`Need::add_page_bounded`]. pub fn add_page(&mut self, m: &gen::JobMap) { if let Some(h) = m.held { self.held = self.held.max(h); @@ -233,6 +319,92 @@ mod tests { assert_eq!(absent.held, 0); } + fn job(sizes: &[u64]) -> crate::manifest::Manifest { + crate::manifest::Manifest { + entries: sizes + .iter() + .enumerate() + .map(|(i, &size)| crate::manifest::Entry { + kind: gen::ENTRY_FILE, + mode: 0o644, + size, + mtime: 1, + path: format!("f{i}"), + root: None, + }) + .collect(), + } + } + + fn page(done: Vec, partial: Vec, last: u8) -> gen::JobMap { + gen::JobMap { + job_id: [0; 16], + status: 0, + last, + done, + partial, + message: None, + held: None, + } + } + + #[test] + fn a_bounded_map_takes_what_a_receiver_builds() { + // S4: every page a receiver writes for this manifest goes in unchanged. + let m = job(&[5 << 20, 3 << 20, 10, 7 << 20]); + let mut want = Need::default(); + want.done.insert(2); + want.partial.entry(0).or_default().insert(0, 1 << 20); + want.partial.entry(0).or_default().insert(2 << 20, 4 << 20); + want.partial.entry(3).or_default().insert(6 << 20, 7 << 20); + let mut got = Need::default(); + let mut seen = MapSeen::default(); + for p in want.to_pages([0; 16], 0) { + got.add_page_bounded(&p, &m, &mut seen).unwrap(); + } + assert_eq!(got, want); + } + + #[test] + fn a_bounded_map_refuses_what_no_receiver_builds() { + // S4: what would grow memory past the manifest is refused, never stored. + let m = job(&[3 << 20, 1 << 20]); + let run = |first, count| FileRun { first, count }; + let range = |file_id, offset, len| FileRange { + file_id, + offset, + len, + }; + let bad: Vec> = vec![ + // a run past the manifest (4 G ids) + vec![page(vec![run(0, u32::MAX)], vec![], 1)], + // the same files again, page after page + vec![ + page(vec![run(0, 2)], vec![], 0), + page(vec![run(0, 2)], vec![], 1), + ], + // durable bytes past a file's end, or of no file + vec![page(vec![], vec![range(1, 0, 2 << 20)], 1)], + vec![page(vec![], vec![range(7, 0, 1)], 1)], + vec![page(vec![], vec![range(0, u64::MAX, u64::MAX)], 1)], + // more disjoint ranges of a file than it has groups + vec![page( + vec![], + (0..4).map(|k| range(0, k * 10, 1)).collect(), + 1, + )], + ]; + for (i, pages) in bad.iter().enumerate() { + let mut need = Need::default(); + let mut seen = MapSeen::default(); + let r = pages + .iter() + .try_for_each(|p| need.add_page_bounded(p, &m, &mut seen)); + assert!(r.is_err(), "case {i} was taken"); + assert!(need.done.len() <= 2 && need.partial.len() <= 2, "case {i}"); + } + } + #[test] fn inserts_merge_and_report_coverage() { let mut r = RangeSet::new(); diff --git a/crates/ava1/src/recv.rs b/crates/ava1/src/recv.rs index b401ee9..30be1b2 100644 --- a/crates/ava1/src/recv.rs +++ b/crates/ava1/src/recv.rs @@ -31,6 +31,12 @@ use crate::wire::FrameMessage; pub trait Sink: Send + Sync { /// Called once with the manifest, before any data (create directories, decide staging). fn prepare(&self, m: &Manifest) -> io::Result<()>; + /// The checks of `m` that need nothing from the disk, run before anything of the job is + /// written (its journal and stored manifest included): a manifest this sink refuses leaves + /// no trace. `prepare` runs them again. The default refuses nothing. + fn check(&self, _m: &Manifest) -> io::Result<()> { + Ok(()) + } /// Bytes of a large file at `off` (group-aligned, whole groups unless it ends the file). fn write_at(&self, id: u32, off: u64, data: &[u8]) -> io::Result<()>; /// A whole small file (its root was checked when it arrived). @@ -624,18 +630,36 @@ fn sync_dirs(_dirs: &BTreeSet) -> io::Result<()> { } impl Sink for LocalSink { + fn check(&self, m: &Manifest) -> io::Result<()> { + if self.single { + return Ok(()); + } + for e in &m.entries { + if !plain_relative(&e.path) { + return Err(path_refused(format!( + "{:.100} is not a plain relative path here", + e.path + ))); + } + } + // A merge writes each file through `.ava-part` beside it (`path`): an entry of that + // name would share it with the file's part, and either one's bytes would land in the other. + if self.merging() { + if let Some((f, q)) = manifest::part_name_clash(m) { + return Err(path_refused(format!( + "{:.100} is the name {:.100} is written under until it is complete", + m.entries[q as usize].path, m.entries[f as usize].path + ))); + } + } + Ok(()) + } + fn prepare(&self, m: &Manifest) -> io::Result<()> { + self.check(m)?; let mut st = self.st.lock().unwrap(); st.m = Some(Arc::new(m.clone())); if !self.single { - for e in &m.entries { - if !plain_relative(&e.path) { - return Err(path_refused(format!( - "{:.100} is not a plain relative path here", - e.path - ))); - } - } let base = self.base(); // A merge into an existing folder (SPEC.md §15.5): a manifest folder, or a file's // parent folder, that already exists as a symlink or as something other than a @@ -1727,6 +1751,9 @@ async fn run_loop( staged: u8::from(staged), root: dest_root.clone(), }; + // What the sink refuses of the manifest is refused before its journal and its stored copy + // are written: a refused job leaves nothing on disk. + sink.check(&m)?; let mut st = State::default(); // A fresh job (no journal to replay, no relay hint) needs nothing from the sender's // map, so the (empty) map goes out BEFORE the journal and the sink's directories are diff --git a/crates/ava1/src/send.rs b/crates/ava1/src/send.rs index e5837dc..1a123aa 100644 --- a/crates/ava1/src/send.rs +++ b/crates/ava1/src/send.rs @@ -21,7 +21,7 @@ use crate::gen::{ }; use crate::governor::{self, Class, Governor, GovernorOptions, JobSummary, Mode, Sample}; use crate::manifest::Manifest; -use crate::ranges::{from_runs, Need, RangeSet}; +use crate::ranges::{MapSeen, Need, RangeSet}; use crate::router::{BoxFut, ConnTx, Inbound, JobLink, LaneOpener, LaneTx}; use crate::source::{read_full_at, Source}; use crate::verify::{self, FileHasher, Outboard, GROUP}; @@ -805,6 +805,7 @@ pub async fn open_upload( }) .await?; let mut need = Need::default(); + let mut seen = MapSeen::default(); let mut credit = ack.credit; // The map may take a while (the receiver replays its journal first), but it is not allowed // to never come: the cancel is honoured and a receiver gone quiet ends the open. @@ -857,7 +858,8 @@ pub async fn open_upload( message: map.message.unwrap_or_default(), }); } - need.add_page(&map); + need.add_page_bounded(&map, m, &mut seen) + .map_err(SendError::Protocol)?; if map.last == 1 { return Ok((credit, need)); } @@ -2063,8 +2065,20 @@ pub async fn run_upload( }, Durable::TYPE => match f.decode::() { Ok(d) => { + // The ids are the receiver's: only the manifest's count, and one + // Durable names each at most once (disjoint runs), so a frame can + // neither grow the set past the manifest nor make the loop long. + let n = manifest.entries.len() as u64; + let named: u64 = d.files.iter().map(|r| r.count as u64).sum(); + if named > n + || d.files.iter().any(|r| r.first as u64 + r.count as u64 > n) + { + break Err(SendError::Protocol(format!( + "a Durable names files past the manifest's {n} entries" + ))); + } let mut s = sh.sched.lock().unwrap(); - for id in from_runs(&d.files) { + for id in d.files.iter().flat_map(|r| r.first..r.first + r.count) { if durable_files.insert(id) { let size = manifest.entry(id).map_or(0, |e| e.size); pg.files_durable.fetch_add(1, Ordering::Relaxed); @@ -2512,6 +2526,7 @@ async fn open_as_responder( .await .map_err(|e| SendError::Disconnected(e.to_string()))?; let mut need = Need::default(); + let mut seen = MapSeen::default(); loop { let f = next_ctl(link).await?; if f.ty != JobMap::TYPE { @@ -2524,7 +2539,8 @@ async fn open_as_responder( message: map.message.unwrap_or_default(), }); } - need.add_page(&map); + need.add_page_bounded(&map, m, &mut seen) + .map_err(SendError::Protocol)?; if map.last == 1 { return Ok((open.credit.unwrap_or(16 << 20), need)); } @@ -3970,6 +3986,10 @@ mod tests { no_map: bool, /// Every lane frame's sequence number (its `channel`), in arrival order. seqs: Option>>>, + /// The done runs the map reports (S4: a hostile one names files past the manifest). + map_done: Vec, + /// A `Durable` sent right after the map. + durable_after_map: Option, } impl Default for FakeReceiver { @@ -3988,6 +4008,8 @@ mod tests { cancel_seen: Arc::new(AtomicU32::new(0)), no_map: false, seqs: None, + map_done: vec![], + durable_after_map: None, } } } @@ -4119,11 +4141,14 @@ mod tests { job_id: job, status: 0, last: 1, - done: vec![], + done: rcv.map_done.clone(), partial: vec![], message: None, held: None, }).await.unwrap(); + if let Some(d) = &rcv.durable_after_map { + let _ = peer_w.send_msg(0, d).await; + } if let Some(p) = rcv.pause_control { control_hold.as_mut().reset(tokio::time::Instant::now() + p); flood.as_mut().reset(tokio::time::Instant::now() + Duration::from_millis(1)); @@ -5600,4 +5625,76 @@ mod tests { ); let _ = std::fs::remove_dir_all(&dir); } + /// S4: a hostile receiver's map or Durable names files the manifest does not have. Pre-fix + /// they were stored as they came (a run of 4 G ids, unbounded across pages); now the job + /// ends as a protocol error before anything is stored. + #[tokio::test] + async fn a_map_or_durable_naming_files_past_the_manifest_ends_the_job() { + for (tag, map_done, durable) in [ + ( + "map", + vec![gen::FileRun { + first: 0, + count: u32::MAX, + }], + None, + ), + ( + "durable", + vec![], + Some(Durable { + job_id: [0x7d; 16], + files: vec![gen::FileRun { + first: 1, + count: u32::MAX - 1, + }], + ranges: vec![], + }), + ), + ] { + let size = 3 << 20; + let (mut link, _lane_seen, _keep) = fake_link( + FakeReceiver { + credit: 64 << 20, + credit_on_apply: true, + done_when_complete: true, + map_done, + durable_after_map: durable, + ..Default::default() + }, + None, + ); + let dir = std::env::temp_dir() + .join(format!("ava1-send-bogusmap-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("big"), vec![0x48u8; size]).unwrap(); + let m = Arc::new(Manifest { + entries: vec![Entry { + kind: gen::ENTRY_FILE, + mode: 0o644, + size: size as u64, + mtime: 1, + path: "big".into(), + root: None, + }], + }); + let r = tokio::time::timeout( + Duration::from_secs(20), + send_job( + &mut link, + m, + Arc::new(crate::source::LocalSource::new(dir.clone())), + SendOptions::upload("dest"), + ), + ) + .await + .expect("the job ended within the bound"); + assert!( + matches!(&r, Err(SendError::Protocol(msg)) if msg.contains("past the manifest")), + "{tag}: {r:?}" + ); + let _ = std::fs::remove_dir_all(&dir); + } + } } diff --git a/spec/SPEC.md b/spec/SPEC.md index aaa339c..a248482 100644 --- a/spec/SPEC.md +++ b/spec/SPEC.md @@ -645,6 +645,10 @@ size and mtime are unchanged, and restarts the others (never splicing old and ne manifest: the receiver answers `JobMap`, or `JobMap{status = ERR_UNKNOWN_JOB}` and the sender falls back to `JobOpen`. A map larger than one control frame is sent as several `JobMap` pages; `last = 1` marks the final one. `Durable` is never paged: each is complete. +A map names only what the manifest has: each done file once, by its id (`FileRun`s that do not +overlap), and for a file not done, durable ranges inside it that start on group boundaries (so no +more ranges than the file has groups); a `Durable` names each of its files once. A sender ends the +job with `ERR_PROTOCOL` on a map or `Durable` that names more, before it stores any of it. Clients reopen with `JobOpen` after any interruption; `Resume` is optional for senders that keep their manifest and credit state. A receiver answers `Resume` with the `JobMap` of a parked job of the same peer key whose stored manifest has that hash, else `JobMap{status = ERR_UNKNOWN_JOB}` — @@ -665,7 +669,10 @@ grant; the sender's window is exactly that number either way. Tests: `crates/ava 11.6 Staging: when the job root does not exist, the receiver writes the whole tree under `.ava-part/` and, after the last file, renames it to `` (same parent, `st_dev` checked; a device that cannot be read is refused with `ERR_IO`, never taken as the same). When the root exists, files are written in place; large files through -`.ava-part` and a same-directory rename. `JF_SINGLE_FILE` writes `.ava-part`. A staging +`.ava-part` and a same-directory rename. `JF_SINGLE_FILE` writes `.ava-part`. So a +merge refuses, with `ERR_PATH`, a manifest that names both a file `P` and `P.ava-part` (in any letter +case: a drive may fold it), since the two would share one name; it refuses it before the manifest is +stored or journaled. A staged job, which writes each file under its own name, takes it. A staging receiver takes `` with `mkdir` before it journals the job (an existing `` then refuses it, `ERR_EXISTS`) and records that in `JnlOpen.staged` bit 1, so on resume the empty `` is its own; the final rename replaces only that empty folder (not empty: `ERR_EXISTS`). @@ -757,7 +764,9 @@ would fail a healthy job. 12.4 Credit: `JobOpenAck.credit` (uploads) or `JobOpen.ext credit` (downloads) is the number of lane-frame body bytes the sender may have outstanding — the window counts the whole body, so a `Chunk` costs its data plus 34 bytes of framing; `Credit{bytes}` returns space as the -receiver frees buffers. A version 1 receiver grants 64 MiB, and never less than 8 MiB: a node whose +receiver frees buffers. A version 1 receiver grants 64 MiB, and never less than 8 MiB; a sender may +use less window than it is granted (the C sender uses at most 64 MiB: what it has in flight stays in +memory until its `Received`), never more. A node whose global buffer budget cannot cover 8 MiB refuses the job with `ERR_BUSY`. A receiver that sees a lane frame exceed the credit still outstanding sends a sealed `Error{ERR_CREDIT}` on the offending lane and closes that lane only: the session, the job and its other lanes go on. Nothing of the frame is