qleisli 0.2.8

Experimental quantum language with linear ownership, exact contracts and independent finite IR verification
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
//! Open discovered sources without following a replacement symlink.
//!
//! macOS 11+ uses O_NOFOLLOW_ANY without requiring read access to ancestors.
//! Older macOS walks components with descriptor-relative openat and O_NOFOLLOW;
//! this compatible fallback also requires read access to ancestors. On the
//! Linux architectures below, procfs supplies descriptor-relative paths with
//! search-only ancestors. Walks keep each parent open until its child is
//! acquired without following links. Other targets retain
//! the legacy filesystem trust assumption. This is not a filesystem sandbox or
//! a guarantee against concurrent writes to an already open regular file.
use std::fs::File;
#[cfg(not(target_os = "macos"))]
use std::fs::OpenOptions;
use std::io;
use std::path::Path;

pub(super) fn open(path: &Path) -> io::Result<File> {
    let file = open_platform(path, false)?;
    if !file.metadata()?.is_file() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "source must be a regular file",
        ));
    }
    Ok(file)
}

/// Acquire a non-symlink directory through the same component walk as sources.
pub(super) fn open_directory(path: &Path) -> io::Result<File> {
    let file = open_platform(path, true)?;
    if !file.metadata()?.is_dir() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "source root is not a directory",
        ));
    }
    Ok(file)
}

#[cfg(target_os = "macos")]
fn open_platform(path: &Path, is_directory: bool) -> io::Result<File> {
    open_macos(
        path,
        is_directory,
        macos_has_nofollow_any(rustix::system::uname().release().to_bytes()),
    )
}

#[cfg(target_os = "macos")]
fn macos_has_nofollow_any(release: &[u8]) -> bool {
    // Darwin 20 is macOS 11. uname is available on the old deployment target;
    // never pass the new flag on an unknown or pre-11 runtime.
    std::str::from_utf8(release)
        .ok()
        .and_then(|s| s.split('.').next())
        .and_then(|major| major.parse::<u32>().ok())
        .is_some_and(|major| major >= 20)
}

#[cfg(target_os = "macos")]
fn open_macos(path: &Path, is_directory: bool, nofollow_any: bool) -> io::Result<File> {
    use rustix::fs::{Mode, OFlags};
    use std::path::Component;
    let absolute = if path.is_absolute() {
        path.to_owned()
    } else {
        std::env::current_dir()?.join(path)
    };
    if absolute
        .components()
        .any(|c| matches!(c, Component::ParentDir))
    {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "source path must not contain parent traversal",
        ));
    }
    if nofollow_any {
        // Darwin 20 SDK O_NOFOLLOW_ANY. rustix 1.1.3 does not expose this bit.
        // The kernel rejects symlinks anywhere in the path atomically; only
        // the final file/directory is opened for reading. NONBLOCK also keeps
        // a replacement FIFO from waiting before the regular-file check.
        let flags = OFlags::from_bits_retain(0x20000000)
            | OFlags::RDONLY
            | OFlags::NONBLOCK
            | OFlags::CLOEXEC;
        let flags = if is_directory {
            flags | OFlags::DIRECTORY
        } else {
            flags
        };
        return Ok(File::from(rustix::fs::open(
            &absolute,
            flags,
            Mode::empty(),
        )?));
    }
    let mut directory = File::from(rustix::fs::open(
        "/",
        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
        Mode::empty(),
    )?);
    let mut components = absolute.components().peekable();
    while let Some(component) = components.next() {
        let name = match component {
            Component::RootDir | Component::CurDir => continue,
            Component::Normal(name) => name,
            _ => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "source path must not contain parent traversal",
                ));
            }
        };
        let file = open_macos_child(
            &directory,
            name,
            is_directory || components.peek().is_some(),
        )?;
        if components.peek().is_none() {
            return Ok(file);
        }
        directory = file;
    }
    if is_directory {
        return Ok(directory);
    }
    Err(io::Error::new(
        io::ErrorKind::InvalidInput,
        "source path has no file name",
    ))
}

