@effect-vfs/nfs 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,13 +5,15 @@ import * as Duration from "effect/Duration";
5
5
  import * as Effect from "effect/Effect";
6
6
  import * as Option from "effect/Option";
7
7
  import * as Predicate from "effect/Predicate";
8
+ import * as Result from "effect/Result";
8
9
  import * as Schedule from "effect/Schedule";
9
10
  import * as Schema from "effect/Schema";
11
+ import * as Scope from "effect/Scope";
10
12
  import * as Semaphore from "effect/Semaphore";
11
- import { ExportCapacityError, InvalidNameError, validateName } from "./export.js";
13
+ import { InvalidFilehandleError, InvalidNameError, validateName } from "./export.js";
12
14
  import { lockRange, MAX_OFFSET, overlaps } from "./lockRanges.js";
13
15
  import { RpcPolicyDenied } from "./rpc.js";
14
- import { Reader, Writer, XdrDecodeError } from "./xdr.js";
16
+ import { make as xdr, XdrCodec, XdrDecodeError, XdrEncodeError } from "./xdr.js";
15
17
  /** @internal */
16
18
  export const Status = {
17
19
  OK: 0,
@@ -208,6 +210,10 @@ const MIN_FORE_REQUEST_BYTES = 40 + 48;
208
210
  const MIN_FORE_RESPONSE_BYTES = 24 + 12 + 8 + 36;
209
211
  /** PERSIST, CONN_BACK_CHAN, and CONN_RDMA are the only defined csa_flags bits. */
210
212
  const CREATE_SESSION4_KNOWN_FLAGS = 0x7;
213
+ // The mode bits knfsd's nfsd_sanitize_attrs strips from a SETATTR that also changes the owner.
214
+ const SET_UID = 0o4000;
215
+ const SET_GID = 0o2000;
216
+ const GROUP_EXECUTE = 0o010;
211
217
  const ACCESS4_READ = 0x01;
212
218
  const ACCESS4_LOOKUP = 0x02;
213
219
  const ACCESS4_MODIFY = 0x04;
@@ -220,6 +226,13 @@ const AUTH_SYS = 1;
220
226
  const MAX_OPAQUE_AUTH_BYTES = 400;
221
227
  /** The export accepts and generates only UTF-8 names (RFC 8881 Section 14.4). */
222
228
  const FSCHARSET_CAP4_ALLOWS_ONLY_UTF8 = 0x2;
229
+ // fh_expire_type (RFC 8881 Section 5.8.1.9): persistent handles never expire; volatile ones here expire only when
230
+ // the server restarts, never while a file is open. RFC 8881 Section 4.2.3 allows FH4_NOEXPIRE_WITH_OPEN only
231
+ // together with FH4_VOLATILE_ANY, so a volatile export sends both.
232
+ const FH4_PERSISTENT = 0x0;
233
+ const FH4_NOEXPIRE_WITH_OPEN = 0x1;
234
+ const FH4_VOLATILE_ANY = 0x2;
235
+ const FH4_VOLATILE_UNTIL_RESTART = FH4_VOLATILE_ANY | FH4_NOEXPIRE_WITH_OPEN;
223
236
  const SP4_NONE = 0;
224
237
  const SP4_MACH_CRED = 1;
225
238
  const SP4_SSV = 2;
@@ -236,7 +249,7 @@ const CLAIM_DELEG_CUR_FH = 5;
236
249
  const CLAIM_DELEG_PREV_FH = 6;
237
250
  /**
238
251
  * Worst-case encoded GETATTR result: the largest attribute set this server can return for a
239
- * 25-byte filehandle and bounded capacity is about 360 bytes; recheck when attributes grow.
252
+ * 57-byte filehandle and bounded capacity is about 390 bytes; recheck when attributes grow.
240
253
  */
241
254
  const MAX_GETATTR_REPLY_BYTES = 512;
242
255
  /** WRITE_LT and WRITEW_LT request exclusive ranges. */
@@ -341,10 +354,8 @@ const sameRequest = (left, right) => {
341
354
  return false;
342
355
  return true;
343
356
  };
344
- const bitmap = (reader, limit) => reader.array((item) => item.uint32(), limit);
345
- const writeBitmap = (writer, words) => {
346
- writer.array(words, (target, word) => target.uint32(word));
347
- };
357
+ const bitmap = (reader, limit) => reader.read(XdrCodec.array(XdrCodec.uint32, limit));
358
+ const writeBitmap = (writer, words) => writer.write(XdrCodec.array(XdrCodec.uint32), words);
348
359
  const attributesIn = (words) => {
349
360
  const result = [];
350
361
  for (let word = 0; word < words.length; word++) {
@@ -354,37 +365,49 @@ const attributesIn = (words) => {
354
365
  }
355
366
  return result;
356
367
  };
357
- const validateWritableAttributes = (words, bytes, limits) => {
368
+ const validateWritableAttributes = Effect.fnUntraced(function* (words, bytes, limits) {
358
369
  const attributes = attributesIn(words);
359
370
  if (attributes.some((attribute) => ![4, 33, 36, 37, 48, 54].includes(attribute)))
360
371
  return;
361
- const values = new Reader(bytes, limits);
372
+ const values = yield* xdr.openReader(bytes, limits);
362
373
  for (const attribute of attributes) {
363
374
  if (attribute === 4)
364
- values.uint64();
375
+ yield* values.read(XdrCodec.uint64);
365
376
  else if (attribute === 33)
366
- values.uint32();
377
+ yield* values.read(XdrCodec.uint32);
367
378
  else if (attribute === 36 || attribute === 37)
368
- values.string(limits.maxStringBytes);
379
+ yield* values.read(XdrCodec.string(limits.maxStringBytes));
369
380
  else if (attribute === 48 || attribute === 54) {
370
- const how = values.uint32();
381
+ const how = yield* values.read(XdrCodec.uint32);
371
382
  if (how === 1) {
372
- values.uint64();
373
- if (values.uint32() >= 1_000_000_000)
374
- throw new XdrDecodeError("Invalid attribute nanoseconds");
383
+ yield* values.read(XdrCodec.uint64);
384
+ if ((yield* values.read(XdrCodec.uint32)) >= 1_000_000_000) {
385
+ return yield* new XdrDecodeError({
386
+ reason: "range",
387
+ offset: yield* values.position,
388
+ path: ["attributes", attribute],
389
+ detail: "Invalid attribute nanoseconds"
390
+ });
391
+ }
392
+ }
393
+ else if (how !== 0) {
394
+ return yield* new XdrDecodeError({
395
+ reason: "discriminant",
396
+ offset: yield* values.position,
397
+ path: ["attributes", attribute],
398
+ detail: "Invalid set-time discriminant"
399
+ });
375
400
  }
376
- else if (how !== 0)
377
- throw new XdrDecodeError("Invalid set-time discriminant");
378
401
  }
379
402
  }
380
- values.finish();
381
- };
382
- const readAttributes = (reader, limits) => {
383
- const words = bitmap(reader, limits.maxBitmapWords);
384
- const values = reader.opaque(limits.maxOpaqueBytes);
385
- validateWritableAttributes(words, values, limits);
403
+ yield* values.finish;
404
+ });
405
+ const readAttributes = Effect.fnUntraced(function* (reader, limits) {
406
+ const words = yield* bitmap(reader, limits.maxBitmapWords);
407
+ const values = yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes));
408
+ yield* validateWritableAttributes(words, values, limits);
386
409
  return { bitmap: words, values };
387
- };
410
+ });
388
411
  const isNumericOwner = Schema.is(Schema.String.check(Schema.isPattern(/^(0|[1-9][0-9]*)$/)));
389
412
  const creationAttributes = Effect.fnUntraced(function* (create, limits, existing) {
390
413
  const attributes = attributesIn(create.attrs.bitmap);
@@ -393,7 +416,7 @@ const creationAttributes = Effect.fnUntraced(function* (create, limits, existing
393
416
  if (!supportedAttrs && !(existing && create.mode === 0)) {
394
417
  return yield* Effect.fail(create.mode === 3 ? Status.INVAL : Status.ATTRNOTSUPP);
395
418
  }
396
- const reader = new Reader(create.attrs.values, limits);
419
+ const reader = yield* xdr.openReader(create.attrs.values, limits);
397
420
  let mode = create.mode === 2 ? 0o600 : undefined;
398
421
  let size;
399
422
  const owner = {};
@@ -407,9 +430,9 @@ const creationAttributes = Effect.fnUntraced(function* (create, limits, existing
407
430
  if (!supported.includes(attribute))
408
431
  break;
409
432
  if (attribute === 4)
410
- size = reader.uint64();
433
+ size = yield* reader.read(XdrCodec.uint64);
411
434
  else if (attribute === 33) {
412
- const value = reader.uint32();
435
+ const value = yield* reader.read(XdrCodec.uint32);
413
436
  if (!existing) {
414
437
  if (value > 0o7777)
415
438
  return yield* Effect.fail(Status.INVAL);
@@ -417,7 +440,7 @@ const creationAttributes = Effect.fnUntraced(function* (create, limits, existing
417
440
  }
418
441
  }
419
442
  else if (attribute === 36 || attribute === 37) {
420
- const value = reader.string(limits.maxStringBytes);
443
+ const value = yield* reader.read(XdrCodec.string(limits.maxStringBytes));
421
444
  if (existing)
422
445
  continue;
423
446
  if (!isNumericOwner(value) || Number(value) > 0xffff_ffff)
@@ -428,10 +451,11 @@ const creationAttributes = Effect.fnUntraced(function* (create, limits, existing
428
451
  owner.gid = Number(value);
429
452
  }
430
453
  else {
431
- const how = reader.uint32();
454
+ const how = yield* reader.read(XdrCodec.uint32);
432
455
  const time = how === 0 ? { kind: "now" } : {
433
456
  kind: "value",
434
- nanoseconds: BigInt.asIntN(64, reader.uint64()) * 1000000000n + BigInt(reader.uint32())
457
+ nanoseconds: BigInt.asIntN(64, yield* reader.read(XdrCodec.uint64)) * 1000000000n +
458
+ BigInt(yield* reader.read(XdrCodec.uint32))
435
459
  };
436
460
  if (attribute === 48)
437
461
  times.access = time;
@@ -440,13 +464,16 @@ const creationAttributes = Effect.fnUntraced(function* (create, limits, existing
440
464
  }
441
465
  }
442
466
  if (supportedAttrs)
443
- reader.finish();
467
+ yield* reader.finish;
444
468
  if (create.mode >= 2) {
445
469
  // RFC 8881 18.16.4 permits timestamp storage. Both verifier halves enter
446
470
  // the creation candidate so a crash cannot separate the file from its verifier.
447
- const verifier = new Reader(create.verifier, limits);
448
- times.access = { kind: "value", nanoseconds: BigInt(verifier.uint32()) * 1000000000n };
449
- times.modification = { kind: "value", nanoseconds: BigInt(verifier.uint32()) * 1000000000n };
471
+ const verifier = yield* xdr.openReader(create.verifier, limits);
472
+ times.access = { kind: "value", nanoseconds: BigInt(yield* verifier.read(XdrCodec.uint32)) * 1000000000n };
473
+ times.modification = {
474
+ kind: "value",
475
+ nanoseconds: BigInt(yield* verifier.read(XdrCodec.uint32)) * 1000000000n
476
+ };
450
477
  }
451
478
  const settings = { times };
452
479
  if (mode !== undefined) {
@@ -465,73 +492,165 @@ const setattrAttributes = Effect.fnUntraced(function* (attrs, limits, supportedA
465
492
  if (invalid !== undefined) {
466
493
  return yield* Effect.fail(supportedAttributes.includes(invalid) ? Status.INVAL : Status.ATTRNOTSUPP);
467
494
  }
468
- const reader = new Reader(attrs.values, limits);
495
+ const reader = yield* xdr.openReader(attrs.values, limits);
469
496
  const changes = [];
470
497
  for (const attribute of attributes) {
471
498
  if (attribute === 4)
472
- changes.push({ kind: "size", attribute, value: reader.uint64() });
499
+ changes.push({ kind: "size", attribute, value: yield* reader.read(XdrCodec.uint64) });
473
500
  else if (attribute === 33) {
474
- const value = reader.uint32();
501
+ const value = yield* reader.read(XdrCodec.uint32);
475
502
  if (value > 0o7777)
476
503
  return yield* Effect.fail(Status.INVAL);
477
504
  changes.push({ kind: "mode", attribute, value });
478
505
  }
479
506
  else if (attribute === 36 || attribute === 37) {
480
- const value = reader.string(limits.maxStringBytes);
507
+ const value = yield* reader.read(XdrCodec.string(limits.maxStringBytes));
481
508
  if (!isNumericOwner(value) || Number(value) > 0xffff_ffff)
482
509
  return yield* Effect.fail(Status.BADOWNER);
483
510
  changes.push({ kind: "owner", attribute, value: Number(value) });
484
511
  }
485
512
  else if (attribute === 48 || attribute === 54) {
486
- const how = reader.uint32();
513
+ const how = yield* reader.read(XdrCodec.uint32);
487
514
  const value = how === 0 ? { kind: "now" } : {
488
515
  kind: "value",
489
- nanoseconds: BigInt.asIntN(64, reader.uint64()) * 1000000000n + BigInt(reader.uint32())
516
+ nanoseconds: BigInt.asIntN(64, yield* reader.read(XdrCodec.uint64)) * 1000000000n +
517
+ BigInt(yield* reader.read(XdrCodec.uint32))
490
518
  };
491
519
  changes.push({ kind: "time", attribute, value });
492
520
  }
493
521
  }
494
- reader.finish();
522
+ yield* reader.finish;
495
523
  return changes;
496
524
  });
497
- const readStateOwner = (reader, limits) => {
498
- reader.uint64();
499
- return reader.opaque(limits.maxOwnerBytes);
525
+ // The one core change a SETATTR's decoded attributes make: owner and group join one owner update, and the two
526
+ // times one times update that omits the one not given.
527
+ const setattrOptions = (changes) => {
528
+ const options = {};
529
+ const owner = {};
530
+ let access;
531
+ let modification;
532
+ for (const change of changes) {
533
+ if (change.kind === "size")
534
+ options.size = change.value;
535
+ else if (change.kind === "mode")
536
+ options.mode = change.value;
537
+ else if (change.kind === "owner" && change.attribute === 36)
538
+ owner.uid = change.value;
539
+ else if (change.kind === "owner")
540
+ owner.gid = change.value;
541
+ else if (change.attribute === 48)
542
+ access = change.value;
543
+ else
544
+ modification = change.value;
545
+ }
546
+ if (Object.keys(owner).length !== 0)
547
+ options.owner = owner;
548
+ if (access !== undefined || modification !== undefined) {
549
+ options.times = { access: access ?? { kind: "omit" }, modification: modification ?? { kind: "omit" } };
550
+ }
551
+ return options;
500
552
  };
501
- const readChannelAttrs = (reader) => ({
502
- headerPadding: reader.uint32(),
503
- maxRequest: reader.uint32(),
504
- maxResponse: reader.uint32(),
505
- maxCachedResponse: reader.uint32(),
506
- maxOperations: reader.uint32(),
507
- maxRequests: reader.uint32(),
508
- rdmaIrd: reader.array((item) => item.uint32(), 1)
553
+ // Linux knfsd's SETATTR (fs/nfsd/vfs.c) treats an owner or group equal to the object's current one as no change:
554
+ // notify_change's chown_ok and chgrp_ok (fs/attr.c) let the owner re-send its own uid, and its own gid without
555
+ // membership, and nfsd_sanitize_attrs revokes set-ID bits only when the uid or gid actually differs. Core's chown
556
+ // is POSIX and refuses a gid outside the caller's groups even when it is the current one, so the unchanged ids
557
+ // are dropped here. The owner update itself stays, possibly empty, so core still checks ownership as chown_ok does.
558
+ // For a real change of the owner or group of a non-directory that sets its mode too, nfsd_sanitize_attrs clears
559
+ // setuid from the requested mode, and setgid when the mode grants group execute (without it, setgid marks
560
+ // mandatory locking, not privilege). Core applies a requested mode after the owner, as POSIX chown then chmod
561
+ // does, so the sanitising happens here. An owner change without a mode needs nothing: core's chown already
562
+ // clears both bits on a regular file. The result pins the revision it observed, so core refuses it if another
563
+ // change lands before it applies.
564
+ const sanitizeSetattr = (export_, reference, options) => {
565
+ const { mode, owner } = options;
566
+ if (owner === undefined)
567
+ return Effect.succeed(options);
568
+ return Effect.map(export_.observeMetadata(reference), ({ value, revision }) => {
569
+ const changed = {};
570
+ if (owner.uid !== undefined && owner.uid !== value.uid)
571
+ changed.uid = owner.uid;
572
+ if (owner.gid !== undefined && owner.gid !== value.gid)
573
+ changed.gid = owner.gid;
574
+ const chowned = changed.uid !== undefined || changed.gid !== undefined;
575
+ return mode === undefined || !chowned || value.kind === "directory"
576
+ ? { ...options, owner: changed, expected: { revision } }
577
+ : {
578
+ ...options,
579
+ owner: changed,
580
+ mode: mode & ~(SET_UID | ((mode & GROUP_EXECUTE) === 0 ? 0 : SET_GID)),
581
+ expected: { revision }
582
+ };
583
+ });
584
+ };
585
+ // Re-observations a SETATTR makes when another change overtook the metadata its owner handling read, before
586
+ // answering DELAY so the client retries later.
587
+ const SETATTR_RETRIES = 3;
588
+ // Whether core refused a setattr because the target moved past the revision it was decided from.
589
+ const isStaleObservation = (error) => error.code === "StaleReference" && error.field === "expected";
590
+ // Sanitises and applies a SETATTR's attributes as one core change, re-observing when another change lands
591
+ // between the observation and the change, and failing with DELAY once the retries run out.
592
+ const applySetattr = (export_, reference, options) => {
593
+ const attempt = (retries) => sanitizeSetattr(export_, reference, options).pipe(Effect.flatMap((attributes) => export_.setattr(reference, attributes)), Effect.catchIf(isStaleObservation, () => retries === 0 ? Effect.fail(Status.DELAY) : attempt(retries - 1)));
594
+ return attempt(SETATTR_RETRIES);
595
+ };
596
+ const readStateOwner = Effect.fnUntraced(function* (reader, limits) {
597
+ yield* reader.read(XdrCodec.uint64);
598
+ return yield* reader.read(XdrCodec.opaque(limits.maxOwnerBytes));
509
599
  });
510
- const readCallbackSecurity = (reader, limits) => {
511
- const flavor = reader.uint32();
600
+ const ChannelAttrsCodec = XdrCodec.struct({
601
+ headerPadding: XdrCodec.uint32,
602
+ maxRequest: XdrCodec.uint32,
603
+ maxResponse: XdrCodec.uint32,
604
+ maxCachedResponse: XdrCodec.uint32,
605
+ maxOperations: XdrCodec.uint32,
606
+ maxRequests: XdrCodec.uint32,
607
+ rdmaIrd: XdrCodec.array(XdrCodec.uint32, 1)
608
+ });
609
+ const readChannelAttrs = (reader) => reader.read(ChannelAttrsCodec);
610
+ const readCallbackSecurity = Effect.fnUntraced(function* (reader, limits) {
611
+ const flavor = yield* reader.read(XdrCodec.uint32);
512
612
  if (flavor === 0)
513
613
  return { flavor };
514
614
  if (flavor === 1) {
515
- const stamp = reader.uint32();
516
- const machineName = reader.string(limits.maxStringBytes);
517
- const uid = reader.uint32();
518
- const gid = reader.uint32();
519
- const groups = reader.array((item) => item.uint32(), limits.maxArrayElements);
520
- return {
521
- flavor,
522
- credential: new Writer().uint32(stamp).string(machineName).uint32(uid).uint32(gid)
523
- .array(groups, (item, group) => item.uint32(group))
524
- .bytes()
525
- };
615
+ const stamp = yield* reader.read(XdrCodec.uint32);
616
+ const machineName = yield* reader.read(XdrCodec.string(limits.maxStringBytes));
617
+ const uid = yield* reader.read(XdrCodec.uint32);
618
+ const gid = yield* reader.read(XdrCodec.uint32);
619
+ const groups = yield* reader.read(XdrCodec.array(XdrCodec.uint32, limits.maxArrayElements));
620
+ const credential = yield* xdr.encode({ stamp, machineName, uid, gid, groups }, XdrCodec.struct({
621
+ stamp: XdrCodec.uint32,
622
+ machineName: XdrCodec.string(),
623
+ uid: XdrCodec.uint32,
624
+ gid: XdrCodec.uint32,
625
+ groups: XdrCodec.array(XdrCodec.uint32)
626
+ }), limits, ByteSize.toNumberUnsafe(limits.maxRecordBytes));
627
+ return { flavor, credential };
526
628
  }
527
629
  if (flavor === 6) {
528
- reader.uint32();
529
- reader.opaque(limits.maxOpaqueBytes);
530
- reader.opaque(limits.maxOpaqueBytes);
630
+ yield* reader.read(XdrCodec.uint32);
631
+ yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes));
632
+ yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes));
531
633
  return { flavor };
532
634
  }
533
- throw new XdrDecodeError("Unsupported callback security flavor");
534
- };
635
+ return yield* new XdrDecodeError({
636
+ reason: "discriminant",
637
+ offset: yield* reader.position,
638
+ path: [],
639
+ detail: "Unsupported callback security flavor"
640
+ });
641
+ });
642
+ const readCallbackSecurityArray = Effect.fnUntraced(function* (reader, limits) {
643
+ const count = yield* reader.read(XdrCodec.uint32);
644
+ if (count > limits.maxArrayElements) {
645
+ return yield* new XdrDecodeError({
646
+ reason: "length-limit",
647
+ offset: yield* reader.position,
648
+ path: [],
649
+ detail: "XDR array exceeds its element limit"
650
+ });
651
+ }
652
+ return yield* Effect.forEach(Array.from({ length: count }), () => readCallbackSecurity(reader, limits));
653
+ });
535
654
  /**
536
655
  * Picks the credential a callback will carry. AUTH_NONE is preferred when the client offered it,
537
656
  * since it needs no identity; otherwise the client's own AUTH_SYS credential is used. A client
@@ -544,59 +663,73 @@ const readCallbackSecurity = (reader, limits) => {
544
663
  */
545
664
  const chooseCallbackSecurity = (offered) => offered.find((entry) => entry.flavor === AUTH_NONE) ??
546
665
  offered.find((entry) => entry.flavor === AUTH_SYS && (entry.credential?.length ?? 0) <= MAX_OPAQUE_AUTH_BYTES);
547
- const writeChannelAttrs = (writer, attrs) => {
548
- writer.uint32(attrs.headerPadding).uint32(attrs.maxRequest).uint32(attrs.maxResponse)
549
- .uint32(attrs.maxCachedResponse).uint32(attrs.maxOperations).uint32(attrs.maxRequests)
550
- .array(attrs.rdmaIrd, (item, value) => item.uint32(value));
551
- };
666
+ const writeChannelAttrs = (writer, attrs) => writer.write(ChannelAttrsCodec, attrs);
552
667
  /** state_protect_ops4: the operations a client wants enforced and allowed under the protection. */
553
- const readStateProtectOps = (reader, limits) => {
554
- bitmap(reader, limits.maxBitmapWords);
555
- bitmap(reader, limits.maxBitmapWords);
556
- };
557
- const readStateProtection = (reader, limits) => {
558
- const how = reader.uint32();
668
+ const readStateProtectOps = Effect.fnUntraced(function* (reader, limits) {
669
+ yield* bitmap(reader, limits.maxBitmapWords);
670
+ yield* bitmap(reader, limits.maxBitmapWords);
671
+ });
672
+ const readStateProtection = Effect.fnUntraced(function* (reader, limits) {
673
+ const how = yield* reader.read(XdrCodec.uint32);
559
674
  if (how === SP4_MACH_CRED) {
560
- readStateProtectOps(reader, limits);
675
+ yield* readStateProtectOps(reader, limits);
561
676
  }
562
677
  else if (how === SP4_SSV) {
563
678
  // ssv_sp_parms4: ops, hash and encryption algorithm lists, window, and GSS handle count.
564
- readStateProtectOps(reader, limits);
565
- reader.array((item) => item.opaque(limits.maxOpaqueBytes), limits.maxArrayElements);
566
- reader.array((item) => item.opaque(limits.maxOpaqueBytes), limits.maxArrayElements);
567
- reader.uint32();
568
- reader.uint32();
679
+ yield* readStateProtectOps(reader, limits);
680
+ yield* reader.read(XdrCodec.array(XdrCodec.opaque(limits.maxOpaqueBytes), limits.maxArrayElements));
681
+ yield* reader.read(XdrCodec.array(XdrCodec.opaque(limits.maxOpaqueBytes), limits.maxArrayElements));
682
+ yield* reader.read(XdrCodec.uint32);
683
+ yield* reader.read(XdrCodec.uint32);
569
684
  }
570
685
  else if (how !== SP4_NONE) {
571
- throw new XdrDecodeError("Invalid state protection discriminant");
686
+ return yield* new XdrDecodeError({
687
+ reason: "discriminant",
688
+ offset: yield* reader.position,
689
+ path: [],
690
+ detail: "Invalid state protection discriminant"
691
+ });
572
692
  }
573
693
  return how;
574
- };
575
- const readLockType = (reader) => {
576
- const lockType = reader.uint32();
577
- if (lockType < 1 || lockType > 4)
578
- throw new XdrDecodeError("Invalid lock type");
694
+ });
695
+ const readLockType = Effect.fnUntraced(function* (reader) {
696
+ const lockType = yield* reader.read(XdrCodec.uint32);
697
+ if (lockType < 1 || lockType > 4) {
698
+ return yield* new XdrDecodeError({
699
+ reason: "range",
700
+ offset: yield* reader.position,
701
+ path: [],
702
+ detail: "Invalid lock type"
703
+ });
704
+ }
579
705
  return lockType;
580
- };
581
- const decodeOperation = (code, reader, limits) => {
706
+ });
707
+ const decodeOperation = Effect.fnUntraced(function* (code, reader, limits) {
582
708
  switch (code) {
583
709
  case Operation.ACCESS:
584
- return { kind: "Access", code, value: reader.uint32() };
710
+ return { kind: "Access", code, value: (yield* reader.read(XdrCodec.uint32)) };
585
711
  case Operation.CLOSE:
586
- return { kind: "Close", code, value: { sequence: reader.uint32(), stateid: reader.fixedOpaque(16) } };
712
+ return {
713
+ kind: "Close",
714
+ code,
715
+ value: {
716
+ sequence: (yield* reader.read(XdrCodec.uint32)),
717
+ stateid: (yield* reader.read(XdrCodec.fixedOpaque(16)))
718
+ }
719
+ };
587
720
  case Operation.CREATE: {
588
- const kind = reader.uint32();
589
- const target = kind === 5 ? reader.string(limits.maxStringBytes) : undefined;
721
+ const kind = yield* reader.read(XdrCodec.uint32);
722
+ const target = kind === 5 ? (yield* reader.read(XdrCodec.string(limits.maxStringBytes))) : undefined;
590
723
  if (kind === 3 || kind === 4) {
591
- reader.uint32();
592
- reader.uint32();
724
+ yield* reader.read(XdrCodec.uint32);
725
+ yield* reader.read(XdrCodec.uint32);
593
726
  }
594
- const name = reader.opaque(limits.maxOpaqueBytes);
595
- const attrs = readAttributes(reader, limits);
727
+ const name = yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes));
728
+ const attrs = yield* readAttributes(reader, limits);
596
729
  return { kind: "Create", code, value: { kind, name, attrs, target } };
597
730
  }
598
731
  case Operation.GETATTR:
599
- return { kind: "Getattr", code, value: bitmap(reader, limits.maxBitmapWords) };
732
+ return { kind: "Getattr", code, value: (yield* bitmap(reader, limits.maxBitmapWords)) };
600
733
  case Operation.GETFH:
601
734
  return { kind: "Getfh", code, value: undefined };
602
735
  case Operation.LOOKUPP:
@@ -610,90 +743,113 @@ const decodeOperation = (code, reader, limits) => {
610
743
  case Operation.SAVEFH:
611
744
  return { kind: "Savefh", code, value: undefined };
612
745
  case Operation.LINK:
613
- return { kind: "Link", code, value: reader.opaque(limits.maxOpaqueBytes) };
746
+ return { kind: "Link", code, value: (yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes))) };
614
747
  case Operation.LOOKUP:
615
- return { kind: "Lookup", code, value: reader.opaque(limits.maxOpaqueBytes) };
748
+ return { kind: "Lookup", code, value: (yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes))) };
616
749
  case Operation.REMOVE:
617
- return { kind: "Remove", code, value: reader.opaque(limits.maxOpaqueBytes) };
750
+ return { kind: "Remove", code, value: (yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes))) };
618
751
  case Operation.OPEN: {
619
- const sequence = reader.uint32();
620
- const access = reader.uint32();
621
- const deny = reader.uint32();
622
- const client = reader.uint64();
623
- const owner = reader.opaque(limits.maxOwnerBytes);
624
- const openHow = reader.uint32();
752
+ const sequence = yield* reader.read(XdrCodec.uint32);
753
+ const access = yield* reader.read(XdrCodec.uint32);
754
+ const deny = yield* reader.read(XdrCodec.uint32);
755
+ const client = yield* reader.read(XdrCodec.uint64);
756
+ const owner = yield* reader.read(XdrCodec.opaque(limits.maxOwnerBytes));
757
+ const openHow = yield* reader.read(XdrCodec.uint32);
625
758
  let create;
626
759
  if (openHow === 1) {
627
- const createMode = reader.uint32();
760
+ const createMode = yield* reader.read(XdrCodec.uint32);
628
761
  let verifier = empty;
629
762
  let attrs = { bitmap: [], values: empty };
630
763
  if (createMode === 0 || createMode === 1) {
631
- attrs = readAttributes(reader, limits);
764
+ attrs = yield* readAttributes(reader, limits);
632
765
  }
633
766
  else if (createMode === 2) {
634
- verifier = reader.fixedOpaque(8);
767
+ verifier = yield* reader.read(XdrCodec.fixedOpaque(8));
635
768
  }
636
769
  else if (createMode === 3) {
637
- verifier = reader.fixedOpaque(8);
638
- attrs = readAttributes(reader, limits);
770
+ verifier = yield* reader.read(XdrCodec.fixedOpaque(8));
771
+ attrs = yield* readAttributes(reader, limits);
639
772
  }
640
773
  else {
641
- throw new XdrDecodeError("Invalid OPEN create mode");
774
+ return yield* new XdrDecodeError({
775
+ reason: "discriminant",
776
+ offset: yield* reader.position,
777
+ path: [],
778
+ detail: "Invalid OPEN create mode"
779
+ });
642
780
  }
643
781
  create = { mode: createMode, verifier, attrs };
644
782
  }
645
783
  else if (openHow !== 0) {
646
- throw new XdrDecodeError("Invalid OPEN how discriminant");
784
+ return yield* new XdrDecodeError({
785
+ reason: "discriminant",
786
+ offset: yield* reader.position,
787
+ path: [],
788
+ detail: "Invalid OPEN how discriminant"
789
+ });
647
790
  }
648
- const claim = reader.uint32();
791
+ const claim = yield* reader.read(XdrCodec.uint32);
649
792
  let name = empty;
650
793
  if (claim === 0 || claim === 3)
651
- name = reader.opaque(limits.maxOpaqueBytes);
794
+ name = yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes));
652
795
  else if (claim === 1)
653
- reader.uint32();
796
+ yield* reader.read(XdrCodec.uint32);
654
797
  else if (claim === 2) {
655
- reader.fixedOpaque(16);
656
- name = reader.opaque(limits.maxOpaqueBytes);
798
+ yield* reader.read(XdrCodec.fixedOpaque(16));
799
+ name = yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes));
657
800
  }
658
801
  else if (claim === 5)
659
- reader.fixedOpaque(16);
660
- else if (claim !== 4 && claim !== 6)
661
- throw new XdrDecodeError("Invalid OPEN claim");
802
+ yield* reader.read(XdrCodec.fixedOpaque(16));
803
+ else if (claim !== 4 && claim !== 6) {
804
+ return yield* new XdrDecodeError({
805
+ reason: "discriminant",
806
+ offset: yield* reader.position,
807
+ path: [],
808
+ detail: "Invalid OPEN claim"
809
+ });
810
+ }
662
811
  return { kind: "Open", code, value: { sequence, access, deny, client, owner, openHow, create, claim, name } };
663
812
  }
664
813
  case Operation.PUTFH:
665
- return { kind: "Putfh", code, value: reader.opaque(limits.maxOpaqueBytes) };
814
+ return { kind: "Putfh", code, value: (yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes))) };
666
815
  case Operation.READ:
667
816
  return {
668
817
  code,
669
818
  kind: "Read",
670
- value: { stateid: reader.fixedOpaque(16), offset: reader.uint64(), count: reader.uint32() }
819
+ value: {
820
+ stateid: (yield* reader.read(XdrCodec.fixedOpaque(16))),
821
+ offset: (yield* reader.read(XdrCodec.uint64)),
822
+ count: (yield* reader.read(XdrCodec.uint32))
823
+ }
671
824
  };
672
825
  case Operation.READDIR:
673
826
  return {
674
827
  code,
675
828
  kind: "Readdir",
676
829
  value: {
677
- cookie: reader.uint64(),
678
- verifier: reader.fixedOpaque(8),
679
- dircount: reader.uint32(),
680
- maxcount: reader.uint32(),
681
- attrs: bitmap(reader, limits.maxBitmapWords)
830
+ cookie: (yield* reader.read(XdrCodec.uint64)),
831
+ verifier: (yield* reader.read(XdrCodec.fixedOpaque(8))),
832
+ dircount: (yield* reader.read(XdrCodec.uint32)),
833
+ maxcount: (yield* reader.read(XdrCodec.uint32)),
834
+ attrs: (yield* bitmap(reader, limits.maxBitmapWords))
682
835
  }
683
836
  };
684
837
  case Operation.RENAME:
685
838
  return {
686
839
  code,
687
840
  kind: "Rename",
688
- value: { oldName: reader.opaque(limits.maxOpaqueBytes), newName: reader.opaque(limits.maxOpaqueBytes) }
841
+ value: {
842
+ oldName: (yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes))),
843
+ newName: (yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes)))
844
+ }
689
845
  };
