Skip to content

std.crypto.Certificate.Bundle.macos

Standard libraryZig 0.17.0Official documentation
Sourcestd/crypto/Certificate/Bundle/macos.zig

Source line 1

std.crypto.Certificate.Bundle.macos.Allocator

alias

Source line 6

Alias of std.mem.Allocator

std.crypto.Certificate.Bundle.macos.ApplDbHeader

container

Source line 90

Fields

signature: [4]u8
version: u32
header_size: u32
schema_offset: u32
auth_offset: u32

std.crypto.Certificate.Bundle.macos.ApplDbSchema

container

Source line 98

Fields

schema_size: u32
table_count: u32

std.crypto.Certificate.Bundle.macos.assert

alias

Source line 3

Alias of std.debug.assert

std.crypto.Certificate.Bundle.macos.Bundle

alias

Source line 7

Alias of std.crypto.Certificate.Bundle

std.crypto.Certificate.Bundle.macos.fs

alias

Source line 4

Alias of std.fs

std.crypto.Certificate.Bundle.macos.Io

alias

Source line 2

Alias of std.Io

std.crypto.Certificate.Bundle.macos.mem

alias

Source line 5

Alias of std.mem

std.crypto.Certificate.Bundle.macos.rescanMac

function

Source line 11

pub fn rescanMac(cb: *Bundle, gpa: Allocator, io: Io, now: Io.Timestamp) RescanMacError!void

Parameters

cb: *Bundle
gpa: Allocator
io: Io
now: Io.Timestamp

Errors

AccessDenied OpenError

In WASI, this error may occur when the file descriptor does not hold the required rights to open a new resource relative to it.

AntivirusInterference OpenError

On Windows, antivirus software is enabled by default. It can be disabled, but Windows Update sometimes ignores the user's preference and re-enables it. When enabled, antivirus software on Windows intercepts file system operations and makes them significantly slower in addition to possibly failing with this error code.

BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

CertificateFieldHasInvalidLength ParseError
CertificateFieldHasWrongDataType ParseTimeError
CertificateHasInvalidBitString ParseBitStringError
CertificateHasUnrecognizedObjectId ParseEnumError
CertificateTimeInvalid ParseTimeError
ConnectionResetByPeer UnendingError
DeviceBusy OpenError
EndOfStream
FileBusy OpenError

One of these three things:

  • pathname refers to an executable image which is currently being executed and write access was requested.
  • pathname refers to a file that is currently in use as a swap file, and the O_TRUNC flag was specified.
  • pathname refers to a file that is currently being read by the kernel (e.g., for module/firmware loading), and write access was requested.
FileLocksUnsupported OpenError
FileNotFound OpenError

Either:

  • One of the path components does not exist.
  • Cwd was used, but cwd has been deleted.
  • The path associated with the open directory handle has been deleted.
  • On macOS, multiple processes or threads raced to create the same file with O.EXCL set to false.
FileTooBig OpenError

The file is too large to be opened. This error is unreachable for 64-bit targets, as well as when opening directories.

InputOutput UnendingError
IsDir OpenError

Either:

  • The path refers to a directory and write permissions were requested.
  • The path refers to a directory and allow_directory was set to false.
LockViolation UnendingError

Unable to read file due to lock. Depending on the Io implementation, reading from a locked file may return this error, or may ignore the lock.

NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NetworkNotFound OpenError

On Windows, \\server or \\server\share was not found.

NoDevice OpenError
NoSpaceLeft OpenError

A new path cannot be created because the device has no room for the new file. This error is only reachable when the CREAT flag is provided.

NotDir OpenError

A component used as a directory in the path was not, in fact, a directory, or DIRECTORY was specified and the path was not a directory.

NotOpenForReading UnendingError

File was not opened with read capability.

OutOfMemory Error
PathAlreadyExists OpenError

The path already exists and the CREAT and EXCL flags were provided.

PermissionDenied OpenError
PipeBusy OpenError
ProcessFdQuotaExceeded OpenError
ReadOnlyFileSystem OpenError
SocketUnconnected UnendingError
SymLinkLoop OpenError
SystemFdQuotaExceeded OpenError
SystemResources OpenError

The path exceeded max_path_bytes bytes. Insufficient kernel memory was available, or the named file is a FIFO and per-user hard limit on memory allocation for pipes has been reached.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