#[cfg(target_os = "macos")]
fn open_macos_child(
    directory: &File,
    name: &std::ffi::OsStr,
    is_directory: bool,
) -> io::Result<File> {
    use rustix::fs::{Mode, OFlags};
    // Every call receives one component and a held parent. NONBLOCK prevents a
    // replacement FIFO from blocking before the regular-file metadata check.
    let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC;
    let flags = if is_directory {
        flags | OFlags::DIRECTORY
    } else {
        flags
    };
    Ok(File::from(rustix::fs::openat(
        directory,
        name,
        flags,
        Mode::empty(),
    )?))
}

#[cfg(all(
    target_os = "linux",
    any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm",
        target_arch = "riscv64",
        target_arch = "riscv32"
    )
))]
fn open_platform(path: &Path, is_directory: bool) -> io::Result<File> {
    open_linux(path, Path::new("/proc/self/fd"), is_directory)
}

#[cfg(all(
    target_os = "linux",
    any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm",
        target_arch = "riscv64",
        target_arch = "riscv32"
    )
))]
fn open_linux(path: &Path, procfs: &Path, is_directory: bool) -> io::Result<File> {
    use std::os::unix::fs::OpenOptionsExt;
    use std::path::Component;
    // Linux UAPI asm-generic/fcntl.h on these architectures.
    const NOFOLLOW: i32 = 0o400000;
    const DIRECTORY: i32 = 0o200000;
    const NONBLOCK: i32 = 0o4000;
    const PATH_ONLY: i32 = 0o10000000;
    let absolute = if path.is_absolute() {
        path.to_owned()
    } else {
        std::env::current_dir()?.join(path)
    };
    let mut directory = OpenOptions::new()
        .read(true)
        .custom_flags(DIRECTORY | PATH_ONLY)
        .open("/")?;
    // Diagnose a missing/inaccessible descriptor filesystem separately from a
    // missing source. Check the actual held descriptor, not just /proc itself.
    procfs_directory(&directory, procfs)?;
    let mut components = absolute.components().peekable();
    while let Some(component) = components.next() {
        let name = match component {
            Component::RootDir | Component::CurDir => continue,
            Component::Normal(name) => name,
            _ => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "source path must not contain parent traversal",
                ));
            }
        };
        let child = procfs_directory(&directory, procfs)?.join(name);
        let flags = NOFOLLOW
            | NONBLOCK
            | if is_directory || components.peek().is_some() {
                DIRECTORY | PATH_ONLY
            } else {
                0
            };
        let file = OpenOptions::new()
            .read(true)
            .custom_flags(flags)
            .open(child)?;
        if components.peek().is_none() {
            return Ok(file);
        }
        // The parent stays open until the child has been acquired atomically.
        directory = file;
    }
    if is_directory {
        return Ok(directory);
    }
    Err(io::Error::new(
        io::ErrorKind::InvalidInput,
        "source path has no file name",
    ))
}

// The injected descriptor root is private and only used by regression tests;
// production never falls back to following the original pathname.
#[cfg(any(
    all(test, unix),
    all(
        target_os = "linux",
        any(
            target_arch = "x86",
            target_arch = "x86_64",
            target_arch = "aarch64",
            target_arch = "arm",
            target_arch = "riscv64",
            target_arch = "riscv32"
        )
    )
))]
fn procfs_directory(directory: &File, procfs: &Path) -> io::Result<std::path::PathBuf> {
    use std::os::fd::AsRawFd;
    let path = procfs.join(directory.as_raw_fd().to_string());
    let unavailable = |cause: String| {
        io::Error::new(
            io::ErrorKind::Unsupported,
            format!(
                "Linux source loading requires accessible procfs descriptors at {}: {cause}",
                procfs.display()
            ),
        )
    };
    let metadata = std::fs::metadata(&path).map_err(|e| unavailable(e.to_string()))?;
    if !metadata.is_dir() {
        return Err(unavailable(
            "held directory descriptor is not accessible as a directory".into(),
        ));
    }
    Ok(path)
}

#[cfg(not(any(
    target_os = "macos",
    all(
        target_os = "linux",
        any(
            target_arch = "x86",
            target_arch = "x86_64",
            target_arch = "aarch64",
            target_arch = "arm",
            target_arch = "riscv64",
            target_arch = "riscv32"
        )
    )
)))]
fn open_platform(path: &Path, is_directory: bool) -> io::Result<File> {
    let mut options = OpenOptions::new();
    options.read(true);
    #[cfg(windows)]
    if is_directory {
        use std::os::windows::fs::OpenOptionsExt;
        // Required to acquire directory handles on Windows. Other targets
        // retain the existing filesystem trust assumption for symlinks.
        options.custom_flags(0x02000000); // FILE_FLAG_BACKUP_SEMANTICS
    }
    #[cfg(not(windows))]
    let _ = is_directory;
    options.open(path)
}