690
846
  case Operation.SETATTR:
691
847
  return {
692
848
  code,
693
849
  kind: "Setattr",
694
850
  value: {
695
- stateid: reader.fixedOpaque(16),
696
- attrs: readAttributes(reader, limits)
851
+ stateid: (yield* reader.read(XdrCodec.fixedOpaque(16))),
852
+ attrs: (yield* readAttributes(reader, limits))
697
853
  }
698
854
  };
699
855
  case Operation.WRITE:
@@ -701,34 +857,34 @@ const decodeOperation = (code, reader, limits) => {
701
857
  code,
702
858
  kind: "Write",
703
859
  value: {
704
- stateid: reader.fixedOpaque(16),
705
- offset: reader.uint64(),
706
- stable: reader.uint32(),
707
- data: reader.opaque(limits.maxWriteBytes)
860
+ stateid: (yield* reader.read(XdrCodec.fixedOpaque(16))),
861
+ offset: (yield* reader.read(XdrCodec.uint64)),
862
+ stable: (yield* reader.read(XdrCodec.uint32)),
863
+ data: (yield* reader.read(XdrCodec.opaque(limits.maxWriteBytes)))
708
864
  }
709
865
  };
710
866
  case Operation.EXCHANGE_ID: {
711
- const verifier = reader.fixedOpaque(8);
712
- const owner = reader.opaque(limits.maxOwnerBytes);
713
- const flags = reader.uint32();
714
- const protection = readStateProtection(reader, limits);
867
+ const verifier = yield* reader.read(XdrCodec.fixedOpaque(8));
868
+ const owner = yield* reader.read(XdrCodec.opaque(limits.maxOwnerBytes));
869
+ const flags = yield* reader.read(XdrCodec.uint32);
870
+ const protection = yield* readStateProtection(reader, limits);
715
871
  // eia_client_impl_id<1>: at most one implementation record (RFC 5662).
716
- reader.array((item) => {
717
- item.string(limits.maxStringBytes);
718
- item.string(limits.maxStringBytes);
719
- item.uint64();
720
- item.uint32();
721
- }, 1);
872
+ yield* reader.read(XdrCodec.array(XdrCodec.struct({
873
+ domain: XdrCodec.string(limits.maxStringBytes),
874
+ name: XdrCodec.string(limits.maxStringBytes),
875
+ seconds: XdrCodec.uint64,
876
+ nanoseconds: XdrCodec.uint32
877
+ }), 1));
722
878
  return { kind: "ExchangeId", code, value: { verifier, owner, flags, protection } };
723
879
  }
724
880
  case Operation.CREATE_SESSION: {
725
- const client = reader.uint64();
726
- const sequence = reader.uint32();
727
- const flags = reader.uint32();
728
- const fore = readChannelAttrs(reader);
729
- const back = readChannelAttrs(reader);
730
- const callbackProgram = reader.uint32();
731
- const flavors = reader.array((item) => readCallbackSecurity(item, limits), limits.maxArrayElements);
881
+ const client = yield* reader.read(XdrCodec.uint64);
882
+ const sequence = yield* reader.read(XdrCodec.uint32);
883
+ const flags = yield* reader.read(XdrCodec.uint32);
884
+ const fore = yield* readChannelAttrs(reader);
885
+ const back = yield* readChannelAttrs(reader);
886
+ const callbackProgram = yield* reader.read(XdrCodec.uint32);
887
+ const flavors = yield* readCallbackSecurityArray(reader, limits);
732
888
  return {
733
889
  kind: "CreateSession",
734
890
  code,
@@ -745,57 +901,61 @@ const decodeOperation = (code, reader, limits) => {
745
901
  };
746
902
  }
747
903
  case Operation.DESTROY_SESSION:
748
- return { kind: "DestroySession", code, value: reader.fixedOpaque(16) };
904
+ return { kind: "DestroySession", code, value: (yield* reader.read(XdrCodec.fixedOpaque(16))) };
749
905
  case Operation.SEQUENCE:
750
906
  return {
751
907
  code,
752
908
  kind: "Sequence",
753
909
  value: {
754
- session: reader.fixedOpaque(16),
755
- sequence: reader.uint32(),
756
- slot: reader.uint32(),
757
- highest: reader.uint32(),
758
- cache: reader.boolean()
910
+ session: (yield* reader.read(XdrCodec.fixedOpaque(16))),
911
+ sequence: (yield* reader.read(XdrCodec.uint32)),
912
+ slot: (yield* reader.read(XdrCodec.uint32)),
913
+ highest: (yield* reader.read(XdrCodec.uint32)),
914
+ cache: (yield* reader.read(XdrCodec.boolean))
759
915
  }
760
916
  };
761
917
  case Operation.DESTROY_CLIENTID:
762
- return { kind: "DestroyClient", code, value: reader.uint64() };
918
+ return { kind: "DestroyClient", code, value: (yield* reader.read(XdrCodec.uint64)) };
763
919
  case Operation.RECLAIM_COMPLETE:
764
- return { kind: "ReclaimComplete", code, value: reader.boolean() };
920
+ return { kind: "ReclaimComplete", code, value: (yield* reader.read(XdrCodec.boolean)) };
765
921
  case Operation.COMMIT:
766
- return { kind: "Commit", code, value: { offset: reader.uint64(), count: reader.uint32() } };
922
+ return {
923
+ kind: "Commit",
924
+ code,
925
+ value: { offset: (yield* reader.read(XdrCodec.uint64)), count: (yield* reader.read(XdrCodec.uint32)) }
926
+ };
767
927
  case Operation.LOCK: {
768
- const lockType = readLockType(reader);
769
- const reclaim = reader.boolean();
770
- const offset = reader.uint64();
771
- const length = reader.uint64();
928
+ const lockType = yield* readLockType(reader);
929
+ const reclaim = yield* reader.read(XdrCodec.boolean);
930
+ const offset = yield* reader.read(XdrCodec.uint64);
931
+ const length = yield* reader.read(XdrCodec.uint64);
772
932
  let locker;
773
- if (reader.boolean()) {
774
- reader.uint32();
775
- const stateid = reader.fixedOpaque(16);
776
- reader.uint32();
777
- locker = { kind: "new", stateid, owner: readStateOwner(reader, limits) };
933
+ if ((yield* reader.read(XdrCodec.boolean))) {
934
+ yield* reader.read(XdrCodec.uint32);
935
+ const stateid = yield* reader.read(XdrCodec.fixedOpaque(16));
936
+ yield* reader.read(XdrCodec.uint32);
937
+ locker = { kind: "new", stateid, owner: (yield* readStateOwner(reader, limits)) };
778
938
  }
779
939
  else {
780
- const stateid = reader.fixedOpaque(16);
781
- reader.uint32();
940
+ const stateid = yield* reader.read(XdrCodec.fixedOpaque(16));
941
+ yield* reader.read(XdrCodec.uint32);
782
942
  locker = { kind: "existing", stateid };
783
943
  }
784
944
  return { kind: "Lock", code, value: { lockType, reclaim, offset, length, locker } };
785
945
  }
786
946
  case Operation.LOCKT: {
787
- const lockType = readLockType(reader);
788
- const offset = reader.uint64();
789
- const length = reader.uint64();
790
- const owner = readStateOwner(reader, limits);
947
+ const lockType = yield* readLockType(reader);
948
+ const offset = yield* reader.read(XdrCodec.uint64);
949
+ const length = yield* reader.read(XdrCodec.uint64);
950
+ const owner = yield* readStateOwner(reader, limits);
791
951
  return { kind: "Lockt", code, value: { lockType, offset, length, owner } };
792
952
  }
793
953
  case Operation.LOCKU: {
794
- readLockType(reader);
795
- reader.uint32();
796
- const stateid = reader.fixedOpaque(16);
797
- const offset = reader.uint64();
798
- const length = reader.uint64();
954
+ yield* readLockType(reader);
955
+ yield* reader.read(XdrCodec.uint32);
956
+ const stateid = yield* reader.read(XdrCodec.fixedOpaque(16));
957
+ const offset = yield* reader.read(XdrCodec.uint64);
958
+ const length = yield* reader.read(XdrCodec.uint64);
799
959
  return { kind: "Locku", code, value: { stateid, offset, length } };
800
960
  }
801
961
  case Operation.NVERIFY:
@@ -803,35 +963,43 @@ const decodeOperation = (code, reader, limits) => {
803
963
  return {
804
964
  kind: "Verify",
805
965
  code,
806
- value: { bitmap: bitmap(reader, limits.maxBitmapWords), values: reader.opaque(limits.maxOpaqueBytes) }
966
+ value: {
967
+ bitmap: (yield* bitmap(reader, limits.maxBitmapWords)),
968
+ values: (yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes)))
969
+ }
807
970
  };
808
971
  case Operation.OPEN_DOWNGRADE:
809
972
  return {
810
973
  kind: "OpenDowngrade",
811
974
  code,
812
975
  value: {
813
- stateid: reader.fixedOpaque(16),
814
- sequence: reader.uint32(),
815
- access: reader.uint32(),
816
- deny: reader.uint32()
976
+ stateid: (yield* reader.read(XdrCodec.fixedOpaque(16))),
977
+ sequence: (yield* reader.read(XdrCodec.uint32)),
978
+ access: (yield* reader.read(XdrCodec.uint32)),
979
+ deny: (yield* reader.read(XdrCodec.uint32))
817
980
  }
818
981
  };
819
982
  case Operation.PUTPUBFH:
820
983
  return { kind: "Putpubfh", code, value: undefined };
821
984
  case Operation.SECINFO:
822
- return { kind: "Secinfo", code, value: reader.opaque(limits.maxOpaqueBytes) };
985
+ return { kind: "Secinfo", code, value: (yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes))) };
823
986
  case Operation.SECINFO_NO_NAME: {
824
- const style = reader.uint32();
987
+ const style = yield* reader.read(XdrCodec.uint32);
825
988
  if (style !== SECINFO_STYLE4_CURRENT_FH && style !== SECINFO_STYLE4_PARENT) {
826
- throw new XdrDecodeError("Invalid SECINFO_NO_NAME style");
989
+ return yield* new XdrDecodeError({
990
+ reason: "discriminant",
991
+ offset: yield* reader.position,
992
+ path: [],
993
+ detail: "Invalid SECINFO_NO_NAME style"
994
+ });
827
995
  }
828
996
  return { kind: "SecinfoNoName", code, value: style };
829
997
  }