Unseekable SeekError
UnsupportedCertificateVersion ParseVersionError
WouldBlock OpenError

Non-blocking was requested and the operation cannot return immediately.

std.crypto.Certificate.Bundle.macos.RescanMacError

error-set

Source line 9

Errors

AccessDenied OpenError

In WASI, this error may occur when the file descriptor does not hold the required rights to open a new resource relative to it.

AntivirusInterference OpenError

On Windows, antivirus software is enabled by default. It can be disabled, but Windows Update sometimes ignores the user's preference and re-enables it. When enabled, antivirus software on Windows intercepts file system operations and makes them significantly slower in addition to possibly failing with this error code.

BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

CertificateFieldHasInvalidLength ParseError
CertificateFieldHasWrongDataType ParseTimeError
CertificateHasInvalidBitString ParseBitStringError
CertificateHasUnrecognizedObjectId ParseEnumError
CertificateTimeInvalid ParseTimeError
ConnectionResetByPeer UnendingError
DeviceBusy OpenError
EndOfStream
FileBusy OpenError

One of these three things:

  • pathname refers to an executable image which is currently being executed and write access was requested.
  • pathname refers to a file that is currently in use as a swap file, and the O_TRUNC flag was specified.
  • pathname refers to a file that is currently being read by the kernel (e.g., for module/firmware loading), and write access was requested.
FileLocksUnsupported OpenError
FileNotFound OpenError

Either:

  • One of the path components does not exist.
  • Cwd was used, but cwd has been deleted.
  • The path associated with the open directory handle has been deleted.
  • On macOS, multiple processes or threads raced to create the same file with O.EXCL set to false.
FileTooBig OpenError

The file is too large to be opened. This error is unreachable for 64-bit targets, as well as when opening directories.

InputOutput UnendingError
IsDir OpenError

Either:

  • The path refers to a directory and write permissions were requested.
  • The path refers to a directory and allow_directory was set to false.
LockViolation UnendingError

Unable to read file due to lock. Depending on the Io implementation, reading from a locked file may return this error, or may ignore the lock.

NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NetworkNotFound OpenError

On Windows, \\server or \\server\share was not found.

NoDevice OpenError
NoSpaceLeft OpenError

A new path cannot be created because the device has no room for the new file. This error is only reachable when the CREAT flag is provided.

NotDir OpenError

A component used as a directory in the path was not, in fact, a directory, or DIRECTORY was specified and the path was not a directory.

NotOpenForReading UnendingError

File was not opened with read capability.

OutOfMemory Error
PathAlreadyExists OpenError

The path already exists and the CREAT and EXCL flags were provided.

PermissionDenied OpenError
PipeBusy OpenError
ProcessFdQuotaExceeded OpenError
ReadOnlyFileSystem OpenError
SocketUnconnected UnendingError
SymLinkLoop OpenError
SystemFdQuotaExceeded OpenError
SystemResources OpenError

The path exceeded max_path_bytes bytes. Insufficient kernel memory was available, or the named file is a FIFO and per-user hard limit on memory allocation for pipes has been reached.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

Unseekable SeekError
UnsupportedCertificateVersion ParseVersionError
WouldBlock OpenError

Non-blocking was requested and the operation cannot return immediately.

std.crypto.Certificate.Bundle.macos.scanReader

function

Source line 37

fn scanReader(cb: *Bundle, gpa: Allocator, reader: *Io.Reader, now_sec: i64) !void

Parameters

cb: *Bundle
gpa: Allocator
reader: *Io.Reader
now_sec: i64

std.crypto.Certificate.Bundle.macos.std

alias

Source line 1

Alias of std

std.crypto.Certificate.Bundle.macos.TableHeader

container

Source line 103

Fields

table_size: u32
table_id: u32
record_count: u32
records: u32
indexes_offset: u32
free_list_head: u32
record_numbers_count: u32

std.crypto.Certificate.Bundle.macos.X509CertHeader

container

Source line 113

Fields

record_size: u32
record_number: u32
unknown1: u32
unknown2: u32
cert_size: u32
unknown3: u32
cert_type: u32
cert_encoding: u32
print_name: u32
alias: u32
subject: u32
issuer: u32
serial_number: u32
subject_key_identifier: u32
public_key_hash: u32
Source code

std/crypto/Certificate/Bundle/macos.zig