#[cfg(all(
    test,
    any(
        target_os = "macos",
        all(
            target_os = "linux",
            any(
                target_arch = "x86",
                target_arch = "x86_64",
                target_arch = "aarch64",
                target_arch = "arm",
                target_arch = "riscv64",
                target_arch = "riscv32"
            )
        )
    )
))]
mod tests {
    use super::*;
    use std::fs;
    use std::os::unix::fs::symlink;
    use std::sync::atomic::{AtomicU64, Ordering};
    static NEXT: AtomicU64 = AtomicU64::new(0);

    #[cfg(target_os = "macos")]
    struct MacosDirectory(std::path::PathBuf);

    #[cfg(target_os = "macos")]
    impl MacosDirectory {
        fn new() -> Self {
            let path = std::env::temp_dir().join(format!(
                "qleisli-macos-openat-{}-{}",
                std::process::id(),
                NEXT.fetch_add(1, Ordering::Relaxed)
            ));
            fs::create_dir(&path).unwrap();
            Self(fs::canonicalize(path).unwrap())
        }
    }

    #[cfg(target_os = "macos")]
    impl Drop for MacosDirectory {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_nofollow_any_is_gated_by_runtime_version() {
        for release in [
            b"19.6.0".as_slice(),
            b"16.7.0",
            b"",
            b"unknown",
            b"999999999999",
        ] {
            assert!(!macos_has_nofollow_any(release));
        }
        for release in [b"20.0.0".as_slice(), b"21.6.0", b"25.0.0"] {
            assert!(macos_has_nofollow_any(release));
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_legacy_walk_rejects_links_and_retains_read_requirement() {
        use std::os::unix::fs::PermissionsExt;
        let root = MacosDirectory::new();
        fs::create_dir(root.0.join("nested")).unwrap();
        let source = root.0.join("nested/main.qli");
        fs::write(&source, "original").unwrap();
        assert!(open_macos(&source, false, false).is_ok());
        fs::set_permissions(&root.0, fs::Permissions::from_mode(0o100)).unwrap();
        let denied = File::open(&root.0).is_err();
        let result = open_macos(&source, false, false);
        fs::set_permissions(&root.0, fs::Permissions::from_mode(0o700)).unwrap();
        if denied {
            assert_eq!(result.unwrap_err().kind(), io::ErrorKind::PermissionDenied);
        }
        fs::rename(root.0.join("nested"), root.0.join("renamed")).unwrap();
        symlink(root.0.join("renamed"), root.0.join("nested")).unwrap();
        assert!(open_macos(&source, false, false).is_err());
        let saved = root.0.join("renamed/main.qli");
        fs::remove_file(&saved).unwrap();
        symlink(root.0.join("missing"), &saved).unwrap();
        assert!(open_macos(&saved, false, false).is_err());
        fs::remove_file(&saved).unwrap();
        assert!(
            std::process::Command::new("mkfifo")
                .arg(&saved)
                .status()
                .unwrap()
                .success()
        );
        assert!(
            !open_macos(&saved, false, false)
                .unwrap()
                .metadata()
                .unwrap()
                .is_file()
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_openat_retains_parent_identity_after_path_replacement() {
        use std::io::Read;
        let root = MacosDirectory::new();
        fs::create_dir(root.0.join("nested")).unwrap();
        fs::write(root.0.join("nested/main.qli"), "original").unwrap();
        fs::create_dir(root.0.join("replacement")).unwrap();
        fs::write(root.0.join("replacement/main.qli"), "replacement").unwrap();
        let held =
            open_macos_child(&File::open(&root.0).unwrap(), "nested".as_ref(), true).unwrap();
        fs::rename(root.0.join("nested"), root.0.join("renamed")).unwrap();
        symlink(root.0.join("replacement"), root.0.join("nested")).unwrap();
        let mut original = open_macos_child(&held, "main.qli".as_ref(), false).unwrap();
        let mut text = String::new();
        original.read_to_string(&mut text).unwrap();
        assert_eq!(text, "original");
        assert!(open(&root.0.join("nested/main.qli")).is_err());
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_fifo_source_replacement_is_rejected_without_a_writer() {
        let root = MacosDirectory::new();
        let source = root.0.join("main.qli");
        fs::write(&source, "original").unwrap();
        let mut discovered = vec![];
        assert!(super::super::collect_qli_files(&root.0, &mut discovered).is_ok());
        assert_eq!(discovered.as_slice(), std::slice::from_ref(&source));
        fs::remove_file(&source).unwrap();
        assert!(
            std::process::Command::new("mkfifo")
                .arg(&source)
                .status()
                .unwrap()
                .success()
        );
        assert_eq!(
            open(&source).unwrap_err().kind(),
            io::ErrorKind::InvalidInput
        );
    }

    #[test]
    fn unavailable_linux_procfs_has_a_targeted_diagnostic() {
        let root = std::env::temp_dir().join(format!(
            "qleisli-procfs-{}-{}",
            std::process::id(),
            NEXT.fetch_add(1, Ordering::Relaxed)
        ));
        fs::create_dir(&root).unwrap();
        struct Cleanup(std::path::PathBuf);
        impl Drop for Cleanup {
            fn drop(&mut self) {
                let _ = fs::remove_dir_all(&self.0);
            }
        }
        let _cleanup = Cleanup(root.clone());
        fs::write(root.join("file"), "not a descriptor directory").unwrap();
        for procfs in [root.join("absent"), root.join("file")] {
            let directory = File::open("/").unwrap();
            let error = procfs_directory(&directory, &procfs).unwrap_err();
            assert_eq!(error.kind(), io::ErrorKind::Unsupported);
            assert!(
                error
                    .to_string()
                    .contains("Linux source loading requires accessible procfs descriptors"),
                "{error}"
            );
            assert!(error.to_string().contains(&procfs.display().to_string()));
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn missing_linux_source_is_not_misreported_as_missing_procfs() {
        let root = std::env::temp_dir().join(format!(
            "qleisli-missing-source-{}-{}",
            std::process::id(),
            NEXT.fetch_add(1, Ordering::Relaxed)
        ));
        let error = open(&root.join("main.qli")).unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::NotFound);
        assert!(!error.to_string().contains("procfs"));
    }

    #[test]
    fn source_replacement_between_discovery_and_open_cannot_follow_links() {
        let path = std::env::temp_dir().join(format!(
            "qleisli-source-open-{}-{}",
            std::process::id(),
            NEXT.fetch_add(1, Ordering::Relaxed)
        ));
        fs::create_dir(&path).unwrap();
        struct Cleanup(std::path::PathBuf);
        impl Drop for Cleanup {
            fn drop(&mut self) {
                let _ = fs::remove_dir_all(&self.0);
            }
        }
        let _cleanup = Cleanup(path.clone());
        let root = fs::canonicalize(path).unwrap();
        fs::create_dir(root.join("nested")).unwrap();
        fs::write(root.join("nested/main.qli"), "original").unwrap();
        fs::write(root.join("outside"), "replacement").unwrap();
        let mut discovered = vec![];
        assert!(super::super::collect_qli_files(&root, &mut discovered).is_ok());
        assert_eq!(discovered, [root.join("nested/main.qli")]);
        let source = &discovered[0];
        let original = open(source).unwrap();
        fs::rename(source, root.join("original")).unwrap();
        symlink(root.join("outside"), source).unwrap();
        assert!(open(source).is_err());
        // An already acquired descriptor still identifies the original file.
        use std::io::Read;
        let mut text = String::new();
        (&original).read_to_string(&mut text).unwrap();
        assert_eq!(text, "original");
        fs::remove_file(source).unwrap();
        fs::write(source, "original").unwrap();
        fs::rename(root.join("nested"), root.join("renamed")).unwrap();
        symlink(root.join("renamed"), root.join("nested")).unwrap();
        assert!(
            open(source).is_err(),
            "an intermediate replacement must also be rejected"
        );
        assert!(
            open(&root.join("renamed")).is_err(),
            "directories are not sources"
        );
        assert!(open(&root.join("original")).is_ok());
    }
}