830
998
  case Operation.FREE_STATEID:
831
- return { kind: "FreeStateid", code, value: reader.fixedOpaque(16) };
999
+ return { kind: "FreeStateid", code, value: (yield* reader.read(XdrCodec.fixedOpaque(16))) };
832
1000
  case Operation.BACKCHANNEL_CTL: {
833
- const program = reader.uint32();
834
- const flavors = reader.array((item) => readCallbackSecurity(item, limits), limits.maxArrayElements);
1001
+ const program = yield* reader.read(XdrCodec.uint32);
1002
+ const flavors = yield* readCallbackSecurityArray(reader, limits);
835
1003
  return {
836
1004
  kind: "BackchannelCtl",
837
1005
  code,
@@ -839,24 +1007,29 @@ const decodeOperation = (code, reader, limits) => {
839
1007
  };
840
1008
  }
841
1009
  case Operation.BIND_CONN_TO_SESSION: {
842
- const session = reader.fixedOpaque(16);
843
- const direction = reader.uint32();
1010
+ const session = yield* reader.read(XdrCodec.fixedOpaque(16));
1011
+ const direction = yield* reader.read(XdrCodec.uint32);
844
1012
  // channel_dir_from_client4: FORE (1), BACK (2), FORE_OR_BOTH (3), or BACK_OR_BOTH (7).
845
1013
  if (direction < CDFC4_FORE || (direction > CDFC4_FORE_OR_BOTH && direction !== CDFC4_BACK_OR_BOTH)) {
846
- throw new XdrDecodeError("Invalid channel direction");
1014
+ return yield* new XdrDecodeError({
1015
+ reason: "discriminant",
1016
+ offset: yield* reader.position,
1017
+ path: [],
1018
+ detail: "Invalid channel direction"
1019
+ });
847
1020
  }
848
- reader.boolean();
1021
+ yield* reader.read(XdrCodec.boolean);
849
1022
  return { kind: "BindConnToSession", code, value: { session, direction } };
850
1023
  }
851
1024
  case Operation.SET_SSV:
852
- reader.opaque(limits.maxOpaqueBytes);
853
- reader.opaque(limits.maxOpaqueBytes);
1025
+ yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes));
1026
+ yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes));
854
1027
  return { kind: "SetSsv", code, value: undefined };
855
1028
  case Operation.TEST_STATEID:
856
1029
  return {
857
1030
  kind: "TestStateid",
858
1031
  code,
859
- value: reader.array((item) => item.fixedOpaque(16), limits.maxArrayElements)
1032
+ value: yield* reader.read(XdrCodec.array(XdrCodec.fixedOpaque(16), limits.maxArrayElements))
860
1033
  };
861
1034
  default:
862
1035
  if (mustNotImplementOperations.has(code) || unsupportedOptionalOperations.has(code)) {
@@ -864,22 +1037,37 @@ const decodeOperation = (code, reader, limits) => {
864
1037
  }
865
1038
  return { kind: "Unknown", code, value: undefined };
866
1039
  }