const std = @import("std");
const Io = std.Io;
const assert = std.debug.assert;
const fs = std.fs;
const mem = std.mem;
const Allocator = std.mem.Allocator;
const Bundle = @import("../Bundle.zig");

pub const RescanMacError = Allocator.Error || Io.File.OpenError || Io.File.Reader.Error || Io.File.SeekError || Bundle.ParseCertError || error{EndOfStream};

pub fn rescanMac(cb: *Bundle, gpa: Allocator, io: Io, now: Io.Timestamp) RescanMacError!void {
    cb.bytes.clearRetainingCapacity();
    cb.map.clearRetainingCapacity();

    const keychain_paths = [2][]const u8{
        "/System/Library/Keychains/SystemRootCertificates.keychain",
        "/Library/Keychains/System.keychain",
    };

    for (keychain_paths) |keychain_path| {
        const bytes = Io.Dir.cwd().readFileAlloc(io, keychain_path, gpa, .limited(std.math.maxInt(u32))) catch |err| switch (err) {
            error.StreamTooLong => return error.FileTooBig,
            else => |e| return e,
        };
        defer gpa.free(bytes);

        var reader: Io.Reader = .fixed(bytes);
        scanReader(cb, gpa, &reader, now.toSeconds()) catch |err| switch (err) {
            error.ReadFailed => unreachable, // prebuffered
            else => |e| return e,
        };
    }

    cb.bytes.shrinkAndFree(gpa, cb.bytes.items.len);
}

fn scanReader(cb: *Bundle, gpa: Allocator, reader: *Io.Reader, now_sec: i64) !void {
    const db_header = try reader.takeStruct(ApplDbHeader, .big);
    assert(mem.eql(u8, &db_header.signature, "kych"));

    reader.seek = db_header.schema_offset;

    const db_schema = try reader.takeStruct(ApplDbSchema, .big);

    var table_list = try gpa.alloc(u32, db_schema.table_count);
    defer gpa.free(table_list);

    var table_idx: u32 = 0;
    while (table_idx < table_list.len) : (table_idx += 1) {
        table_list[table_idx] = try reader.takeInt(u32, .big);
    }

    for (table_list) |table_offset| {
        reader.seek = db_header.schema_offset + table_offset;

        const table_header = try reader.takeStruct(TableHeader, .big);

        if (@as(std.c.DB_RECORDTYPE, @fromBackingInt(@intCast(table_header.table_id))) != .X509_CERTIFICATE) {
            continue;
        }

        var record_list = try gpa.alloc(u32, table_header.record_count);
        defer gpa.free(record_list);

        var record_idx: u32 = 0;
        while (record_idx < record_list.len) : (record_idx += 1) {
            record_list[record_idx] = try reader.takeInt(u32, .big);
        }

        for (record_list) |record_offset| {
            // An offset of zero means that the record is not present.
            // An offset that is not 4-byte-aligned is invalid.
            if (record_offset == 0 or record_offset % 4 != 0) continue;

            reader.seek = db_header.schema_offset + table_offset + record_offset;

            const cert_header = try reader.takeStruct(X509CertHeader, .big);

            if (cert_header.cert_size == 0) continue;

            const cert_start: u32 = @intCast(cb.bytes.items.len);
            const dest_buf = try cb.bytes.addManyAsSlice(gpa, cert_header.cert_size);
            try reader.readSliceAll(dest_buf);

            try cb.parseCert(gpa, cert_start, now_sec);
        }
    }
}

const ApplDbHeader = extern struct {
    signature: [4]u8,
    version: u32,
    header_size: u32,
    schema_offset: u32,
    auth_offset: u32,
};

const ApplDbSchema = extern struct {
    schema_size: u32,
    table_count: u32,
};

const TableHeader = extern struct {
    table_size: u32,
    table_id: u32,
    record_count: u32,
    records: u32,
    indexes_offset: u32,
    free_list_head: u32,
    record_numbers_count: u32,
};

const X509CertHeader = extern struct {
    record_size: u32,
    record_number: u32,
    unknown1: u32,
    unknown2: u32,
    cert_size: u32,
    unknown3: u32,
    cert_type: u32,
    cert_encoding: u32,
    print_name: u32,
    alias: u32,
    subject: u32,
    issuer: u32,
    serial_number: u32,
    subject_key_identifier: u32,
    public_key_hash: u32,
};