867
- };
868
- const parseCompound = (bytes, limits) => {
869
- if (byteLength(bytes.length) > limits.maxCompoundBytes)
870
- throw new XdrDecodeError("COMPOUND exceeds byte limit");
871
- const reader = new Reader(bytes, limits);
872
- const tag = reader.opaque(limits.maxStringBytes);
873
- const minor = reader.uint32();
874
- const count = reader.uint32();
1040
+ });
1041
+ const parseCompound = Effect.fnUntraced(function* (bytes, limits) {
1042
+ if (byteLength(bytes.length) > limits.maxCompoundBytes) {
1043
+ return yield* new XdrDecodeError({
1044
+ reason: "length-limit",
1045
+ offset: 0,
1046
+ path: [],
1047
+ detail: "COMPOUND exceeds byte limit"
1048
+ });
1049
+ }
1050
+ const reader = yield* xdr.openReader(bytes, limits);
1051
+ const tag = yield* reader.read(XdrCodec.opaque(limits.maxStringBytes));
1052
+ const minor = yield* reader.read(XdrCodec.uint32);
1053
+ const count = yield* reader.read(XdrCodec.uint32);
875
1054
  if (count > limits.maxOperations || count > limits.maxArrayElements) {
876
- throw new XdrDecodeError("COMPOUND operation count exceeds its limit");
1055
+ return yield* new XdrDecodeError({
1056
+ reason: "length-limit",
1057
+ offset: yield* reader.position,
1058
+ path: [],
1059
+ detail: "COMPOUND operation count exceeds its limit"
1060
+ });
877
1061
  }
878
1062
  const operations = [];
879
1063
  let stopped = false;
880
1064
  for (let index = 0; index < count; index++) {
881
- const code = reader.uint32();
882
- const operation = decodeOperation_(code);
1065
+ const code = yield* reader.read(XdrCodec.uint32);
1066
+ const decoded = yield* Effect.result(decodeOperation(code, reader, limits));
1067
+ // SAFETY: decodeOperation returns a ParsedOperation on every successful branch.
1068
+ const operation = Result.isFailure(decoded)
1069
+ ? { kind: "Malformed", code, value: undefined }
1070
+ : decoded.success;
883
1071
  operations.push(operation);
884
1072
  // The compound fails at an undecoded operation, so later bytes are never interpreted.
885
1073
  if (operation.kind === "Unknown" || operation.kind === "NotSupported" || operation.kind === "Malformed") {
@@ -888,39 +1076,29 @@ const parseCompound = (bytes, limits) => {
888
1076
  }
889
1077
  }
890
1078
  if (!stopped)
891
- reader.finish();
1079
+ yield* reader.finish;
892
1080
  return { tag, minor, count, operations };
893
- /**
894
- * Section 15.1.1.1 defines NFS4ERR_BADXDR per operation: the operations before a
895
- * malformed one are still processed and reported.
896
- */
897
- function decodeOperation_(code) {
898
- try {
899
- return decodeOperation(code, reader, limits);
900
- }
901
- catch (error) {
902
- if (!(error instanceof XdrDecodeError))
903
- throw error;
904
- return { kind: "Malformed", code, value: undefined };
905
- }
906
- }
907
- };
908
- const encodeCompound = (tag, parts, overallStatus = parts.find((part) => part.status !== Status.OK)?.status ?? Status.OK) => {
909
- const status = overallStatus;
910
- const writer = new Writer().uint32(status).opaque(tag).uint32(parts.length);
1081
+ });
1082
+ const encodeCompound = (limits, tag, parts, overallStatus = parts.find((part) => part.status !== Status.OK)?.status ?? Status.OK) => Effect.gen(function* () {
1083
+ const writer = yield* xdr.openWriter(limits, ByteSize.toNumberUnsafe(limits.maxRecordBytes));
1084
+ yield* writer.write(XdrCodec.uint32, overallStatus);
1085
+ yield* writer.write(XdrCodec.opaque(limits.maxStringBytes), tag);
1086
+ yield* writer.write(XdrCodec.uint32, parts.length);
911
1087
  for (const part of parts) {
912
- writer.uint32(part.code).uint32(part.status);
1088
+ yield* writer.write(XdrCodec.uint32, part.code);
1089
+ yield* writer.write(XdrCodec.uint32, part.status);
913
1090
  if (part.body !== undefined)
914
- writer.fixedOpaque(part.body);
1091
+ yield* writer.appendEncoded(part.body);
915
1092
  }
916
- return writer.bytes();
917
- };
1093
+ return yield* writer.finish;
1094
+ });
918
1095
  const fsStatuses = {
919
1096
  NotFound: Status.NOENT,
920
1097
  AlreadyExists: Status.EXIST,
921
1098
  NotEmpty: Status.NOTEMPTY,
922
1099
  NotDirectory: Status.NOTDIR,
923
1100
  AccessDenied: Status.ACCESS,
1101
+ NotPermitted: Status.PERM,
924
1102
  InvalidHandle: Status.SERVERFAULT,
925
1103
  ForeignHandle: Status.SERVERFAULT,
926
1104
  InvalidReference: Status.SERVERFAULT,
@@ -940,15 +1118,55 @@ const fsStatuses = {
940
1118
  VolumeBusy: Status.DELAY,
941
1119
  // NFSv4.1 has no LOOP status. The reference-based NFS read path never follows symbolic links.
942
1120
  SymlinkLoop: Status.INVAL,
943
- UnrepresentableName: Status.INVAL
1121
+ UnrepresentableName: Status.INVAL,
1122
+ // Codec and store failures never reach an NFS operation; a server fault says so if one does.
1123
+ InvalidEncoding: Status.SERVERFAULT,
1124
+ UnsupportedVersion: Status.SERVERFAULT,
1125
+ InvalidStructure: Status.SERVERFAULT,
1126
+ LimitExceeded: Status.SERVERFAULT,
1127
+ BaseMismatch: Status.SERVERFAULT,
1128
+ Storage: Status.IO,
1129
+ Ownership: Status.IO,
1130
+ IncompatibleStore: Status.IO,
1131
+ CorruptStore: Status.IO
944
1132
  };
1133
+ // RFC 8881 Section 15.2 lists NFS4ERR_PERM for CREATE, OPEN and SETATTR only. Core's NotPermitted (EPERM) from
1134
+ // any other operation, such as a sticky-directory REMOVE or RENAME, answers ACCESS, which their Section 15.2 lists
1135
+ // include.
1136
+ const PERM_OPERATIONS = new Set([Operation.CREATE, Operation.OPEN, Operation.SETATTR]);
1137
+ // The table is total over the codes this build knows. The guard is for a core release newer than this server,
1138
+ // whose errors can carry a code added since, which a client should see as a server fault.
945
1139
  /** @internal */
946
- export const failureForFs = (error) => Object.hasOwn(fsStatuses, error.code) ? fsStatuses[error.code] : Status.SERVERFAULT;
947
- const encodeStatusBody = (build) => {
948
- const writer = new Writer();
949
- build(writer);
950
- return writer.bytes();
1140
+ export const failureForFs = (error, operation) => {
1141
+ if (!Object.hasOwn(fsStatuses, error.code))
1142
+ return Status.SERVERFAULT;
1143
+ const status = fsStatuses[error.code];
1144
+ return status === Status.PERM && !PERM_OPERATIONS.has(operation) ? Status.ACCESS : status;
951
1145
  };
1146
+ // RFC 8881 Section 15.2 lists these for PUTFH; a volume failure outside them answers SERVERFAULT, which it includes.
1147
+ const PUTFH_STATUSES = new Set([
1148
+ Status.BADHANDLE,
1149
+ Status.DELAY,
1150
+ Status.FHEXPIRED,
1151
+ Status.SERVERFAULT,
1152
+ Status.STALE
1153
+ ]);
1154
+ // A handle the export could not read, or one from another volume or epoch, keeps its filehandle status; any other
1155
+ // volume failure goes through the shared table, so a gone object is STALE and a busy volume DELAY.
1156
+ /** @internal */
1157
+ export const putfhFailure = (error) => {
1158
+ if (error instanceof InvalidFilehandleError) {
1159
+ return error.reason === "Expired" ? Status.FHEXPIRED : error.reason === "Stale" ? Status.STALE : Status.BADHANDLE;
1160
+ }
1161
+ const status = failureForFs(error, Operation.PUTFH);
1162
+ return PUTFH_STATUSES.has(status) ? status : Status.SERVERFAULT;
1163
+ };
1164
+ const field = (codec, value) => (writer) => writer.write(codec, value);
1165
+ const encodeStatusBody = (limits, fields) => Effect.gen(function* () {
1166
+ const writer = yield* xdr.openWriter(limits, ByteSize.toNumberUnsafe(limits.maxRecordBytes));
1167
+ yield* Effect.forEach(fields, (write) => write(writer), { discard: true });
1168
+ return yield* writer.finish;
1169
+ });
952
1170
  const baseSupportedAttributes = [
953
1171
  0,
954
1172
  1,
@@ -986,10 +1204,7 @@ const baseSupportedAttributes = [
986
1204
  ];
987
1205
  const maxUint64 = 0xffffffffffffffffn;
988
1206
  const supportedAttributesFor = (export_) => {
989
- const capacity = export_.capacity;
990
- if (capacity === undefined)
991
- return baseSupportedAttributes;
992
- const { maxBytes, maxEntries } = capacity.limits;
1207
+ const { maxBytes, maxEntries } = export_.capacity.limits;
993
1208
  const additional = [27];
994
1209
  if (maxEntries !== undefined)
995
1210
  additional.push(21, 22, 23);
@@ -1028,39 +1243,37 @@ const isValidName = (name, maxNameBytes) => {
1028
1243
  return false;
1029
1244
  }
1030
1245
  };
1031
- const encodeTime = (writer, nanoseconds) => {
1032
- let seconds = nanoseconds / 1000000000n;
1033
- let nanos = nanoseconds % 1000000000n;
1034
- if (nanos < 0) {
1035
- seconds -= 1n;
1036
- nanos += 1000000000n;
1037
- }
1246
+ const encodeTime = (writer, nanoseconds) => Effect.gen(function* () {
1247
+ const remainder = nanoseconds % 1000000000n;
1248
+ const seconds = nanoseconds / 1000000000n - (remainder < 0n ? 1n : 0n);
1249
+ const nanos = remainder < 0n ? remainder + 1000000000n : remainder;
1038
1250
  if (seconds < -0x8000000000000000n || seconds > 0x7fffffffffffffffn)
1039
1251
  return false;
1040
- writer.uint64(BigInt.asUintN(64, seconds)).uint32(Number(nanos));
1252
+ yield* writer.write(XdrCodec.uint64, BigInt.asUintN(64, seconds));
1253
+ yield* writer.write(XdrCodec.uint32, Number(nanos));
1041
1254
  return true;
1042
- };
1043
- const encodeAttributeValues = (requested, observation, filehandle, export_, options, supportedAttributes, usage) => {
1255
+ });
1256
+ const encodeAttributeValues = (requested, observation, filehandle, export_, options, supportedAttributes, usage) => Effect.gen(function* () {
1044
1257
  if (requested.some((attribute) => !supportedAttributes.includes(attribute)))
1045
1258
  return undefined;
1046
- const values = new Writer();
1259
+ const values = yield* xdr.openWriter(options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes));
1047
1260
  const metadata = observation.value;
1048
1261
  for (const attribute of requested) {
1049
1262
  switch (attribute) {
1050
1263
  case 0:
1051
- writeBitmap(values, wordsFor(supportedAttributes));
1264
+ yield* writeBitmap(values, wordsFor(supportedAttributes));
1052
1265
  break;
1053
1266
  case 1:
1054
- values.uint32(metadata.kind === "file" ? 1 : metadata.kind === "directory" ? 2 : 5);
1267
+ yield* values.write(XdrCodec.uint32, metadata.kind === "file" ? 1 : metadata.kind === "directory" ? 2 : 5);
1055
1268
  break;
1056
1269
  case 2:
1057
- values.uint32(0x3);
1270
+ yield* values.write(XdrCodec.uint32, export_.persistentHandles ? FH4_PERSISTENT : FH4_VOLATILE_UNTIL_RESTART);
1058
1271
  break;
1059
1272
  case 3:
1060
- values.uint64(BigInt.asUintN(64, observation.revision));
1273
+ yield* values.write(XdrCodec.uint64, BigInt.asUintN(64, observation.revision));
1061
1274
  break;
1062
1275
  case 4:
1063
- values.uint64(metadata.size);
1276
+ yield* values.write(XdrCodec.uint64, metadata.size);
1064
1277
  break;
1065
1278
  case 5:
1066
1279
  case 6:
@@ -1068,107 +1281,112 @@ const encodeAttributeValues = (requested, observation, filehandle, export_, opti
1068
1281
  case 17:
1069
1282
  case 26:
1070
1283
  case 34:
1071
- values.boolean(true);
1284
+ yield* values.write(XdrCodec.boolean, true);
1072
1285
  break;
1073
1286
  case 7:
1074
1287
  case 16:
1075
- values.boolean(false);
1288
+ yield* values.write(XdrCodec.boolean, false);
1076
1289
  break;
1077
1290
  case 51:
1078
- values.uint64(0n).uint32(1);
1291
+ yield* values.write(XdrCodec.uint64, 0n);
1292
+ yield* values.write(XdrCodec.uint32, 1);
1079
1293
  break;
1080
1294
  case 76:
1081
- values.uint32(FSCHARSET_CAP4_ALLOWS_ONLY_UTF8);
1295
+ yield* values.write(XdrCodec.uint32, FSCHARSET_CAP4_ALLOWS_ONLY_UTF8);
1082
1296
  break;
1083
1297
  case 8:
1084
- values.uint64(export_.fsid[0]).uint64(export_.fsid[1]);
1298
+ yield* values.write(XdrCodec.uint64, export_.fsid[0]);
1299
+ yield* values.write(XdrCodec.uint64, export_.fsid[1]);
1085
1300
  break;
1086
1301
  case 10:
1087
- values.uint32(options.leaseDurationSeconds);
1302
+ yield* values.write(XdrCodec.uint32, options.leaseDurationSeconds);
1088
1303
  break;
1089
1304
  case 11:
1090
- values.uint32(Status.OK);
1305
+ yield* values.write(XdrCodec.uint32, Status.OK);
1091
1306
  break;
1092
1307
  case 19:
1093
- values.opaque(filehandle);
1308
+ yield* values.write(XdrCodec.opaque(), filehandle);
1094
1309
  break;
1095
1310
  case 20:
1096
1311
  case 55:
1097
- values.uint64(BigInt.asUintN(64, metadata.ino));
1312
+ yield* values.write(XdrCodec.uint64, BigInt.asUintN(64, metadata.ino));
1098
1313
  break;
1099
1314
  case 21:
1100
1315
  case 22:
1101
1316
  case 23: {
1102
1317
  const total = BigInt(export_.capacity.limits.maxEntries);
1103
- values.uint64(attribute === 23 ? total : total - BigInt(usage.entries));
1318
+ yield* values.write(XdrCodec.uint64, attribute === 23 ? total : total - BigInt(usage.entries));
1104
1319
  break;
1105
1320
  }
1106
1321
  case 27:
1107
- values.uint64(ByteSize.toBigInt(export_.capacity.limits.maxFileBytes));
1322
+ yield* values.write(XdrCodec.uint64, ByteSize.toBigInt(export_.capacity.limits.maxFileBytes));
1108
1323
  break;
1109
1324
  case 29:
1110
- values.uint32(ByteSize.toNumberUnsafe(options.limits.maxNameBytes));
1325
+ yield* values.write(XdrCodec.uint32, ByteSize.toNumberUnsafe(options.limits.maxNameBytes));
1111
1326
  break;
1112
1327
  case 30:
1113
- values.uint64(options.limits.maxReadBytes);
1328
+ yield* values.write(XdrCodec.uint64, options.limits.maxReadBytes);
1114
1329
  break;
1115
1330
  case 31:
1116
- values.uint64(options.limits.maxWriteBytes);
1331
+ yield* values.write(XdrCodec.uint64, options.limits.maxWriteBytes);
1117
1332
  break;
1118
1333
  case 33:
1119
- values.uint32(metadata.mode);
1334
+ yield* values.write(XdrCodec.uint32, metadata.mode);
1120
1335
  break;
1121
1336
  case 35:
1122
- values.uint32(metadata.nlink);
1337
+ yield* values.write(XdrCodec.uint32, metadata.nlink);
1123
1338
  break;
1124
1339
  case 36:
1125
- values.string(String(metadata.uid));
1340
+ yield* values.write(XdrCodec.string(), String(metadata.uid));
1126
1341
  break;
1127
1342
  case 37:
1128
- values.string(String(metadata.gid));
1343
+ yield* values.write(XdrCodec.string(), String(metadata.gid));
1129
1344
  break;
1130
1345
  case 42:
1131
1346
  case 43:
1132
1347
  case 44: {
1133
1348
  const total = ByteSize.toBigInt(export_.capacity.limits.maxBytes);
1134
- values.uint64(attribute === 44 ? total : total - usage.usedBytes);
1349
+ yield* values.write(XdrCodec.uint64, attribute === 44 ? total : total - usage.usedBytes);
1135
1350
  break;
1136
1351
  }
1137
1352
  case 45:
1138
- values.uint64(metadata.size);
1353
+ yield* values.write(XdrCodec.uint64, metadata.size);
1139
1354
  break;
1140
1355
  case 47:
1141
- if (!encodeTime(values, metadata.atimeNs))
1356
+ if (!(yield* encodeTime(values, metadata.atimeNs)))
1142
1357
  return undefined;
1143
1358
  break;
1144
1359
  case 52:
1145
- if (!encodeTime(values, metadata.ctimeNs))
1360
+ if (!(yield* encodeTime(values, metadata.ctimeNs)))
1146
1361
  return undefined;
1147
1362
  break;
1148
1363
  case 53:
1149
- if (!encodeTime(values, metadata.mtimeNs))
1364
+ if (!(yield* encodeTime(values, metadata.mtimeNs)))
1150
1365
  return undefined;
1151
1366
  break;
1152
1367
  case 75:
1153
- writeBitmap(values, options.writable ? wordsFor([4, 33, 36, 37]) : []);
1368
+ yield* writeBitmap(values, options.writable ? wordsFor([4, 33, 36, 37]) : []);
1154
1369
  break;
1155
1370
  }
1156
1371
  }
1157
- return values.bytes();
1158
- };
1159
- const encodeAttributes = (requested, observation, filehandle, export_, options, supportedAttributes, usage) => {
1160
- const values = encodeAttributeValues(requested, observation, filehandle, export_, options, supportedAttributes, usage);
1372
+ return yield* values.finish;
1373
+ });
1374
+ const encodeAttributes = (requested, observation, filehandle, export_, options, supportedAttributes, usage) => Effect.gen(function* () {
1375
+ const values = yield* encodeAttributeValues(requested, observation, filehandle, export_, options, supportedAttributes, usage);
1161
1376
  if (values === undefined)
1162
1377
  return undefined;
1163
- return encodeStatusBody((writer) => {
1164
- writeBitmap(writer, wordsFor(requested));
1165
- writer.opaque(values);
1166
- });
1167
- };
1378
+ return yield* encodeStatusBody(options.limits, [
1379
+ (writer) => writeBitmap(writer, wordsFor(requested)),
1380
+ field(XdrCodec.opaque(), values)
1381
+ ]);
1382
+ });
1168
1383
  /** Encodes a READDIR entry's attributes as only `rdattr_error` (RFC 8881 Section 18.23.3). */
1169
- const encodeReaddirError = (status) => encodeStatusBody((writer) => {
1170
- writeBitmap(writer, wordsFor([11]));
1171
- writer.opaque(new Writer().uint32(status).bytes());
1384
+ const encodeReaddirError = (status, limits) => Effect.gen(function* () {
1385
+ const error = yield* xdr.encode(status, XdrCodec.uint32, limits, ByteSize.toNumberUnsafe(limits.maxRecordBytes));
1386
+ return yield* encodeStatusBody(limits, [
1387
+ (writer) => writeBitmap(writer, wordsFor([11])),
1388
+ field(XdrCodec.opaque(), error)
1389
+ ]);
1172
1390
  });
1173
1391
  const supportedAccessMask = (kind) => {
1174
1392
  switch (kind) {
@@ -1223,30 +1441,40 @@ const grantedAccess = (supported, metadata, credentials) => {
1223
1441
  * The credential is the one the client authorized in csa_sec_parms (Section 18.36.3), never a
1224
1442
  * flavor it did not offer.
1225
1443
  */
1226
- const encodeCallbackCall = (xid, program, procedure, security, body) => {
1227
- const header = new Writer()
1228
- .uint32(xid).uint32(0).uint32(2)
1229
- .uint32(program).uint32(CALLBACK_RPC_VERSION).uint32(procedure)
1230
- .uint32(security.flavor).opaque(security.credential ?? empty)
1231
- .uint32(0).opaque(empty)
1232
- .bytes();
1233
- const message = new Uint8Array(header.length + body.length);
1234
- message.set(header);
1235
- message.set(body, header.length);
1236
- return message;
1237
- };
1444
+ const encodeCallbackCall = (xid, program, procedure, security, body, limits) => Effect.gen(function* () {
1445
+ const writer = yield* xdr.openWriter(limits, ByteSize.toNumberUnsafe(limits.maxRecordBytes));
1446
+ yield* writer.write(XdrCodec.uint32, xid);
1447
+ yield* writer.write(XdrCodec.uint32, 0);
1448
+ yield* writer.write(XdrCodec.uint32, 2);
1449
+ yield* writer.write(XdrCodec.uint32, program);
1450
+ yield* writer.write(XdrCodec.uint32, CALLBACK_RPC_VERSION);
1451
+ yield* writer.write(XdrCodec.uint32, procedure);
1452
+ yield* writer.write(XdrCodec.uint32, security.flavor);
1453
+ yield* writer.write(XdrCodec.opaque(ByteSize.bytes(MAX_OPAQUE_AUTH_BYTES)), security.credential ?? empty);
1454
+ yield* writer.write(XdrCodec.uint32, 0);
1455
+ yield* writer.write(XdrCodec.opaque(ByteSize.bytes(MAX_OPAQUE_AUTH_BYTES)), empty);
1456
+ yield* writer.appendEncoded(body);
1457
+ return yield* writer.finish;
1458
+ });
1238
1459
  /**
1239
1460
  * A CB_COMPOUND carrying CB_SEQUENCE alone. Section 20.9.3 requires CB_SEQUENCE to appear once and
1240
1461
  * first in every CB_COMPOUND, and erratum 6015 makes it REQUIRED rather than the OPTIONAL that
1241
1462
  * Table 17 prints. With no delegations or layouts to recall, this is the whole callback: it
1242
1463
  * exercises the backchannel and renews nothing else.
1243
1464
  */
1244
- const encodeCallbackSequence = (session, sequence, slot, highestSlot) => new Writer()
1245
- .string("probe").uint32(1).uint32(0).uint32(1)
1246
- .uint32(OP_CB_SEQUENCE)
1247
- .fixedOpaque(session).uint32(sequence).uint32(slot).uint32(highestSlot).boolean(false)
1248
- .array([], () => undefined)
1249
- .bytes();
1465
+ const encodeCallbackSequence = (session, sequence, slot, highestSlot, limits) => encodeStatusBody(limits, [
1466
+ field(XdrCodec.string(), "probe"),
1467
+ field(XdrCodec.uint32, 1),
1468
+ field(XdrCodec.uint32, 0),
1469
+ field(XdrCodec.uint32, 1),
1470
+ field(XdrCodec.uint32, OP_CB_SEQUENCE),
1471
+ field(XdrCodec.fixedOpaque(16), session),
1472
+ field(XdrCodec.uint32, sequence),
1473
+ field(XdrCodec.uint32, slot),
1474
+ field(XdrCodec.uint32, highestSlot),
1475
+ field(XdrCodec.boolean, false),
1476
+ field(XdrCodec.array(XdrCodec.uint32), [])
1477
+ ]);
1250
1478
  /**
1251
1479
  * Decides whether a callback reply actually says the client handled the callback. An RPC REPLY is
1252
1480
  * not success on its own: the client's RPC layer answers PROG_UNAVAIL for a program it does not
@@ -1254,49 +1482,42 @@ const encodeCallbackSequence = (session, sequence, slot, highestSlot) => new Wri
1254
1482
  * from a client with no working callback path. The CB_SEQUENCE result is checked too, because
1255
1483
  * Section 20.9.3 lets the client reject the slot or sequence it was given.
1256
1484
  */
1257
- const callbackAccepted = (reply, limits, session, slot, sequence) => {
1258
- try {
1259
- const reader = new Reader(reply, limits);
1260
- reader.uint32();
1261
- // RPC: REPLY, MSG_ACCEPTED, verifier, then SUCCESS.
1262
- if (reader.uint32() !== 1)
1263
- return false;
1264
- if (reader.uint32() !== 0)
1265
- return false;
1266
- reader.uint32();
1267
- reader.opaque(ByteSize.bytes(MAX_OPAQUE_AUTH_BYTES));
1268
- if (reader.uint32() !== 0)
1269
- return false;
1270
- // CB_COMPOUND: an all-OK status, then CB_SEQUENCE first (Section 20.9.3).
1271
- if (reader.uint32() !== Status.OK)
1272
- return false;
1273
- reader.string(limits.maxStringBytes);
1274
- // Exactly one result: this server sends a CB_SEQUENCE-only CB_COMPOUND, so anything else is
1275
- // not an answer to what it asked.
1276
- if (reader.uint32() !== 1)
1277
- return false;
1278
- if (reader.uint32() !== OP_CB_SEQUENCE)
1279
- return false;
1280
- if (reader.uint32() !== Status.OK)
1281
- return false;
1282
- // The client echoes what it was given; anything else means it answered a different callback.
1283
- const echoed = bytesKey(reader.fixedOpaque(16)) === bytesKey(session) &&
1284
- reader.uint32() === sequence &&
1285
- reader.uint32() === slot;
1286
- // csr_highest_slotid and csr_target_highest_slotid are mandatory, and nothing may follow the
1287
- // one result. Reading them out and finishing rejects a truncated or padded reply, which would
1288
- // otherwise pass as a working callback path.
1289
- reader.uint32();
1290
- reader.uint32();
1291
- reader.finish();
1292
- return echoed;
1293
- }
1294
- catch (error) {
1295
- if (error instanceof XdrDecodeError)
1296
- return false;
1297
- throw error;
1298
- }
1299
- };
1485
+ const callbackAccepted = (reply, limits, session, slot, sequence) => Effect.gen(function* () {
1486
+ const reader = yield* xdr.openReader(reply, limits);
1487
+ yield* reader.read(XdrCodec.uint32);
1488
+ // RPC: REPLY, MSG_ACCEPTED, verifier, then SUCCESS.
1489
+ if ((yield* reader.read(XdrCodec.uint32)) !== 1)
1490
+ return false;
1491
+ if ((yield* reader.read(XdrCodec.uint32)) !== 0)
1492
+ return false;
1493
+ yield* reader.read(XdrCodec.uint32);
1494
+ yield* reader.read(XdrCodec.opaque(ByteSize.bytes(MAX_OPAQUE_AUTH_BYTES)));
1495
+ if ((yield* reader.read(XdrCodec.uint32)) !== 0)
1496
+ return false;
1497
+ // CB_COMPOUND: an all-OK status, then CB_SEQUENCE first (Section 20.9.3).
1498
+ if ((yield* reader.read(XdrCodec.uint32)) !== Status.OK)
1499
+ return false;
1500
+ yield* reader.read(XdrCodec.string(limits.maxStringBytes));
1501
+ // Exactly one result: this server sends a CB_SEQUENCE-only CB_COMPOUND, so anything else is
1502
+ // not an answer to what it asked.
1503
+ if ((yield* reader.read(XdrCodec.uint32)) !== 1)
1504
+ return false;
1505
+ if ((yield* reader.read(XdrCodec.uint32)) !== OP_CB_SEQUENCE)
1506
+ return false;
1507
+ if ((yield* reader.read(XdrCodec.uint32)) !== Status.OK)
1508
+ return false;
1509
+ // The client echoes what it was given; anything else means it answered a different callback.
1510
+ const echoed = bytesKey(yield* reader.read(XdrCodec.fixedOpaque(16))) === bytesKey(session) &&
1511
+ (yield* reader.read(XdrCodec.uint32)) === sequence &&
1512
+ (yield* reader.read(XdrCodec.uint32)) === slot;
1513
+ // csr_highest_slotid and csr_target_highest_slotid are mandatory, and nothing may follow the
1514
+ // one result. Reading them out and finishing rejects a truncated or padded reply, which would
1515
+ // otherwise pass as a working callback path.
1516
+ yield* reader.read(XdrCodec.uint32);
1517
+ yield* reader.read(XdrCodec.uint32);
1518
+ yield* reader.finish;
1519
+ return echoed;
1520
+ }).pipe(Effect.catchTag("XdrDecodeError", () => Effect.succeed(false)));
1300
1521
  const makeOpaqueId = (generation, serial) => {
1301
1522
  const result = new Uint8Array(16);
1302
1523
  result.set(generation.subarray(0, 8), 0);
@@ -1323,7 +1544,7 @@ const makeCookieVerifier = (generation, revision) => {
1323
1544
  };
1324
1545
  /**
1325
1546
  * Operations that change server state before the reply size is known. READ belongs here
1326
- * because reading updates the file's access time, which a slot rollback cannot undo.
1547
+ * because reading can update the file's access time, which a slot rollback cannot undo.
1327
1548
  */
1328
1549
  const stateChangingKinds = new Set([
1329
1550
  "Read",
@@ -1447,6 +1668,7 @@ export const makeNfs4Handler = (export_, options) => {
1447
1668
  assertOptions(options);
1448
1669
  const storageGeneration = options.storageGeneration ?? options.generation;
1449
1670
  const supportedAttributes = supportedAttributesFor(export_);
1671
+ const encodeBody = (value, codec) => xdr.encode(value, codec, options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes));
1450
1672
  const sampleUsage = (requested) => requested.some((attribute) => capacityAttributes.has(attribute))
1451
1673
  ? export_.capacity.usage
1452
1674
  : Effect.succeed(null);
@@ -1479,17 +1701,13 @@ export const makeNfs4Handler = (export_, options) => {
1479
1701
  }
1480
1702
  return undefined;
1481
1703
  };
1482
- const deniedLock = (code, conflict) => ({
1483
- code,
1484
- status: Status.DENIED,
1485
- body: new Writer()
1486
- .uint64(conflict.entry.range.offset)
1487
- .uint64(conflict.entry.range.length)
1488
- .uint32(conflict.entry.type)
1489
- .uint64(conflict.state.client.id)
1490
- .opaque(conflict.state.owner)
1491
- .bytes()
1492
- });
1704
+ const deniedLock = (code, conflict) => Effect.map(encodeStatusBody(options.limits, [
1705
+ field(XdrCodec.uint64, conflict.entry.range.offset),
1706
+ field(XdrCodec.uint64, conflict.entry.range.length),
1707
+ field(XdrCodec.uint32, conflict.entry.type),
1708
+ field(XdrCodec.uint64, conflict.state.client.id),
1709
+ field(XdrCodec.opaque(), conflict.state.owner)
1710
+ ]), (body) => ({ code, status: Status.DENIED, body }));
1493
1711
  let replayBytes = ByteSize.bytes(0);
1494
1712
  const maxRpcRequestBytes = ByteSize.min(options.limits.maxRecordBytes, options.limits.maxCompoundBytes);
1495
1713
  const maxRpcResponseBytes = ByteSize.min(options.limits.maxRecordBytes, options.limits.maxCompoundBytes);
@@ -1526,9 +1744,9 @@ export const makeNfs4Handler = (export_, options) => {
1526
1744
  // ca_maxrequestsize bounds the whole RPC call the client will accept, not just its
1527
1745
  // CB_COMPOUND body, so the framed message is what gets measured. The xid does not change
1528
1746
  // the size, so any value serves for the measurement.
1529
- if (encodeCallbackCall(0, back.program, procedure, security, body).length > back.attrs.maxRequest) {
1747
+ const measured = yield* Effect.result(encodeCallbackCall(0, back.program, procedure, security, body, options.limits));
1748
+ if (Result.isFailure(measured) || measured.success.length > back.attrs.maxRequest)
1530
1749
  return false;
1531
- }
1532
1750
  // A carrier that fails outright must not burn the whole deadline when it is the only one,
1533
1751
  // so the race also ends as soon as every carrier has definitively failed.
1534
1752
  let failed = 0;
@@ -1546,7 +1764,12 @@ export const makeNfs4Handler = (export_, options) => {
1546
1764
  const reply = yield* Deferred.make();
1547
1765
  pendingCallbacks.set(xid, { carrier, reply });
1548
1766
  return yield* Effect.ensuring(Effect.gen(function* () {
1549
- const sent = yield* carrier.send(encodeCallbackCall(xid, back.program, procedure, security, body));
1767
+ const encoded = yield* Effect.result(encodeCallbackCall(xid, back.program, procedure, security, body, options.limits));
1768
+ if (Result.isFailure(encoded)) {
1769
+ yield* noteFailure;
1770
+ return yield* Effect.never;
1771
+ }
1772
+ const sent = yield* carrier.send(encoded.success);
1550
1773
  // A carrier that cannot be written to, or whose client rejects the callback, loses
1551
1774
  // the race instead of ending it. The outer deadline bounds the wait when every
1552
1775
  // carrier does so.
@@ -1555,7 +1778,7 @@ export const makeNfs4Handler = (export_, options) => {
1555
1778
  return yield* Effect.never;
1556
1779
  }
1557
1780
  const answered = yield* Deferred.await(reply);
1558
- if (accepted(answered))
1781
+ if (yield* accepted(answered))
1559
1782
  return true;
1560
1783
  yield* noteFailure;
1561
1784
  return yield* Effect.never;
@@ -1625,25 +1848,21 @@ export const makeNfs4Handler = (export_, options) => {
1625
1848
  Effect.repeat(stateGate.withPermit(Effect.uninterruptible(sweepExpired)), {
1626
1849
  schedule: Schedule.spaced(sweepInterval)
1627
1850
  }), handlerScope);
1851
+ // The export forks each open's scope from the handler scope, so closing the handler scope closes them too.
1852
+ // The handler still closes what `opens` holds through each open's own close, since that close is all the
1853
+ // export contract promises; on the built-in export the second close finds a closed scope and does nothing.
1628
1854
  yield* Effect.addFinalizer(() => Effect.forEach(opens.values(), (open) => open.close, { discard: true }));
1629
1855
  /** Reads only the leading SEQUENCE of a compound to find its session, tolerating later decode errors. */
1630
- const sequenceSessionOf = (bytes) => {
1631
- try {
1632
- const reader = new Reader(bytes, options.limits);
1633
- reader.opaque(options.limits.maxStringBytes);
1634
- const minor = reader.uint32();
1635
- const operationCount = reader.uint32();
1636
- if (minor !== 1 || reader.uint32() !== Operation.SEQUENCE)
1637
- return undefined;
1638
- const session = sessions.get(bytesKey(reader.fixedOpaque(16)));
1639
- return session === undefined ? undefined : { session, operationCount };
1640
- }
1641
- catch (error) {
1642
- if (error instanceof XdrDecodeError)
1643
- return undefined;
1644
- throw error;
1645
- }
1646
- };
1856
+ const sequenceSessionOf = (bytes) => Effect.gen(function* () {
1857
+ const reader = yield* xdr.openReader(bytes, options.limits);
1858
+ yield* reader.read(XdrCodec.opaque(options.limits.maxStringBytes));
1859
+ const minor = yield* reader.read(XdrCodec.uint32);
1860
+ const operationCount = yield* reader.read(XdrCodec.uint32);
1861
+ if (minor !== 1 || (yield* reader.read(XdrCodec.uint32)) !== Operation.SEQUENCE)
1862
+ return undefined;
1863
+ const session = sessions.get(bytesKey(yield* reader.read(XdrCodec.fixedOpaque(16))));
1864
+ return session === undefined ? undefined : { session, operationCount };
1865
+ }).pipe(Effect.catchTag("XdrDecodeError", () => Effect.as(Effect.void, undefined)));
1647
1866
  /**
1648
1867
  * `restore` reopens the compound's own interrupt window. The caller runs the whole compound
1649
1868
  * uninterruptibly so the replay-slot commit below cannot be torn in half, but an operation
@@ -1653,38 +1872,33 @@ export const makeNfs4Handler = (export_, options) => {
1653
1872
  * interrupt arriving between them rolls the slot back via `rollbackSequence` so nothing stays
1654
1873
  * charged for a reply that was never sent.
1655
1874
  */
1656
- const executeCompound = (call, export_, activeCaller, restore) => Effect.suspend(() => {
1657
- let parsed;
1658
- try {
1659
- parsed = parseCompound(call.arguments, options.limits);
1660
- }
1661
- catch (error) {
1662
- if (!(error instanceof XdrDecodeError))
1663
- throw error;
1664
- const tag = (() => {
1665
- try {
1666
- return new Reader(call.arguments, options.limits).opaque(options.limits.maxStringBytes);
1875
+ const executeCompound = (call, export_, activeCaller, restore) => Effect.flatMap(Effect.result(parseCompound(call.arguments, options.limits)), (parsedResult) => {
1876
+ if (Result.isFailure(parsedResult)) {
1877
+ return Effect.gen(function* () {
1878
+ const tagResult = yield* Effect.result(xdr.openReader(call.arguments, options.limits).pipe(Effect.flatMap((reader) => reader.read(XdrCodec.opaque(options.limits.maxStringBytes)))));
1879
+ const tag = Result.isFailure(tagResult) ? empty : tagResult.success;
1880
+ // Section 2.10.6.4: an oversized request is reported as such even when later
1881
+ // operations fail to decode.
1882
+ const oversized = yield* sequenceSessionOf(call.arguments);
1883
+ if (oversized !== undefined &&
1884
+ (call.requestBytes ?? call.arguments.length) > oversized.session.fore.maxRequest) {
1885
+ return yield* encodeCompound(options.limits, tag, [{
1886
+ code: Operation.SEQUENCE,
1887
+ status: Status.REQ_TOO_BIG
1888
+ }]);
1667
1889
  }
1668
- catch (tagError) {
1669
- if (!(tagError instanceof XdrDecodeError))
1670
- throw tagError;
1671
- return empty;
1890
+ if (oversized !== undefined && oversized.operationCount > oversized.session.fore.maxOperations) {
1891
+ return yield* encodeCompound(options.limits, tag, [{
1892
+ code: Operation.SEQUENCE,
1893
+ status: Status.TOO_MANY_OPS
1894
+ }]);
1672
1895
  }
1673
- })();
1674
- // Section 2.10.6.4: an oversized request is reported as such even when later
1675
- // operations fail to decode.
1676
- const oversized = sequenceSessionOf(call.arguments);
1677
- if (oversized !== undefined &&
1678
- (call.requestBytes ?? call.arguments.length) > oversized.session.fore.maxRequest) {
1679
- return Effect.succeed(encodeCompound(tag, [{ code: Operation.SEQUENCE, status: Status.REQ_TOO_BIG }]));
1680
- }
1681
- if (oversized !== undefined && oversized.operationCount > oversized.session.fore.maxOperations) {
1682
- return Effect.succeed(encodeCompound(tag, [{ code: Operation.SEQUENCE, status: Status.TOO_MANY_OPS }]));
1683
- }
1684
- return Effect.succeed(encodeCompound(tag, [], Status.BADXDR));
1896
+ return yield* encodeCompound(options.limits, tag, [], Status.BADXDR);
1897
+ });
1685
1898
  }
1899
+ const parsed = parsedResult.success;
1686
1900
  if (parsed.minor !== 1) {
1687
- return Effect.succeed(encodeCompound(parsed.tag, [], Status.MINOR_VERS_MISMATCH));
1901
+ return encodeCompound(options.limits, parsed.tag, [], Status.MINOR_VERS_MISMATCH);
1688
1902
  }
1689
1903
  const first = parsed.operations[0];
1690
1904
  const firstCode = first?.code;
@@ -1697,20 +1911,23 @@ export const makeNfs4Handler = (export_, options) => {
1697
1911
  // Sections 15.2 and 18.52: an illegal opcode answers as OP_ILLEGAL whether or not a
1698
1912
  // session exists, and arguments are decoded before any session check.
1699
1913
  if (first.kind === "Unknown") {
1700
- return Effect.succeed(encodeCompound(parsed.tag, [{ code: Operation.ILLEGAL, status: Status.OP_ILLEGAL }]));
1914
+ return encodeCompound(options.limits, parsed.tag, [{
1915
+ code: Operation.ILLEGAL,
1916
+ status: Status.OP_ILLEGAL
1917
+ }]);
1701
1918
  }
1702
1919
  if (first.kind === "Malformed") {
1703
- return Effect.succeed(encodeCompound(parsed.tag, [{ code: first.code, status: Status.BADXDR }]));
1920
+ return encodeCompound(options.limits, parsed.tag, [{ code: first.code, status: Status.BADXDR }]);
1704
1921
  }
1705
1922
  // Sections 18.34.3, 18.35.3, 18.36.3, 18.37.3, and 18.50.3: these MUST be the only operation.
1706
1923
  if (isBootstrap) {
1707
- return Effect.succeed(encodeCompound(parsed.tag, [{ code: firstCode, status: Status.NOT_ONLY_OP }]));
1924
+ return encodeCompound(options.limits, parsed.tag, [{ code: firstCode, status: Status.NOT_ONLY_OP }]);
1708
1925
  }
1709
1926
  // Section 15.2 allows only NFS4ERR_NOTSUPP for the NFSv4.0 operations.
1710
1927
  if (mustNotImplementOperations.has(firstCode)) {
1711
- return Effect.succeed(encodeCompound(parsed.tag, [{ code: firstCode, status: Status.NOTSUPP }]));
1928
+ return encodeCompound(options.limits, parsed.tag, [{ code: firstCode, status: Status.NOTSUPP }]);
1712
1929
  }
1713
- return Effect.succeed(encodeCompound(parsed.tag, [{ code: firstCode, status: Status.OP_NOT_IN_SESSION }]));
1930
+ return encodeCompound(options.limits, parsed.tag, [{ code: firstCode, status: Status.OP_NOT_IN_SESSION }]);
1714
1931
  }
1715
1932
  if (first?.kind === "Sequence") {
1716
1933
  const value = first.value;
@@ -1722,7 +1939,10 @@ export const makeNfs4Handler = (export_, options) => {
1722
1939
  // so it happens before the retry is judged: even a false retry was transmitted here.
1723
1940
  associate(session, call.connection, CHANNEL_FORE);
1724
1941
  if (!sameRequest(slot.request, call.arguments) || slot.credentials !== credentialsKey(call.credentials)) {
1725
- return Effect.succeed(encodeCompound(parsed.tag, [{ code: Operation.SEQUENCE, status: Status.SEQ_FALSE_RETRY }]));
1942
+ return encodeCompound(options.limits, parsed.tag, [{
1943
+ code: Operation.SEQUENCE,
1944
+ status: Status.SEQ_FALSE_RETRY
1945
+ }]);
1726
1946
  }
1727
1947
  // A policy may remap the same wire credential between attempts. Never replay a
1728
1948
  // response computed under a caller that no longer has this request's authority.
@@ -1750,25 +1970,28 @@ export const makeNfs4Handler = (export_, options) => {
1750
1970
  rollbackSequence?.();
1751
1971
  }
1752
1972
  rollbackSequence = undefined;
1753
- return encodeCompound(parsed.tag, [{ code: Operation.SEQUENCE, status }]);
1973
+ return encodeCompound(options.limits, parsed.tag, [{ code: Operation.SEQUENCE, status }]);
1754
1974
  };
1755
1975
  for (let index = 0; index < parsed.operations.length; index++) {
1756
1976
  const operation = parsed.operations[index];
1757
1977
  let result;
1758
1978
  // Operations remain interruptible while waiting on the export. Their own commit
1759
1979
  // boundaries protect state changes; the consumed slot prevents rerunning them.
1760
- result = yield* restore(execute(operation));
1980
+ result = yield* restore(execute(operation)).pipe(Effect.catchTag("XdrEncodeError", (error) => Effect.succeed({
1981
+ code: operation.code,
1982
+ status: error.reason === "output-limit" ? Status.REP_TOO_BIG : Status.SERVERFAULT
1983
+ })));
1761
1984
  parts.push(result);
1762
1985
  if (index === 0 && mayChangeState && activeSlot !== undefined && result.status === Status.OK) {
1763
1986
  // Publish a consumed-slot marker before any later operation can commit. An
1764
1987
  // interrupted or failed operation can leave this marker instead of its full reply.
1765
1988
  const second = parsed.operations[1];
1766
- activeSlot.response = second === undefined
1767
- ? encodeCompound(parsed.tag, [result])
1768
- : encodeCompound(parsed.tag, [
1989
+ activeSlot.response = yield* (second === undefined
1990
+ ? encodeCompound(options.limits, parsed.tag, [result])
1991
+ : encodeCompound(options.limits, parsed.tag, [
1769
1992
  result,
1770
1993
  { code: second.code, status: Status.RETRY_UNCACHED_REP }
1771
- ]);
1994
+ ]));
1772
1995
  activeSlot.request = new Uint8Array(call.arguments);
1773
1996
  activeSlot.credentials = credentialsKey(call.credentials);
1774
1997
  if (activeCaller === undefined)
@@ -1780,20 +2003,27 @@ export const makeNfs4Handler = (export_, options) => {
1780
2003
  if (result.status !== Status.OK)
1781
2004
  break;
1782
2005
  }
1783
- const response = encodeCompound(parsed.tag, parts);
2006
+ const encodedResponse = yield* Effect.result(encodeCompound(options.limits, parsed.tag, parts));
2007
+ if (Result.isFailure(encodedResponse)) {
2008
+ if (encodedResponse.failure.reason === "output-limit") {
2009
+ return yield* rejectAfterExecution(Status.REP_TOO_BIG);
2010
+ }
2011
+ return yield* encodedResponse.failure;
2012
+ }
2013
+ const response = encodedResponse.success;
1784
2014
  const responseBytes = addBytes(byteLength(response.length), rpcReplyOverheadBytes);
1785
2015
  if (responseBytes > byteLength(activeSession?.fore.maxResponse ?? Number.MAX_SAFE_INTEGER)) {
1786
- return rejectAfterExecution(Status.REP_TOO_BIG);
2016
+ return yield* rejectAfterExecution(Status.REP_TOO_BIG);
1787
2017
  }
1788
2018
  if (shouldCache &&
1789
2019
  responseBytes > byteLength(activeSession?.fore.maxCachedResponse ?? Number.MAX_SAFE_INTEGER)) {
1790
- return rejectAfterExecution(Status.REP_TOO_BIG_TO_CACHE);
2020
+ return yield* rejectAfterExecution(Status.REP_TOO_BIG_TO_CACHE);
1791
2021
  }
1792
2022
  if (activeSlot !== undefined && shouldCache) {
1793
2023
  const retainedBytes = addBytes(byteLength(call.arguments.length), byteLength(response.length));
1794
2024
  if (retainedBytes > options.limits.maxReplayBytes ||
1795
2025
  addBytes(subtractBytes(replayBytes, activeSlot.retainedBytes ?? ByteSize.bytes(0)), retainedBytes) > options.limits.maxReplayBytes) {
1796
- return rejectAfterExecution(Status.REP_TOO_BIG_TO_CACHE);
2026
+ return yield* rejectAfterExecution(Status.REP_TOO_BIG_TO_CACHE);
1797
2027
  }
1798
2028
  replayBytes = subtractBytes(replayBytes, activeSlot.retainedBytes ?? ByteSize.bytes(0));
1799
2029
  activeSlot.response = new Uint8Array(response);
@@ -1809,15 +2039,15 @@ export const makeNfs4Handler = (export_, options) => {
1809
2039
  else if (activeSlot !== undefined) {
1810
2040
  const sequencePart = parts[0];
1811
2041
  const second = parsed.operations[1];
1812
- const replay = second === undefined
1813
- ? encodeCompound(parsed.tag, [sequencePart])
1814
- : encodeCompound(parsed.tag, [
2042
+ const replay = yield* (second === undefined
2043
+ ? encodeCompound(options.limits, parsed.tag, [sequencePart])
2044
+ : encodeCompound(options.limits, parsed.tag, [
1815
2045
  sequencePart,
1816
2046
  { code: second.code, status: Status.RETRY_UNCACHED_REP }
1817
- ]);
2047
+ ]));
1818
2048
  const retainedBytes = addBytes(byteLength(call.arguments.length), byteLength(replay.length));
1819
2049
  if (addBytes(subtractBytes(replayBytes, activeSlot.retainedBytes ?? ByteSize.bytes(0)), retainedBytes) > options.limits.maxReplayBytes) {
1820
- return rejectAfterExecution(Status.DELAY);
2050
+ return yield* rejectAfterExecution(Status.DELAY);
1821
2051
  }
1822
2052
  replayBytes = subtractBytes(replayBytes, activeSlot.retainedBytes ?? ByteSize.bytes(0));
1823
2053
  activeSlot.response = replay;
@@ -1834,27 +2064,30 @@ export const makeNfs4Handler = (export_, options) => {
1834
2064
  return response;
1835
2065
  function execute(operation) {
1836
2066
  const noCurrent = () => ({ code: operation.code, status: Status.NOFILEHANDLE });
1837
- const mapFs = (effect) => effect.pipe(Effect.mapError(failureForFs));
2067
+ const mapFs = (effect) => effect.pipe(Effect.mapError((error) => failureForFs(error, operation.code)));
2068
+ // Fails as ACCESS unless every requested bit is granted.
2069
+ const requireAccess = (reference, bits) => mapFs(export_.access(reference, bits)).pipe(Effect.flatMap((granted) => granted === bits ? Effect.void : Effect.fail(Status.ACCESS)));
1838
2070
  const withCurrent = (f) => current === undefined ? Effect.fail(Status.NOFILEHANDLE) : f(current);
1839
- const statusResult = (effect, success = () => undefined) => effect.pipe(Effect.map((value) => {
1840
- const body = success(value);
1841
- return body === undefined
2071
+ const statusResult = (effect, success = () => undefined) => Effect.flatMap(Effect.result(effect), (outcome) => {
2072
+ if (Result.isFailure(outcome)) {
2073
+ return outcome.failure instanceof XdrEncodeError
2074
+ ? Effect.fail(outcome.failure)
2075
+ : Effect.succeed({ code: operation.code, status: outcome.failure });
2076
+ }
2077
+ const body = success(outcome.success);
2078
+ return Effect.map(Effect.isEffect(body) ? body : Effect.succeed(body), (encoded) => encoded === undefined
1842
2079
  ? { code: operation.code, status: Status.OK }
1843
- : { code: operation.code, status: Status.OK, body };
1844
- }), Effect.catch((status) => Effect.succeed({ code: operation.code, status })));
1845
- const requireAttributes = (attributes) => attributes === undefined ? Effect.fail(Status.SERVERFAULT) : Effect.succeed(attributes);
1846
- /** Registers a filehandle only when the `filehandle` attribute (19) is requested. */
1847
- const filehandleFor = (reference, requested) => requested.includes(19)
1848
- ? export_.handleFor(reference).pipe(Effect.mapError(() => Status.SERVERFAULT))
1849
- : Effect.succeed(empty);
2080
+ : { code: operation.code, status: Status.OK, body: encoded });
2081
+ });
2082
+ const requireAttributes = (attributes) => Effect.filterOrFail(attributes, (value) => value !== undefined, () => Status.SERVERFAULT);
2083
+ /** Encodes a filehandle only when the `filehandle` attribute (19) is requested. */
2084
+ const filehandleFor = (reference, requested) => requested.includes(19) ? mapFs(export_.handleFor(reference)) : Effect.succeed(empty);
1850
2085
  /**
1851
2086
  * Requires a directory. Only operations whose Section 15.2 error list includes
1852
2087
  * NFS4ERR_SYMLINK may report a symbolic link as such; the others say NOTDIR.
1853
2088
  */
1854
- const requireDirectory = (reference, symlinkStatus) => mapFs(export_.observeMetadata(reference)).pipe(Effect.flatMap((observation) => observation.value.kind === "directory"
1855
- ? Effect.void
1856
- : Effect.fail(observation.value.kind === "symlink" ? symlinkStatus : Status.NOTDIR)));
1857
- const parentOfDirectory = (reference, symlinkStatus) => requireDirectory(reference, symlinkStatus).pipe(Effect.flatMap(() => parentOf(reference)));
2089
+ const requireDirectory = (reference, symlinkStatus) => mapFs(export_.observeMetadata(reference)).pipe(Effect.filterOrFail((observation) => observation.value.kind === "directory", (observation) => observation.value.kind === "symlink" ? symlinkStatus : Status.NOTDIR), Effect.asVoid);
2090
+ const parentOfDirectory = (reference, symlinkStatus) => requireDirectory(reference, symlinkStatus).pipe(Effect.flatMap(() => parentOf(reference, operation.code)));
1858
2091
  /** Requires a regular file, naming the offending type as Sections 18.16.4 and 18.22.3 do. */
1859
2092
  const requireRegularFile = (reference) => mapFs(export_.observeMetadata(reference)).pipe(Effect.flatMap((observation) => {
1860
2093
  switch (observation.value.kind) {
@@ -1888,7 +2121,7 @@ export const makeNfs4Handler = (export_, options) => {
1888
2121
  }
1889
2122
  catch (error) {
1890
2123
  if (error instanceof InvalidNameError)
1891
- return Effect.fail(nameStatus(error));
2124
+ return Effect.fail(nameStatus(error, operation.code));
1892
2125
  throw error;
1893
2126
  }
1894
2127
  }
@@ -1900,12 +2133,13 @@ export const makeNfs4Handler = (export_, options) => {
1900
2133
  try: () => {
1901
2134
  validateName(name, options.limits.maxNameBytes);
1902
2135
  },
1903
- catch: (error) => error instanceof InvalidNameError ? nameStatus(error) : Status.SERVERFAULT
2136
+ catch: (error) => error instanceof InvalidNameError ? nameStatus(error, operation.code) : Status.SERVERFAULT
2137
+ });
2138
+ const writeChangeInfo = (change) => (writer) => Effect.gen(function* () {
2139
+ yield* writer.write(XdrCodec.boolean, true);
2140
+ yield* writer.write(XdrCodec.uint64, BigInt.asUintN(64, change.before));
2141
+ yield* writer.write(XdrCodec.uint64, BigInt.asUintN(64, change.after));
1904
2142
  });
1905
- const writeChangeInfo = (writer, change) => {
1906
- writer.boolean(true).uint64(BigInt.asUintN(64, change.before))
1907
- .uint64(BigInt.asUintN(64, change.after));
1908
- };
1909
2143
  switch (operation.kind) {
1910
2144
  case "ExchangeId": {
1911
2145
  const value = operation.value;
@@ -1954,6 +2188,7 @@ export const makeNfs4Handler = (export_, options) => {
1954
2188
  return { code: operation.code, status: Status.DELAY };
1955
2189
  }
1956
2190
  let previous;
2191
+ let revokeConfirmed = false;
1957
2192
  if (confirmedRecord !== undefined && confirmedRecord.principal !== principal) {
1958
2193
  // Case 3: owner collision with another principal. Live state protects the
1959
2194
  // confirmed record; otherwise it is replaced outright.
@@ -1962,8 +2197,7 @@ export const makeNfs4Handler = (export_, options) => {
1962
2197
  if (hasState && options.now() <= confirmedRecord.leaseExpiresAt) {
1963
2198
  return { code: operation.code, status: Status.CLID_INUSE };
1964
2199
  }
1965
- yield* revokeClient(confirmedRecord);
1966
- removeClientRecord(confirmedRecord);
2200
+ revokeConfirmed = true;
1967
2201
  }
1968
2202
  else if (confirmedRecord !== undefined) {
1969
2203
  // Case 5: client restart. The confirmed record survives until CREATE_SESSION.
@@ -1976,12 +2210,8 @@ export const makeNfs4Handler = (export_, options) => {
1976
2210
  }
1977
2211
  // Case 4: any unconfirmed record for this owner is replaced by a new client ID.
1978
2212
  const unconfirmed = clientsByOwner.get(owner);
1979
- if (unconfirmed !== undefined && !unconfirmed.confirmed) {
1980
- releaseCreateSessionReplay(unconfirmed);
1981
- clients.delete(unconfirmed.id);
1982
- }
1983
2213
  const created = {
1984
- id: clientSerial++,
2214
+ id: clientSerial,
1985
2215
  owner,
1986
2216
  verifier,
1987
2217
  principal,
@@ -1992,28 +2222,45 @@ export const makeNfs4Handler = (export_, options) => {
1992
2222
  confirmed: false,
1993
2223
  createSessionReplay: undefined
1994
2224
  };
2225
+ // A failed response encode must not consume a client ID, replace an owner,
2226
+ // or revoke a confirmed record the caller cannot identify afterward.
2227
+ const response = yield* exchangeIdResult(created);
2228
+ if (revokeConfirmed && confirmedRecord !== undefined) {
2229
+ yield* revokeClient(confirmedRecord);
2230
+ removeClientRecord(confirmedRecord);
2231
+ }
2232
+ if (unconfirmed !== undefined && !unconfirmed.confirmed) {
2233
+ releaseCreateSessionReplay(unconfirmed);
2234
+ clients.delete(unconfirmed.id);
2235
+ }
2236
+ clientSerial++;
1995
2237
  clients.set(created.id, created);
1996
2238
  clientsByOwner.set(owner, created);
1997
- return exchangeIdResult(created);
2239
+ return response;
1998
2240
  });
1999
2241
  }
2000
- return Effect.succeed(exchangeIdResult(client));
2242
+ return exchangeIdResult(client);
2001
2243
  function exchangeIdResult(client) {
2002
- const body = encodeStatusBody((writer) => {
2003
- const flags = EXCHGID4_FLAG_USE_NON_PNFS |
2004
- (client.confirmed ? EXCHGID4_FLAG_CONFIRMED_R : 0);
2005
- writer.uint64(client.id).uint32(client.sequence).uint32(flags >>> 0).uint32(0);
2006
- writer.uint64(export_.fsid[0]).opaque(options.generation).opaque(options.generation);
2007
- writer.array([], () => undefined);
2008
- });
2009
- return { code: operation.code, status: Status.OK, body };
2244
+ const flags = EXCHGID4_FLAG_USE_NON_PNFS |
2245
+ (client.confirmed ? EXCHGID4_FLAG_CONFIRMED_R : 0);
2246
+ return Effect.map(encodeStatusBody(options.limits, [
2247
+ field(XdrCodec.uint64, client.id),
2248
+ field(XdrCodec.uint32, client.sequence),
2249
+ field(XdrCodec.uint32, flags >>> 0),
2250
+ field(XdrCodec.uint32, 0),
2251
+ field(XdrCodec.uint64, export_.fsid[0]),
2252
+ field(XdrCodec.opaque(), options.generation),
2253
+ field(XdrCodec.opaque(), options.generation),
2254
+ field(XdrCodec.array(XdrCodec.uint32), [])
2255
+ ]), (body) => ({ code: operation.code, status: Status.OK, body }));
2010
2256
  }
2011
2257
  }
2012
2258
  case "CreateSession": {
2013
2259
  const value = operation.value;
2014
2260
  const client = clients.get(value.client);
2015
- if (client === undefined)
2261
+ if (client === undefined) {
2016
2262
  return Effect.succeed({ code: operation.code, status: Status.STALE_CLIENTID });
2263
+ }
2017
2264
  const replay = client.createSessionReplay;
2018
2265
  if (replay?.sequence === value.sequence) {
2019
2266
  // Section 18.36.4 phase 2: an equal csa_sequence identifies a retry, which may
@@ -2064,8 +2311,9 @@ export const makeNfs4Handler = (export_, options) => {
2064
2311
  if (!client.confirmed && client.principal !== principalKey(call.credentials)) {
2065
2312
  return { code: operation.code, status: Status.CLID_INUSE };
2066
2313
  }
2067
- if ((value.flags & ~CREATE_SESSION4_KNOWN_FLAGS) !== 0)
2314
+ if ((value.flags & ~CREATE_SESSION4_KNOWN_FLAGS) !== 0) {
2068
2315
  return complete(Status.INVAL);
2316
+ }
2069
2317
  // Section 18.36.3: a callback security entry naming an RPCSEC_GSS handle the
2070
2318
  // server did not issue is NFS4ERR_NOENT.
2071
2319
  if (value.gssCallback)
@@ -2094,11 +2342,13 @@ export const makeNfs4Handler = (export_, options) => {
2094
2342
  // internal limit on how many callbacks it issues, not a renegotiation.
2095
2343
  const back = { ...value.back, headerPadding: 0, rdmaIrd: [] };
2096
2344
  const agreedFlags = wantsBackChannel ? CREATE_SESSION4_FLAG_CONN_BACK_CHAN : 0;
2097
- const body = encodeStatusBody((writer) => {
2098
- writer.fixedOpaque(id).uint32(value.sequence).uint32(agreedFlags);
2099
- writeChannelAttrs(writer, fore);
2100
- writeChannelAttrs(writer, back);
2101
- });
2345
+ const body = yield* encodeStatusBody(options.limits, [
2346
+ field(XdrCodec.fixedOpaque(16), id),
2347
+ field(XdrCodec.uint32, value.sequence),
2348
+ field(XdrCodec.uint32, agreedFlags),
2349
+ (writer) => writeChannelAttrs(writer, fore),
2350
+ (writer) => writeChannelAttrs(writer, back)
2351
+ ]);
2102
2352
  // Section 18.36.3: a channel that can never carry a SEQUENCE compound in either
2103
2353
  // direction, or fewer than two operations, is too small to be used.
2104
2354
  if (fore.maxRequest < MIN_FORE_REQUEST_BYTES || fore.maxResponse < MIN_FORE_RESPONSE_BYTES ||
@@ -2270,20 +2520,22 @@ export const makeNfs4Handler = (export_, options) => {
2270
2520
  const statusFlags = session.back !== undefined && !session.back.healthy
2271
2521
  ? SEQ4_STATUS_CB_PATH_DOWN_SESSION
2272
2522
  : 0;
2273
- const body = encodeStatusBody((writer) => {
2274
- writer.fixedOpaque(session.id).uint32(value.sequence).uint32(value.slot)
2275
- .uint32(session.slots.length - 1).uint32(session.slots.length - 1).uint32(statusFlags);
2523
+ return Effect.flatMap(encodeStatusBody(options.limits, [
2524
+ field(XdrCodec.fixedOpaque(16), session.id),
2525
+ field(XdrCodec.uint32, value.sequence),
2526
+ field(XdrCodec.uint32, value.slot),
2527
+ field(XdrCodec.uint32, session.slots.length - 1),
2528
+ field(XdrCodec.uint32, session.slots.length - 1),
2529
+ field(XdrCodec.uint32, statusFlags)
2530
+ ]), (body) => {
2531
+ // Probe only after the SEQUENCE reply body has encoded successfully.
2532
+ const back = session.back;
2533
+ if (back === undefined || back.probed) {
2534
+ return Effect.succeed({ code: operation.code, status: Status.OK, body });
2535
+ }
2536
+ back.probed = true;
2537
+ return Effect.forkIn(probe(session), handlerScope).pipe(Effect.as({ code: operation.code, status: Status.OK, body }));
2276
2538
  });
2277
- // The callback path is probed once, on the first SEQUENCE rather than during
2278
- // CREATE_SESSION, because only then is the client known to hold the session id
2279
- // that CB_SEQUENCE carries. It is forked because the probe's own reply arrives on
2280
- // this connection, whose read loop is busy with this compound until it returns.
2281
- const back = session.back;
2282
- if (back === undefined || back.probed) {
2283
- return Effect.succeed({ code: operation.code, status: Status.OK, body });
2284
- }
2285
- back.probed = true;
2286
- return Effect.forkIn(probe(session), handlerScope).pipe(Effect.as({ code: operation.code, status: Status.OK, body }));
2287
2539
  }
2288
2540
  case "ReclaimComplete": {
2289
2541
  if (activeSession === undefined) {
@@ -2339,11 +2591,11 @@ export const makeNfs4Handler = (export_, options) => {
2339
2591
  : bound === CHANNEL_FORE
2340
2592
  ? CDFS4_FORE
2341
2593
  : CDFS4_BOTH;
2342
- return Effect.succeed({
2343
- code: operation.code,
2344
- status: Status.OK,
2345
- body: new Writer().fixedOpaque(session.id).uint32(answered).boolean(false).bytes()
2346
- });
2594
+ return Effect.map(encodeStatusBody(options.limits, [
2595
+ field(XdrCodec.fixedOpaque(16), session.id),
2596
+ field(XdrCodec.uint32, answered),
2597
+ field(XdrCodec.boolean, false)
2598
+ ]), (body) => ({ code: operation.code, status: Status.OK, body }));
2347
2599
  }
2348
2600
  case "BackchannelCtl": {
2349
2601
  // Section 18.33.3: an RPCSEC_GSS handle the server never issued is NFS4ERR_NOENT.
@@ -2429,24 +2681,11 @@ export const makeNfs4Handler = (export_, options) => {
2429
2681
  return export_.resolve(operation.value).pipe(Effect.map((reference) => {
2430
2682
  setCurrent(reference);
2431
2683
  return { code: operation.code, status: Status.OK };
2432
- }), Effect.catch((error) => Effect.succeed({
2433
- code: operation.code,
2434
- status: error.reason === "WrongGeneration"
2435
- ? Status.FHEXPIRED
2436
- : error.reason === "Stale"
2437
- ? Status.STALE
2438
- : error.reason === "Unavailable"
2439
- ? Status.SERVERFAULT
2440
- : Status.BADHANDLE
2441
- })));
2684
+ }), Effect.catch((error) => Effect.succeed({ code: operation.code, status: putfhFailure(error) })));
2442
2685
  case "Getfh":
2443
2686
  if (current === undefined)
2444
2687
  return Effect.succeed(noCurrent());
2445
- return export_.handleFor(current).pipe(Effect.map((handle) => ({
2446
- code: operation.code,
2447
- status: Status.OK,
2448
- body: new Writer().opaque(handle).bytes()
2449
- })), Effect.orElseSucceed(() => ({ code: operation.code, status: Status.SERVERFAULT })));
2688
+ return export_.handleFor(current).pipe(Effect.mapError((error) => failureForFs(error, operation.code)), Effect.flatMap((handle) => Effect.map(encodeBody(handle, XdrCodec.opaque()), (body) => ({ code: operation.code, status: Status.OK, body }))), Effect.catchIf((error) => Predicate.isNumber(error), (status) => Effect.succeed({ code: operation.code, status })));
2450
2689
  case "Savefh":
2451
2690
  if (current === undefined)
2452
2691
  return Effect.succeed(noCurrent());
@@ -2461,15 +2700,15 @@ export const makeNfs4Handler = (export_, options) => {
2461
2700
  return Effect.succeed({ code: operation.code, status: Status.OK });
2462
2701
  case "Lookup":
2463
2702
  // Section 15.1.2.8: a symbolic link as the current filehandle is NFS4ERR_SYMLINK.
2464
- return statusResult(withCurrent((reference) => requireDirectory(reference, Status.SYMLINK).pipe(Effect.andThen(export_.lookup(reference, operation.value).pipe(Effect.mapError(nameStatus))))), (reference) => {
2703
+ return statusResult(withCurrent((reference) => requireDirectory(reference, Status.SYMLINK).pipe(Effect.andThen(export_.lookup(reference, operation.value).pipe(Effect.mapError((error) => nameStatus(error, operation.code)))))), (reference) => {
2465
2704
  setCurrent(reference);
2466
2705
  return undefined;
2467
2706
  });
2468
2707
  case "Secinfo":
2469
2708
  // SECINFO consumes the current filehandle (RFC 8881 Section 18.29.3).
2470
- return statusResult(withCurrent((reference) => export_.lookup(reference, operation.value).pipe(Effect.mapError(nameStatus))), () => {
2709
+ return statusResult(withCurrent((reference) => export_.lookup(reference, operation.value).pipe(Effect.mapError((error) => nameStatus(error, operation.code)))), () => {
2471
2710
  setCurrent(undefined);
2472
- return new Writer().array(options.securityFlavors ?? [AUTH_SYS, AUTH_NONE], (writer, flavor) => writer.uint32(flavor)).bytes();
2711
+ return xdr.encode(options.securityFlavors ?? [AUTH_SYS, AUTH_NONE], XdrCodec.array(XdrCodec.uint32), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes));
2473
2712
  });
2474
2713
  case "Lookupp":
2475
2714
  return statusResult(withCurrent((reference) => parentOfDirectory(reference, Status.SYMLINK)), (reference) => {
@@ -2483,7 +2722,7 @@ export const makeNfs4Handler = (export_, options) => {
2483
2722
  ? parentOfDirectory(reference, Status.NOTDIR)
2484
2723
  : Effect.succeed(reference)), () => {
2485
2724
  setCurrent(undefined);
2486
- return new Writer().array(options.securityFlavors ?? [AUTH_SYS, AUTH_NONE], (writer, flavor) => writer.uint32(flavor)).bytes();
2725
+ return xdr.encode(options.securityFlavors ?? [AUTH_SYS, AUTH_NONE], XdrCodec.array(XdrCodec.uint32), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes));
2487
2726
  });
2488
2727
  case "Getattr": {
2489
2728
  if (current === undefined) {
@@ -2528,32 +2767,38 @@ export const makeNfs4Handler = (export_, options) => {
2528
2767
  ? grantedAccess(supported, observation.value, call.credentials)
2529
2768
  : 0;
2530
2769
  if (activeCaller !== undefined) {
2770
+ const writeFlags = observation.value.kind === "directory"
2771
+ ? [ACCESS4_MODIFY, ACCESS4_EXTEND, ACCESS4_DELETE]
2772
+ : [ACCESS4_MODIFY, ACCESS4_EXTEND];
2773
+ const writeBits = observation.value.kind === "directory" ? 0o3 : 0o2;
2531
2774
  for (const [flag, bit] of [
2532
2775
  [ACCESS4_READ, 0o4],
2533
- [observation.value.kind === "directory" ? ACCESS4_LOOKUP : ACCESS4_EXECUTE, 0o1]
2776
+ [observation.value.kind === "directory" ? ACCESS4_LOOKUP : ACCESS4_EXECUTE, 0o1],
2777
+ ...(options.writable ? writeFlags.map((flag) => [flag, writeBits]) : [])
2534
2778
  ]) {
2535
2779
  if ((supported & flag) === 0)
2536
2780
  continue;
2537
- const allowed = yield* activeCaller.accessReference(reference, bit).pipe(Effect.as(true), Effect.catchTag("FsError", (error) => error.code === "AccessDenied"
2538
- ? Effect.succeed(false)
2539
- : Effect.fail(failureForFs(error))));
2781
+ const allowed = yield* export_.access(reference, bit).pipe(Effect.map((granted) => granted === bit), Effect.mapError((error) => failureForFs(error, operation.code)));
2540
2782
  if (allowed)
2541
2783
  granted |= flag;
2542
2784
  }
2543
2785
  }
2544
2786
  return { supported, granted };
2545
- }), ({ supported, granted }) => new Writer().uint32(supported).uint32(granted).bytes());
2787
+ }), ({ supported, granted }) => encodeStatusBody(options.limits, [
2788
+ field(XdrCodec.uint32, supported),
2789
+ field(XdrCodec.uint32, granted)
2790
+ ]));
2546
2791
  }
2547
2792
  case "Commit": {
2548
2793
  if (current === undefined)
2549
2794
  return Effect.succeed(noCurrent());
2550
2795
  // Every writable mutation is committed before publication. There is no unstable
2551
2796
  // range to flush, but a failed provider must not produce a success reply.
2552
- return statusResult(requireRegularFile(current), () => new Writer().fixedOpaque(writeVerifier).bytes());
2797
+ return statusResult(requireRegularFile(current), () => xdr.encode(writeVerifier, XdrCodec.fixedOpaque(8), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes)));
2553
2798
  }
2554
2799
  case "Readlink":
2555
2800
  // Section 18.24.4: an object that is not a symbolic link is NFS4ERR_WRONG_TYPE.
2556
- return statusResult(withCurrent((reference) => mapFs(export_.observeMetadata(reference)).pipe(Effect.filterOrFail((observation) => observation.value.kind === "symlink", () => Status.WRONG_TYPE), Effect.andThen(mapFs(export_.readLink(reference))), Effect.filterOrFail((target) => byteLength(target.length) <= options.limits.maxStringBytes, () => Status.SERVERFAULT))), (target) => new Writer().opaque(target).bytes());
2801
+ return statusResult(withCurrent((reference) => mapFs(export_.observeMetadata(reference)).pipe(Effect.filterOrFail((observation) => observation.value.kind === "symlink", () => Status.WRONG_TYPE), Effect.andThen(mapFs(export_.readLink(reference))), Effect.filterOrFail((target) => byteLength(target.length) <= options.limits.maxStringBytes, () => Status.SERVERFAULT))), (target) => xdr.encode(target, XdrCodec.opaque(), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes)));
2557
2802
  case "Readdir": {
2558
2803
  if (current === undefined)
2559
2804
  return Effect.succeed(noCurrent());
@@ -2574,43 +2819,64 @@ export const makeNfs4Handler = (export_, options) => {
2574
2819
  if (!Number.isSafeInteger(start) || start < 0 || start > observation.value.length) {
2575
2820
  return { code: operation.code, status: Status.BAD_COOKIE };
2576
2821
  }
2577
- const writer = new Writer().fixedOpaque(verifier);
2578
- let count = 0;
2579
- let directoryBytes = 0;
2580
- const responseLimit = Math.min(value.maxcount, ByteSize.toNumberUnsafe(options.limits.maxReaddirReplyBytes));
2822
+ const paddedTagBytes = parsed.tag.length + (4 - parsed.tag.length % 4) % 4;
2823
+ const envelopeBytes = 44 + paddedTagBytes +
2824
+ parts.reduce((bytes, part) => bytes + 8 + (part.body?.length ?? 0), 0);
2825
+ const responseLimit = Math.min(value.maxcount, ByteSize.toNumberUnsafe(options.limits.maxReaddirReplyBytes), Math.max(0, ByteSize.toNumberUnsafe(maxRpcResponseBytes) - envelopeBytes), Math.max(0, (activeSession?.fore.maxResponse ?? Number.MAX_SAFE_INTEGER) - envelopeBytes), shouldCache
2826
+ ? Math.max(0, (activeSession?.fore.maxCachedResponse ?? Number.MAX_SAFE_INTEGER) - envelopeBytes)
2827
+ : Number.MAX_SAFE_INTEGER);
2581
2828
  if (responseLimit < 16) {
2582
2829
  return { code: operation.code, status: Status.TOOSMALL };
2583
2830
  }
2831
+ const writer = yield* xdr.openWriter(options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes));
2832
+ yield* writer.write(XdrCodec.fixedOpaque(8), verifier);
2833
+ let count = 0;
2834
+ let directoryBytes = 0;
2584
2835
  for (let item = start; item < observation.value.length && count < options.limits.maxReaddirEntries; item++) {
2585
2836
  const entry = observation.value[item];
2586
2837
  if (!isValidName(entry.name, options.limits.maxNameBytes)) {
2587
2838
  return { code: operation.code, status: Status.INVAL };
2588
2839
  }
2589
2840
  const attrs = supportedRequested.length === 0
2590
- ? new Writer().uint32(0).uint32(0).bytes()
2841
+ ? yield* encodeStatusBody(options.limits, [
2842
+ field(XdrCodec.uint32, 0),
2843
+ field(XdrCodec.uint32, 0)
2844
+ ])
2591
2845
  : yield* filehandleFor(entry.reference, supportedRequested).pipe(Effect.flatMap((handle) => mapFs(export_.observeMetadata(entry.reference)).pipe(Effect.flatMap((metadata) => requireAttributes(encodeAttributes(supportedRequested, metadata, handle, export_, options, supportedAttributes, usage))))),
2592
- // With rdattr_error requested, a failing entry reports its own error
2593
- // instead of failing the whole READDIR (RFC 8881 Section 18.23.3).
2594
- Effect.catch((status) => supportedRequested.includes(11)
2595
- ? Effect.succeed(encodeReaddirError(status))
2596
- : Effect.fail(status)));
2597
- const encoded = new Writer().boolean(true).uint64(BigInt(item + 3)).opaque(entry.name)
2598
- .fixedOpaque(attrs).bytes();
2846
+ // With rdattr_error requested, a failing entry reports its own error.
2847
+ Effect.catch((error) => {
2848
+ if (error instanceof XdrEncodeError)
2849
+ return Effect.fail(error);
2850
+ if (supportedRequested.includes(11))
2851
+ return encodeReaddirError(error, options.limits);
2852
+ return Effect.fail(error);
2853
+ }));
2854
+ const encoded = yield* encodeStatusBody(options.limits, [
2855
+ field(XdrCodec.boolean, true),
2856
+ field(XdrCodec.uint64, BigInt(item + 3)),
2857
+ field(XdrCodec.opaque(), entry.name),
2858
+ (itemWriter) => itemWriter.appendEncoded(attrs)
2859
+ ]);
2599
2860
  const entryDirectoryBytes = 12 + entry.name.length + (4 - entry.name.length % 4) % 4;
2600
2861
  if ((value.dircount !== 0 && directoryBytes + entryDirectoryBytes > value.dircount) ||
2601
- writer.length + encoded.length + 8 > responseLimit) {
2862
+ (yield* writer.length) + encoded.length + 8 > responseLimit) {
2602
2863
  if (count === 0) {
2603
2864
  return { code: operation.code, status: Status.TOOSMALL };
2604
2865
  }
2605
2866
  break;
2606
2867
  }
2607
- writer.fixedOpaque(encoded);
2868
+ yield* writer.appendEncoded(encoded);
2608
2869
  directoryBytes += entryDirectoryBytes;
2609
2870
  count += 1;
2610
2871
  }
2611
- writer.boolean(false).boolean(start + count >= observation.value.length);
2612
- return { code: operation.code, status: Status.OK, body: writer.bytes() };
2613
- })), Effect.catch((status) => Effect.succeed({ code: operation.code, status })));
2872
+ yield* writer.write(XdrCodec.boolean, false);
2873
+ yield* writer.write(XdrCodec.boolean, start + count >= observation.value.length);
2874
+ return {
2875
+ code: operation.code,
2876
+ status: Status.OK,
2877
+ body: yield* writer.finish
2878
+ };
2879
+ })), Effect.catchIf(Predicate.isNumber, (status) => Effect.succeed({ code: operation.code, status })));
2614
2880
  }
2615
2881
  case "Open": {
2616
2882
  if (activeSession === undefined) {
@@ -2654,7 +2920,7 @@ export const makeNfs4Handler = (export_, options) => {
2654
2920
  yield* restore(requireDirectory(directory, Status.SYMLINK));
2655
2921
  const create = value.create;
2656
2922
  const found = yield* restore(export_.lookup(directory, value.name).pipe(Effect.catch((error) => error instanceof InvalidNameError || error.code !== "NotFound"
2657
- ? Effect.fail(nameStatus(error)) :
2923
+ ? Effect.fail(nameStatus(error, operation.code)) :
2658
2924
  Effect.void)));
2659
2925
  const observed = found === undefined
2660
2926
  ? undefined
@@ -2663,7 +2929,7 @@ export const makeNfs4Handler = (export_, options) => {
2663
2929
  return yield* Effect.fail(Status.EXIST);
2664
2930
  // Existing-file creates ignore initial values; the attribute mask and
2665
2931
  // XDR structure still obey the selected create mode's restrictions.
2666
- const attrs = yield* creationAttributes(create, options.limits, observed !== undefined);
2932
+ const attrs = yield* creationAttributes(create, options.limits, observed !== undefined).pipe(Effect.mapError((error) => error instanceof XdrDecodeError ? Status.BADXDR : error));
2667
2933
  if (observed !== undefined) {
2668
2934
  if (create.mode >= 2) {
2669
2935
  const times = attrs.settings.times;
@@ -2688,7 +2954,8 @@ export const makeNfs4Handler = (export_, options) => {
2688
2954
  if (existing === undefined && opens.size >= options.limits.maxOpens) {
2689
2955
  return yield* Effect.fail(Status.DELAY);
2690
2956
  }
2691
- const truncate = create.mode === 0 && attrs.settings.initialSize === 0n && observed !== undefined;
2957
+ const truncate = create.mode === 0 && attrs.settings.initialSize === 0n &&
2958
+ observed !== undefined;
2692
2959
  if (truncate && !wantsWrite)
2693
2960
  return yield* Effect.fail(Status.INVAL);
2694
2961
  const opened = yield* restore(export_.openChild(directory, value.name, {
@@ -2703,14 +2970,12 @@ export const makeNfs4Handler = (export_, options) => {
2703
2970
  atimeNs: observed.value.atimeNs,
2704
2971
  mtimeNs: observed.value.mtimeNs
2705
2972
  }
2706
- }).pipe(Effect.mapError((error) => {
2707
- if (error instanceof ExportCapacityError)
2708
- return Status.DELAY;
2973
+ }).pipe(Scope.provide(handlerScope), Effect.mapError((error) => {
2709
2974
  if (error instanceof InvalidNameError)
2710
- return nameStatus(error);
2975
+ return nameStatus(error, operation.code);
2711
2976
  if (error.code === "StaleReference")
2712
2977
  return Status.DELAY;
2713
- return failureForFs(error);
2978
+ return failureForFs(error, operation.code);
2714
2979
  })));
2715
2980
  let id;
2716
2981
  if (existing === undefined) {
@@ -2748,17 +3013,18 @@ export const makeNfs4Handler = (export_, options) => {
2748
3013
  }
2749
3014
  current = opened.reference;
2750
3015
  const applied = opened.created ? attrs.attributes : truncate ? [4] : [];
2751
- return openResult(id, opened.directory.before, true, opened.directory.after, create.mode >= 2 ? [...applied, 47, 53] : applied);
2752
- })).pipe(Effect.catch((status) => Effect.succeed({ code: operation.code, status })));
3016
+ return yield* openResult(id, opened.directory.before, true, opened.directory.after, create.mode >= 2 ? [...applied, 47, 53] : applied);
3017
+ })).pipe(Effect.catchIf(Predicate.isNumber, (status) => Effect.succeed({ code: operation.code, status })));
2753
3018
  }
2754
3019
  const target = value.claim === 4
2755
3020
  ? Effect.succeed({ revision: 0n, reference: directory })
2756
- : requireDirectory(directory, Status.SYMLINK).pipe(Effect.andThen(mapFs(export_.observeMetadata(directory))), Effect.flatMap((directoryObservation) => export_.lookup(directory, value.name).pipe(Effect.mapError(nameStatus), Effect.map((reference) => ({ revision: directoryObservation.revision, reference })))));
3021
+ : requireDirectory(directory, Status.SYMLINK).pipe(Effect.andThen(mapFs(export_.observeMetadata(directory))), Effect.flatMap((directoryObservation) => export_.lookup(directory, value.name).pipe(Effect.mapError((error) => nameStatus(error, operation.code)), Effect.map((reference) => ({ revision: directoryObservation.revision, reference })))));
2757
3022
  return target.pipe(Effect.tap(({ reference }) => requireRegularFile(reference)),
2758
3023
  // Write access is refused only once the target is known to be a regular file.
2759
3024
  Effect.tap(() => wantsWrite && !options.writable ? Effect.fail(Status.ROFS) : Effect.void), Effect.flatMap(({ revision, reference }) => Effect.uninterruptibleMask((restore) => Effect.suspend(() => {
2760
3025
  const owner = bytesKey(value.owner);
2761
- const existing = [...opens.values()].find((open) => open.client === activeSession.client && open.owner === owner && open.reference === reference);
3026
+ const existing = [...opens.values()].find((open) => open.client === activeSession.client && open.owner === owner &&
3027
+ open.reference === reference);
2762
3028
  // Section 9.7 checks every open, including this open-owner's own state.
2763
3029
  const denied = [...opens.values()].some((open) => open.reference === reference &&
2764
3030
  ((open.deny & accessMode) !== 0 || (value.deny & open.access) !== 0));
@@ -2771,14 +3037,15 @@ export const makeNfs4Handler = (export_, options) => {
2771
3037
  const nextAccess = existing.access | accessMode;
2772
3038
  const permission = activeCaller === undefined ?
2773
3039
  Effect.void :
2774
- mapFs(activeCaller.accessReference(reference, (accessMode & 1 ? 0o4 : 0) | (accessMode & 2 ? 0o2 : 0)));
3040
+ requireAccess(reference, (accessMode & 1 ? 0o4 : 0) | (accessMode & 2 ? 0o2 : 0));
2775
3041
  const addedAccess = nextAccess & ~existing.access;
2776
3042
  const heldHandle = addedAccess === OPEN4_SHARE_ACCESS_READ
2777
3043
  ? existing.readFile
2778
3044
  : existing.writeFile;
2779
3045
  const replacement = addedAccess === 0 || heldHandle !== undefined ?
2780
3046
  Effect.succeed(null) :
2781
- mapFs(export_.open(reference, addedAccess === OPEN4_SHARE_ACCESS_READ ? "read" : "write"));
3047
+ mapFs(export_.open(reference, addedAccess === OPEN4_SHARE_ACCESS_READ ? "read" : "write")
3048
+ .pipe(Scope.provide(handlerScope)));
2782
3049
  let transferred = false;
2783
3050
  return restore(permission).pipe(Effect.andThen(Effect.acquireUseRelease(restore(replacement), (opened) => opened === null ? Effect.void : Effect.sync(() => {
2784
3051
  const previousClose = existing.close;
@@ -2788,7 +3055,7 @@ export const makeNfs4Handler = (export_, options) => {
2788
3055
  existing.writeFile = opened.handle;
2789
3056
  existing.close = opened.close.pipe(Effect.andThen(previousClose));
2790
3057
  transferred = true;
2791
- }), (opened) => opened === null || transferred ? Effect.void : opened.close)), Effect.map(() => {
3058
+ }), (opened) => opened === null || transferred ? Effect.void : opened.close)), Effect.flatMap(() => {
2792
3059
  existing.access = nextAccess;
2793
3060
  existing.deny |= value.deny;
2794
3061
  advanceStateId(existing);
@@ -2800,7 +3067,8 @@ export const makeNfs4Handler = (export_, options) => {
2800
3067
  return Effect.succeed({ code: operation.code, status: Status.DELAY });
2801
3068
  }
2802
3069
  const serial = openSerial++;
2803
- return restore(mapFs(export_.open(reference, accessMode === 3 ? "readWrite" : wantsWrite ? "write" : "read"))).pipe(Effect.map((opened) => {
3070
+ return restore(mapFs(export_.open(reference, accessMode === 3 ? "readWrite" : wantsWrite ? "write" : "read")
3071
+ .pipe(Scope.provide(handlerScope)))).pipe(Effect.flatMap((opened) => {
2804
3072
  const id = makeStateId(options.generation, serial, 1);
2805
3073
  opens.set(stateIdKey(id), {
2806
3074
  id,
@@ -2817,30 +3085,30 @@ export const makeNfs4Handler = (export_, options) => {
2817
3085
  current = reference;
2818
3086
  return openResult(id, revision, value.claim === 4);
2819
3087
  }));
2820
- }))), Effect.catch((status) => Effect.succeed({ code: operation.code, status })));
3088
+ }))), Effect.catchIf(Predicate.isNumber, (status) => Effect.succeed({ code: operation.code, status })));
2821
3089
  function openResult(id, revision, atomic, after = revision, attributes = []) {
2822
- currentStateid = id;
2823
- const body = encodeStatusBody((writer) => {
2824
- writer.fixedOpaque(id).boolean(atomic)
2825
- .uint64(BigInt.asUintN(64, revision))
2826
- .uint64(BigInt.asUintN(64, after)).uint32(0);
2827
- writeBitmap(writer, wordsFor(attributes));
2828
- if (delegationWant === 0) {
2829
- writer.uint32(OPEN_DELEGATE_NONE);
2830
- }
2831
- else {
2832
- // Section 18.16.3: a want that is not satisfied MUST be answered with
2833
- // OPEN_DELEGATE_NONE_EXT and a reason. NOT_WANTED and CANCELLED carry no body,
2834
- // and NOT_SUPP_FTYPE is the honest reason for a server without delegations.
2835
- const why = delegationWant === OPEN4_SHARE_ACCESS_WANT_NO_DELEG
3090
+ const delegationFields = delegationWant === 0
3091
+ ? [field(XdrCodec.uint32, OPEN_DELEGATE_NONE)]
3092
+ : [
3093
+ field(XdrCodec.uint32, OPEN_DELEGATE_NONE_EXT),
3094
+ field(XdrCodec.uint32, delegationWant === OPEN4_SHARE_ACCESS_WANT_NO_DELEG
2836
3095
  ? WND4_NOT_WANTED
2837
3096
  : delegationWant === OPEN4_SHARE_ACCESS_WANT_CANCEL
2838
3097
  ? WND4_CANCELLED
2839
- : WND4_NOT_SUPP_FTYPE;
2840
- writer.uint32(OPEN_DELEGATE_NONE_EXT).uint32(why);
2841
- }
3098
+ : WND4_NOT_SUPP_FTYPE)
3099
+ ];
3100
+ return Effect.map(encodeStatusBody(options.limits, [
3101
+ field(XdrCodec.fixedOpaque(16), id),
3102
+ field(XdrCodec.boolean, atomic),
3103
+ field(XdrCodec.uint64, BigInt.asUintN(64, revision)),
3104
+ field(XdrCodec.uint64, BigInt.asUintN(64, after)),
3105
+ field(XdrCodec.uint32, 0),
3106
+ (writer) => writeBitmap(writer, wordsFor(attributes)),
3107
+ ...delegationFields
3108
+ ]), (body) => {
3109
+ currentStateid = id;
3110
+ return { code: operation.code, status: Status.OK, body };
2842
3111
  });
2843
- return { code: operation.code, status: Status.OK, body };
2844
3112
  }
2845
3113
  }
2846
3114
  case "Read": {
@@ -2853,14 +3121,14 @@ export const makeNfs4Handler = (export_, options) => {
2853
3121
  return Effect.succeed(noCurrent());
2854
3122
  const readPermission = activeCaller === undefined
2855
3123
  ? Effect.void
2856
- : activeCaller.accessReference(current, 0o4).pipe(Effect.mapError(failureForFs));
3124
+ : requireAccess(current, 0o4);
2857
3125
  if (isAllZero(value.stateid) || isAllOnes(value.stateid)) {
2858
3126
  const reference = current;
2859
3127
  // Section 9.1.2: the anonymous stateid must still respect a deny-read share
2860
3128
  // reservation; the READ-bypass stateid (all ones) may ignore it.
2861
3129
  const denied = isAllZero(value.stateid) &&
2862
3130
  [...opens.values()].some((open) => open.reference === reference && (open.deny & OPEN4_SHARE_DENY_READ) !== 0);
2863
- return requireRegularFile(reference).pipe(Effect.andThen(denied ? Effect.fail(Status.LOCKED) : Effect.void), Effect.andThen(readPermission), Effect.andThen(Effect.acquireUseRelease(mapFs(export_.open(reference)), (opened) => readFrom(opened.handle), (opened) => opened.close)), Effect.catch((status) => Effect.succeed({ code: operation.code, status })));
3131
+ return requireRegularFile(reference).pipe(Effect.andThen(denied ? Effect.fail(Status.LOCKED) : Effect.void), Effect.andThen(readPermission), Effect.andThen(Effect.acquireUseRelease(mapFs(Scope.provide(export_.open(reference), handlerScope)), (opened) => readFrom(opened.handle), (opened) => opened.close)), Effect.catchIf(Predicate.isNumber, (status) => Effect.succeed({ code: operation.code, status })));
2864
3132
  }
2865
3133
  const effectiveStateid = isCurrentStateId(value.stateid) ? currentStateid : value.stateid;
2866
3134
  if (effectiveStateid === undefined) {
@@ -2889,30 +3157,33 @@ export const makeNfs4Handler = (export_, options) => {
2889
3157
  if (open.readFile === undefined) {
2890
3158
  return Effect.succeed({ code: operation.code, status: Status.SERVERFAULT });
2891
3159
  }
2892
- return readPermission.pipe(Effect.andThen(readFrom(open.readFile)), Effect.catch((status) => Effect.succeed({ code: operation.code, status })));
3160
+ return readPermission.pipe(Effect.andThen(readFrom(open.readFile)), Effect.catchIf(Predicate.isNumber, (status) => Effect.succeed({ code: operation.code, status })));
2893
3161
  function readFrom(file) {
2894
- return file.pread(value.count, value.offset).pipe(Effect.flatMap((data) => file.stat.pipe(Effect.map((metadata) => ({ data, metadata })))), Effect.map(({ data, metadata }) => ({
2895
- code: operation.code,
2896
- status: Status.OK,
2897
- body: new Writer().boolean(value.offset + BigInt(data.length) >= metadata.size).opaque(data)
2898
- .bytes()
2899
- })), Effect.catch((error) => Effect.succeed({ code: operation.code, status: failureForFs(error) })));
3162
+ return file.pread(value.count, value.offset).pipe(Effect.flatMap(({ bytes: data, eof }) => Effect.map(encodeStatusBody(options.limits, [
3163
+ field(XdrCodec.boolean, eof),
3164
+ field(XdrCodec.opaque(), data)
3165
+ ]), (body) => ({ code: operation.code, status: Status.OK, body }))), Effect.catchTag("VfsError", (error) => Effect.succeed({ code: operation.code, status: failureForFs(error, operation.code) })));
2900
3166
  }
2901
3167
  }
2902
3168
  case "OpenDowngrade": {
2903
- if (current === undefined)
3169
+ if (current === undefined) {
2904
3170
  return Effect.succeed(noCurrent());
3171
+ }
2905
3172
  const value = operation.value;
2906
3173
  // Section 16.2.3: the special current stateid refers to a preceding OPEN.
2907
3174
  const stateid = isCurrentStateId(value.stateid) ? currentStateid : value.stateid;
2908
- if (stateid === undefined)
3175
+ if (stateid === undefined) {
3176
+ // The special stateid has no earlier OPEN result to refer to.
2909
3177
  return Effect.succeed({ code: operation.code, status: Status.BAD_STATEID });
3178
+ }
2910
3179
  const open = opens.get(stateIdKey(stateid));
2911
- if (open === undefined)
3180
+ if (open === undefined) {
2912
3181
  return Effect.succeed({ code: operation.code, status: Status.BAD_STATEID });
3182
+ }
2913
3183
  const stateidStatus = checkOpenStateId(stateid, open);
2914
- if (stateidStatus !== Status.OK)
3184
+ if (stateidStatus !== Status.OK) {
2915
3185
  return Effect.succeed({ code: operation.code, status: stateidStatus });
3186
+ }
2916
3187
  // Section 18.18.3: delegation want bits are masked off, and the new modes must be
2917
3188
  // non-empty subsets of what is held.
2918
3189
  const access = value.access & ~OPEN4_SHARE_ACCESS_WANT_DELEG_MASK;
@@ -2923,11 +3194,7 @@ export const makeNfs4Handler = (export_, options) => {
2923
3194
  open.deny = value.deny;
2924
3195
  advanceStateId(open);
2925
3196
  currentStateid = open.id;
2926
- return Effect.succeed({
2927
- code: operation.code,
2928
- status: Status.OK,
2929
- body: new Writer().fixedOpaque(open.id).bytes()
2930
- });
3197
+ return Effect.map(xdr.encode(open.id, XdrCodec.fixedOpaque(16), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes)), (body) => ({ code: operation.code, status: Status.OK, body }));
2931
3198
  }
2932
3199
  case "FreeStateid": {
2933
3200
  if (activeSession === undefined) {
@@ -2939,8 +3206,10 @@ export const makeNfs4Handler = (export_, options) => {
2939
3206
  const lock = lockStates.get(key);
2940
3207
  if (lock !== undefined && lock.client === activeSession.client) {
2941
3208
  const status = checkStateIdSequence(operation.value, lock);
2942
- if (status !== Status.OK)
3209
+ if (status !== Status.OK) {
3210
+ // A stale stateid cannot release the lock owner's state.
2943
3211
  return Effect.succeed({ code: operation.code, status });
3212
+ }
2944
3213
  if (lock.ranges.length !== 0) {
2945
3214
  return Effect.succeed({ code: operation.code, status: Status.LOCKS_HELD });
2946
3215
  }
@@ -2963,8 +3232,9 @@ export const makeNfs4Handler = (export_, options) => {
2963
3232
  const session = activeSession;
2964
3233
  // TEST_STATEID checks stateids alone; it does not involve the current filehandle.
2965
3234
  const results = operation.value.map((stateid) => {
2966
- if (isSpecialStateId(stateid))
3235
+ if (isSpecialStateId(stateid)) {
2967
3236
  return Status.BAD_STATEID;
3237
+ }
2968
3238
  const open = opens.get(stateIdKey(stateid));
2969
3239
  if (open === undefined) {
2970
3240
  const lock = lockStates.get(stateIdKey(stateid));
@@ -2972,48 +3242,53 @@ export const makeNfs4Handler = (export_, options) => {
2972
3242
  ? Status.BAD_STATEID
2973
3243
  : checkStateIdSequence(stateid, lock);
2974
3244
  }
2975
- if (open.client !== session.client)
3245
+ if (open.client !== session.client) {
3246
+ // TEST_STATEID cannot expose another client's open state.
2976
3247
  return Status.BAD_STATEID;
3248
+ }
2977
3249
  return checkStateIdSequence(stateid, open);
2978
3250
  });
2979
- return Effect.succeed({
2980
- code: operation.code,
2981
- status: Status.OK,
2982
- body: new Writer().array(results, (writer, status) => writer.uint32(status)).bytes()
2983
- });
3251
+ return Effect.map(xdr.encode(results, XdrCodec.array(XdrCodec.uint32), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes)), (body) => ({ code: operation.code, status: Status.OK, body }));
2984
3252
  }
2985
3253
  case "SetSsv":
2986
3254
  // State protection is always SP4_NONE (RFC 8881 Section 18.47.3).
2987
3255
  return Effect.succeed({ code: operation.code, status: Status.INVAL });
2988
3256
  case "Lock": {
2989
- if (current === undefined)
3257
+ if (current === undefined) {
2990
3258
  return Effect.succeed(noCurrent());
3259
+ }
2991
3260
  const value = operation.value;
2992
3261
  const range = lockRange(value.offset, value.length);
2993
- return requireRegularFile(current).pipe(Effect.andThen(Effect.sync(() => {
2994
- if (range === undefined)
3262
+ return requireRegularFile(current).pipe(Effect.andThen(Effect.gen(function* () {
3263
+ if (range === undefined) {
2995
3264
  return { code: operation.code, status: Status.INVAL };
2996
- if (value.reclaim)
3265
+ }
3266
+ if (value.reclaim) {
2997
3267
  return { code: operation.code, status: Status.NO_GRACE };
3268
+ }
2998
3269
  if (WRITE_LOCK_TYPES.has(value.lockType) && !options.writable) {
2999
3270
  return { code: operation.code, status: Status.ROFS };
3000
3271
  }
3001
- if (activeSession === undefined)
3272
+ if (activeSession === undefined) {
3002
3273
  return { code: operation.code, status: Status.BADSESSION };
3274
+ }
3003
3275
  const client = activeSession.client;
3004
3276
  const locker = value.locker;
3005
3277
  let lock;
3006
3278
  let created = false;
3007
3279
  if (locker.kind === "new") {
3008
3280
  const stateid = isCurrentStateId(locker.stateid) ? currentStateid : locker.stateid;
3009
- if (stateid === undefined)
3281
+ if (stateid === undefined) {
3010
3282
  return { code: operation.code, status: Status.BAD_STATEID };
3283
+ }
3011
3284
  const open = opens.get(stateIdKey(stateid));
3012
- if (open === undefined)
3285
+ if (open === undefined) {
3013
3286
  return { code: operation.code, status: Status.BAD_STATEID };
3287
+ }
3014
3288
  const status = checkOpenStateId(stateid, open);
3015
- if (status !== Status.OK)
3289
+ if (status !== Status.OK) {
3016
3290
  return { code: operation.code, status };
3291
+ }
3017
3292
  if ((open.access & (WRITE_LOCK_TYPES.has(value.lockType) ? 2 : 1)) === 0) {
3018
3293
  return { code: operation.code, status: Status.OPENMODE };
3019
3294
  }
@@ -3038,25 +3313,30 @@ export const makeNfs4Handler = (export_, options) => {
3038
3313
  }
3039
3314
  else {
3040
3315
  const stateid = isCurrentStateId(locker.stateid) ? currentStateid : locker.stateid;
3041
- if (stateid === undefined)
3316
+ if (stateid === undefined) {
3042
3317
  return { code: operation.code, status: Status.BAD_STATEID };
3318
+ }
3043
3319
  lock = lockStates.get(stateIdKey(stateid));
3044
- if (lock === undefined)
3320
+ if (lock === undefined) {
3045
3321
  return { code: operation.code, status: Status.BAD_STATEID };
3322
+ }
3046
3323
  const status = checkLockStateId(stateid, lock);
3047
- if (status !== Status.OK)
3324
+ if (status !== Status.OK) {
3048
3325
  return { code: operation.code, status };
3326
+ }
3049
3327
  if ((lock.open.access & (WRITE_LOCK_TYPES.has(value.lockType) ? 2 : 1)) === 0) {
3050
3328
  return { code: operation.code, status: Status.OPENMODE };
3051
3329
  }
3052
3330
  }
3053
3331
  const conflict = conflictingLock(lock.open.reference, lock.client, lock.ownerKey, range, value.lockType);
3054
- if (conflict !== undefined)
3055
- return deniedLock(operation.code, conflict);
3332
+ if (conflict !== undefined) {
3333
+ return yield* deniedLock(operation.code, conflict);
3334
+ }
3056
3335
  const ownerStates = [...lockStates.values()].filter((state) => state.client === lock.client && state.ownerKey === lock.ownerKey &&
3057
3336
  state.open.reference === lock.open.reference);
3058
- if (created)
3337
+ if (created) {
3059
3338
  ownerStates.push(lock);
3339
+ }
3060
3340
  const updates = ownerStates.map((state) => ({
3061
3341
  state,
3062
3342
  next: replaceLockRange(state.ranges, range, state === lock ? (WRITE_LOCK_TYPES.has(value.lockType) ? 2 : 1) : undefined)
@@ -3079,8 +3359,9 @@ export const makeNfs4Handler = (export_, options) => {
3079
3359
  if (changed)
3080
3360
  advanceStateId(lock);
3081
3361
  currentStateid = lock.id;
3082
- return { code: operation.code, status: Status.OK, body: new Writer().fixedOpaque(lock.id).bytes() };
3083
- })), Effect.catch((status) => Effect.succeed({ code: operation.code, status })));
3362
+ const body = yield* xdr.encode(lock.id, XdrCodec.fixedOpaque(16), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes));
3363
+ return { code: operation.code, status: Status.OK, body };
3364
+ })), Effect.catchIf(Predicate.isNumber, (status) => Effect.succeed({ code: operation.code, status })));
3084
3365
  }
3085
3366
  case "Lockt": {
3086
3367
  if (current === undefined)
@@ -3088,7 +3369,7 @@ export const makeNfs4Handler = (export_, options) => {
3088
3369
  const reference = current;
3089
3370
  const value = operation.value;
3090
3371
  const range = lockRange(value.offset, value.length);
3091
- return requireRegularFile(reference).pipe(Effect.map(() => {
3372
+ return requireRegularFile(reference).pipe(Effect.flatMap(() => Effect.gen(function* () {
3092
3373
  if (range === undefined)
3093
3374
  return { code: operation.code, status: Status.INVAL };
3094
3375
  if (WRITE_LOCK_TYPES.has(value.lockType) && !options.writable) {
@@ -3099,8 +3380,8 @@ export const makeNfs4Handler = (export_, options) => {
3099
3380
  const conflict = conflictingLock(reference, activeSession.client, bytesKey(value.owner), range, value.lockType);
3100
3381
  return conflict === undefined
3101
3382
  ? { code: operation.code, status: Status.OK }
3102
- : deniedLock(operation.code, conflict);
3103
- }), Effect.catch((status) => Effect.succeed({ code: operation.code, status })));
3383
+ : yield* deniedLock(operation.code, conflict);
3384
+ })), Effect.catchIf(Predicate.isNumber, (status) => Effect.succeed({ code: operation.code, status })));
3104
3385
  }
3105
3386
  case "Locku": {
3106
3387
  if (current === undefined)
@@ -3134,11 +3415,7 @@ export const makeNfs4Handler = (export_, options) => {
3134
3415
  }
3135
3416
  advanceStateId(lock);
3136
3417
  currentStateid = lock.id;
3137
- return Effect.succeed({
3138
- code: operation.code,
3139
- status: Status.OK,
3140
- body: new Writer().fixedOpaque(lock.id).bytes()
3141
- });
3418
+ return Effect.map(xdr.encode(lock.id, XdrCodec.fixedOpaque(16), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes)), (body) => ({ code: operation.code, status: Status.OK, body }));
3142
3419
  }
3143
3420
  case "Close": {
3144
3421
  if (current === undefined)
@@ -3153,8 +3430,9 @@ export const makeNfs4Handler = (export_, options) => {
3153
3430
  if (open === undefined)
3154
3431
  return Effect.succeed({ code: operation.code, status: Status.BAD_STATEID });
3155
3432
  const stateidStatus = checkOpenStateId(stateid, open);
3156
- if (stateidStatus !== Status.OK)
3433
+ if (stateidStatus !== Status.OK) {
3157
3434
  return Effect.succeed({ code: operation.code, status: stateidStatus });
3435
+ }
3158
3436
  if ([...lockStates.values()].some((lock) => lock.open === open && lock.ranges.length > 0)) {
3159
3437
  return Effect.succeed({ code: operation.code, status: Status.LOCKS_HELD });
3160
3438
  }
@@ -3163,18 +3441,14 @@ export const makeNfs4Handler = (export_, options) => {
3163
3441
  // Closing the handle and dropping it from `opens` are one region. An interrupt
3164
3442
  // delivered between them would leave a closed handle in the map for the handler
3165
3443
  // scope's finalizer to close a second time.
3166
- return Effect.uninterruptible(open.close.pipe(Effect.tap(() => Effect.sync(() => {
3444
+ return xdr.encode(closedStateid, XdrCodec.fixedOpaque(16), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes)).pipe(Effect.flatMap((body) => Effect.uninterruptible(open.close.pipe(Effect.tap(() => Effect.sync(() => {
3167
3445
  opens.delete(key);
3168
3446
  for (const [lockKey, lock] of lockStates) {
3169
3447
  if (lock.open === open)
3170
3448
  lockStates.delete(lockKey);
3171
3449
  }
3172
3450
  currentStateid = closedStateid;
3173
- })))).pipe(Effect.as({
3174
- code: operation.code,
3175
- status: Status.OK,
3176
- body: new Writer().fixedOpaque(closedStateid).bytes()
3177
- }));
3451
+ })))).pipe(Effect.as({ code: operation.code, status: Status.OK, body }))));
3178
3452
  }
3179
3453
  case "Write": {
3180
3454
  if (current === undefined)
@@ -3208,71 +3482,53 @@ export const makeNfs4Handler = (export_, options) => {
3208
3482
  const writeFile = open.writeFile;
3209
3483
  return statusResult(requireRegularFile(reference).pipe(Effect.andThen(activeCaller === undefined
3210
3484
  ? Effect.void
3211
- : activeCaller.accessReference(reference, 0o2).pipe(Effect.mapError(failureForFs))), Effect.andThen(mapFs(writeFile.pwrite(value.data, value.offset)))), (count) => new Writer().uint32(count).uint32(2).fixedOpaque(writeVerifier).bytes());
3485
+ : requireAccess(reference, 0o2)), Effect.andThen(mapFs(writeFile.pwrite(value.data, value.offset)))), (count) => encodeStatusBody(options.limits, [
3486
+ field(XdrCodec.uint32, count),
3487
+ field(XdrCodec.uint32, 2),
3488
+ field(XdrCodec.fixedOpaque(8), writeVerifier)
3489
+ ]));
3212
3490
  }
3213
3491
  case "Setattr": {
3214
- const emptyAttrs = new Writer().uint32(0).bytes();
3215
- if (current === undefined) {
3216
- return Effect.succeed({ ...noCurrent(), body: emptyAttrs });
3217
- }
3218
- if (!options.writable) {
3219
- return Effect.succeed({ code: operation.code, status: Status.ROFS, body: emptyAttrs });
3492
+ if (current === undefined || !options.writable) {
3493
+ return Effect.map(xdr.encode([], XdrCodec.array(XdrCodec.uint32), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes)), (body) => ({
3494
+ code: operation.code,
3495
+ status: current === undefined ? Status.NOFILEHANDLE : Status.ROFS,
3496
+ body
3497
+ }));
3220
3498
  }
3221
3499
  const reference = current;
3222
3500
  const value = operation.value;
3223
3501
  return Effect.gen(function* () {
3224
- const applied = [];
3225
- const reply = (status) => ({
3226
- code: operation.code,
3227
- status,
3228
- body: encodeStatusBody((writer) => writeBitmap(writer, wordsFor(applied)))
3229
- });
3230
- const decoded = yield* setattrAttributes(value.attrs, options.limits, supportedAttributes).pipe(Effect.map((changes) => ({ changes })), Effect.catch((status) => Effect.succeed({ status })));
3502
+ const reply = (status, attrsset = []) => Effect.map(encodeStatusBody(options.limits, [(writer) => writeBitmap(writer, wordsFor(attrsset))]), (body) => ({ code: operation.code, status, body }));
3503
+ const decoded = yield* setattrAttributes(value.attrs, options.limits, supportedAttributes).pipe(Effect.mapError((error) => error instanceof XdrDecodeError ? Status.BADXDR : error), Effect.map((changes) => ({ changes })), Effect.catch((status) => Effect.succeed({ status })));
3231
3504
  if ("status" in decoded)
3232
- return reply(decoded.status);
3505
+ return yield* reply(decoded.status);
3233
3506
  if (decoded.changes.some((change) => change.kind === "size")) {
3234
3507
  const stateid = isCurrentStateId(value.stateid) ? currentStateid : value.stateid;
3235
3508
  if (stateid === undefined || isAllZero(stateid) || isAllOnes(stateid)) {
3236
- return reply(Status.BAD_STATEID);
3509
+ return yield* reply(Status.BAD_STATEID);
3237
3510
  }
3238
3511
  const key = stateIdKey(stateid);
3239
3512
  const lock = lockStates.get(key);
3240
3513
  const open = opens.get(key) ?? lock?.open;
3241
3514
  if (open === undefined || open.reference !== reference)
3242
- return reply(Status.BAD_STATEID);
3515
+ return yield* reply(Status.BAD_STATEID);
3243
3516
  const stateStatus = lock === undefined
3244
3517
  ? checkOpenStateId(stateid, open)
3245
3518
  : checkLockStateId(stateid, lock);
3246
3519
  if (stateStatus !== Status.OK)
3247
- return reply(stateStatus);
3520
+ return yield* reply(stateStatus);
3248
3521
  if ((open.access & OPEN4_SHARE_ACCESS_WRITE) === 0)
3249
- return reply(Status.OPENMODE);
3522
+ return yield* reply(Status.OPENMODE);
3250
3523
  if ([...opens.values()].some((state) => state.reference === reference && (state.deny & OPEN4_SHARE_ACCESS_WRITE) !== 0))
3251
- return reply(Status.SHARE_DENIED);
3252
- }
3253
- const accessTime = decoded.changes.find((change) => change.attribute === 48);
3254
- const modificationTime = decoded.changes.find((change) => change.attribute === 54);
3255
- for (const change of decoded.changes) {
3256
- if (change.attribute === 54 && accessTime !== undefined)
3257
- continue;
3258
- const mutation = change.kind === "size"
3259
- ? export_.truncate(reference, change.value)
3260
- : change.kind === "mode"
3261
- ? export_.chmod(reference, change.value)
3262
- : change.kind === "owner"
3263
- ? export_.chown(reference, change.attribute === 36 ? { uid: change.value } : { gid: change.value })
3264
- : export_.utimes(reference, {
3265
- access: change.attribute === 48 ? change.value : { kind: "omit" },
3266
- modification: modificationTime?.kind === "time" ? modificationTime.value : { kind: "omit" }
3267
- });
3268
- const status = yield* mutation.pipe(Effect.as(Status.OK), Effect.catch((error) => Effect.succeed(change.kind === "owner" && error.code === "AccessDenied" ? Status.PERM : failureForFs(error))));
3269
- if (status !== Status.OK)
3270
- return reply(status);
3271
- applied.push(change.attribute);
3272
- if (change.attribute === 48 && modificationTime !== undefined)
3273
- applied.push(54);
3524
+ return yield* reply(Status.SHARE_DENIED);
3274
3525
  }
3275
- return reply(Status.OK);
3526
+ // RFC 8881 lets a failed SETATTR report some attributes or none; one setattr applies all
3527
+ // of them or none, so attrsset is empty on failure and complete on success.
3528
+ const status = yield* applySetattr(export_, reference, setattrOptions(decoded.changes)).pipe(Effect.as(Status.OK), Effect.catch((error) => Effect.succeed(error === Status.DELAY ? error : failureForFs(error, operation.code))));
3529
+ return yield* reply(status, status === Status.OK
3530
+ ? decoded.changes.map((change) => change.attribute)
3531
+ : []);
3276
3532
  });
3277
3533
  }
3278
3534
  // Section 15.2 lists NFS4ERR_SYMLINK for LINK but not for CREATE, REMOVE, or RENAME.
@@ -3293,7 +3549,7 @@ export const makeNfs4Handler = (export_, options) => {
3293
3549
  if (!attributes.every((attribute) => supported.includes(attribute))) {
3294
3550
  return yield* Effect.fail(Status.ATTRNOTSUPP);
3295
3551
  }
3296
- const reader = new Reader(value.attrs.values, options.limits);
3552
+ const reader = yield* xdr.openReader(value.attrs.values, options.limits);
3297
3553
  let mode;
3298
3554
  const times = {
3299
3555
  access: { kind: "omit" },
@@ -3301,15 +3557,16 @@ export const makeNfs4Handler = (export_, options) => {
3301
3557
  };
3302
3558
  for (const attribute of attributes) {
3303
3559
  if (attribute === 33) {
3304
- mode = reader.uint32();
3560
+ mode = yield* reader.read(XdrCodec.uint32);
3305
3561
  if (mode > 0o7777)
3306
3562
  return yield* Effect.fail(Status.INVAL);
3307
3563
  }
3308
3564
  else {
3309
- const how = reader.uint32();
3565
+ const how = yield* reader.read(XdrCodec.uint32);
3310
3566
  const time = how === 0 ? { kind: "now" } : {
3311
3567
  kind: "value",
3312
- nanoseconds: BigInt.asIntN(64, reader.uint64()) * 1000000000n + BigInt(reader.uint32())
3568
+ nanoseconds: BigInt.asIntN(64, yield* reader.read(XdrCodec.uint64)) * 1000000000n +
3569
+ BigInt(yield* reader.read(XdrCodec.uint32))
3313
3570
  };
3314
3571
  if (attribute === 48)
3315
3572
  times.access = time;
@@ -3317,20 +3574,18 @@ export const makeNfs4Handler = (export_, options) => {
3317
3574
  times.modification = time;
3318
3575
  }
3319
3576
  }
3320
- reader.finish();
3577
+ yield* reader.finish;
3321
3578
  const result = yield* (value.kind === 2
3322
3579
  ? export_.mkdir(parent, value.name, mode === undefined ? { times } : { mode, times, exactMode: true })
3323
- : export_.symlink(value.target, parent, value.name, { times })).pipe(Effect.mapError((error) => error instanceof ExportCapacityError ?
3324
- Status.DELAY :
3325
- error instanceof InvalidNameError
3326
- ? nameStatus(error)
3327
- : failureForFs(error)));
3580
+ : export_.symlink(value.target, parent, value.name, { times })).pipe(Effect.mapError((error) => error instanceof InvalidNameError
3581
+ ? nameStatus(error, operation.code)
3582
+ : failureForFs(error, operation.code)));
3328
3583
  setCurrent(result.reference);
3329
3584
  return { change: result.directory, attributes };
3330
- }), ({ change, attributes }) => encodeStatusBody((writer) => {
3331
- writeChangeInfo(writer, change);
3332
- writeBitmap(writer, wordsFor(attributes));
3333
- }));
3585
+ }).pipe(Effect.mapError((error) => error instanceof XdrDecodeError ? Status.BADXDR : error)), ({ change, attributes }) => encodeStatusBody(options.limits, [
3586
+ writeChangeInfo(change),
3587
+ (writer) => writeBitmap(writer, wordsFor(attributes))
3588
+ ]));
3334
3589
  }
3335
3590
  case "Remove": {
3336
3591
  if (current === undefined)
@@ -3342,7 +3597,7 @@ export const makeNfs4Handler = (export_, options) => {
3342
3597
  yield* requireDirectory(directory, Status.NOTDIR);
3343
3598
  yield* validName(operation.value);
3344
3599
  return yield* mapFs(export_.remove(directory, operation.value));
3345
- }), (change) => encodeStatusBody((writer) => writeChangeInfo(writer, change)));
3600
+ }), (change) => encodeStatusBody(options.limits, [writeChangeInfo(change)]));
3346
3601
  }
3347
3602
  case "Rename": {
3348
3603
  if (current === undefined || saved === undefined)
@@ -3360,17 +3615,19 @@ export const makeNfs4Handler = (export_, options) => {
3360
3615
  return yield* export_.rename(source, operation.value.oldName, destination, operation.value.newName)
3361
3616
  .pipe(Effect.mapError((error) => error.code === "IsDirectory" || error.code === "NotDirectory" || error.code === "NotEmpty"
3362
3617
  ? Status.EXIST
3363
- : failureForFs(error)));
3364
- }), (change) => encodeStatusBody((writer) => {
3618
+ : failureForFs(error, operation.code)));
3619
+ }), (change) => {
3365
3620
  const sourceChange = Predicate.isTagged(change, "SameDirectory")
3366
3621
  ? change.directory
3367
3622
  : change.sourceDirectory;
3368
3623
  const destinationChange = Predicate.isTagged(change, "SameDirectory")
3369
3624
  ? change.directory
3370
3625
  : change.destinationDirectory;
3371
- writeChangeInfo(writer, sourceChange);
3372
- writeChangeInfo(writer, destinationChange);
3373
- }));
3626
+ return encodeStatusBody(options.limits, [
3627
+ writeChangeInfo(sourceChange),
3628
+ writeChangeInfo(destinationChange)
3629
+ ]);
3630
+ });
3374
3631
  }
3375
3632
  case "Link": {
3376
3633
  if (current === undefined || saved === undefined)
@@ -3383,7 +3640,7 @@ export const makeNfs4Handler = (export_, options) => {
3383
3640
  yield* requireDirectory(destination, Status.SYMLINK);
3384
3641
  yield* validName(operation.value);
3385
3642
  return yield* mapFs(export_.link(source, destination, operation.value));
3386
- }), (result) => encodeStatusBody((writer) => writeChangeInfo(writer, result.directory)));
3643
+ }), (result) => encodeStatusBody(options.limits, [writeChangeInfo(result.directory)]));
3387
3644
  }
3388
3645
  case "NotSupported":
3389
3646
  return Effect.succeed({ code: operation.code, status: Status.NOTSUPP });
@@ -3398,11 +3655,11 @@ export const makeNfs4Handler = (export_, options) => {
3398
3655
  current = reference;
3399
3656
  currentStateid = undefined;
3400
3657
  }
3401
- function parentOf(reference) {
3658
+ function parentOf(reference, operation) {
3402
3659
  // The root has no parent in this export (RFC 8881 Section 18.14.3).
3403
- return export_.parent(reference).pipe(Effect.mapError(failureForFs), Effect.filterOrFail((parent) => parent !== reference, () => Status.NOENT));
3660
+ return export_.parent(reference).pipe(Effect.mapError((error) => failureForFs(error, operation)), Effect.filterOrFail((parent) => parent !== reference, () => Status.NOENT));
3404
3661
  }
3405
- function nameStatus(error) {
3662
+ function nameStatus(error, operation) {
3406
3663
  if (error instanceof InvalidNameError) {
3407
3664
  // RFC 8881 Section 14.5: reserved components are BADNAME, over-long names NAMETOOLONG,
3408
3665
  // valid UTF-8 the file system cannot store (a slash or NUL) BADCHAR, and other
@@ -3418,7 +3675,7 @@ export const makeNfs4Handler = (export_, options) => {
3418
3675
  return Status.INVAL;
3419
3676
  }
3420
3677
  }
3421
- return failureForFs(error);
3678
+ return failureForFs(error, operation);
3422
3679
  }
3423
3680
  function isSpecialStateId(stateid) {
3424
3681
  return isAllZero(stateid) || isAllOnes(stateid) || isCurrentStateId(stateid);
@@ -3459,7 +3716,7 @@ export const makeNfs4Handler = (export_, options) => {
3459
3716
  if (!consumedSequence)
3460
3717
  rollbackSequence?.();
3461
3718
  })));
3462
- }).pipe(Effect.orDie);
3719
+ });
3463
3720
  /**
3464
3721
  * Takes the next free backchannel slot. Section 2.10.6.1 requires slot state even for
3465
3722
  * callbacks, so a slot in flight is never reused for a second concurrent callback.
@@ -3490,11 +3747,14 @@ export const makeNfs4Handler = (export_, options) => {
3490
3747
  // previous value and answering the next callback NFS4ERR_SEQ_MISORDERED forever.
3491
3748
  const sequence = nextSequenceId(back.slots[slot].sequence);
3492
3749
  // Section 20.9.3: csa_highest_slotid is the highest slot the server will use.
3493
- const body = encodeCallbackSequence(session.id, sequence, slot, back.slots.length - 1);
3494
- // Section 18.46.3 has SEQUENCE report an unusable callback path. A reply counts only if
3495
- // the client actually handled the callback: PROG_UNAVAIL, AUTH_ERROR and a rejected
3496
- // CB_SEQUENCE are all well-formed replies from a client with no working path.
3497
- const accepted = yield* Effect.ensuring(callback(session, CB_COMPOUND_PROCEDURE, body, (reply) => callbackAccepted(reply, options.limits, session.id, slot, sequence)), Effect.sync(() => {
3750
+ // Section 18.46.3 has SEQUENCE report an unusable callback path. The slot is released
3751
+ // even if encoding the callback body fails before any bytes are sent.
3752
+ const accepted = yield* Effect.ensuring(Effect.gen(function* () {
3753
+ const encodedBody = yield* Effect.result(encodeCallbackSequence(session.id, sequence, slot, back.slots.length - 1, options.limits));
3754
+ if (Result.isFailure(encodedBody))
3755
+ return false;
3756
+ return yield* callback(session, CB_COMPOUND_PROCEDURE, encodedBody.success, (reply) => callbackAccepted(reply, options.limits, session.id, slot, sequence));
3757
+ }), Effect.sync(() => {
3498
3758
  back.slots[slot].busy = false;
3499
3759
  }));
3500
3760
  // A re-arm while this probe was in flight means its verdict is about a path the client