Crate wnf

source ·
Expand description

GitHub crates.io docs.rs license rustc 1.62+

Safe bindings for the Windows Notification Facility

The Windows Notification Facility (WNF) is a registrationless publisher/subscriber mechanism that was introduced in Windows 8 and forms an undocumented part of the Windows API.

This crate provides safe Rust abstractions over (a part of) this API. If you are looking for raw bindings to the API, take a look at the ntapi crate.

Note that while great care was taken in making these abstractions memory-safe, there cannot be a guarantee due to the undocumented nature of the API.

This is a Windows-only crate and will fail to compile on other platforms. If you target multiple platforms, it is recommended that you declare it as a platform specific dependency.

How WNF works

WNF is built upon the core concept of a state name. Processes can publish to and subscribe to a state name, represented by a 64-bit identifier. In this crate, in order to distinguish between such an identifier and the actual operating system object it represents, we call the identifier a state name, while the underlying object will be referred to as a state.

A state can have different lifetimes:

  • A well-known state is provisioned with the system and cannot be created or deleted.
  • A permanent state can be created and stays alive even across system reboots until it is explicitly deleted.
  • A persistent or volatile state can be created and stays alive until the next system reboot or until it is explicitly deleted.
  • A temporary state can be created and stays alive until the process it was created from exits or until it is explicitly deleted.

For details, see StateLifetime.

A state has an associated payload, called the state data or state value, of up to 4 KB in size. Processes can query and update these data and subscribe to changes of the data. Furthermore, a state has an associated change stamp, which starts at zero when the state is created and increases by one on every update of the data.

A state that lives across system reboots (i.e. with well-known or permanent lifetime) can be configured to persist its data across reboots. Otherwise, the state itself stays alive but its data is reset on reboots.

A state can have different data scopes that control whether it maintains multiple independent instances of its data that are scoped in different ways. See DataScope for the available options.

A state can have an associated type id, which is a GUID that identifies the type of the data. While WNF does not maintain a registry of types itself, it can ensure that state data are only updated if the correct type id is provided. This can be useful if you maintain your own type registry or just want to avoid accidental updates with invalid data.

Access to a state is secured by a standard Windows Security Descriptor. In addition, creating a permanent or persistent state or a state with process scope requires the SeCreatePermanentPrivilege privilege.

The WNF mechanism, though officially undocumented, has been described by various sources. Its API is part of the Windows Native API exposed through ntdll.dll and has been (partly) reverse engineered and described. For details, refer to these sources:

What this crate offers

This crate provides memory-safe abstractions over most of the WNF API to accomplish these tasks:

  • Create and delete a state
  • Query information on a state
  • Query and update state data
  • Subscribe to state data

Subscribing uses higher-level functions from ntdll.dll whose names start with Rtl, standing for runtime library:

  • RtlSubscribeWnfStateChangeNotification
  • RtlUnsubscribeWnfStateChangeNotification

The other features use more low-level functions from ntdll.dll whose names start with Nt*:

  • NtCreateWnfStateName
  • NtDeleteWnfStateName
  • NtQueryWnfStateNameInformation
  • NtQueryWnfStateData
  • NtUpdateWnfStateData

In addition, this crate provides some higher-level abstractions:

  • Apply a transformation to state data
  • Replace state data
  • Wait for updates of state data (in both blocking and async variants)
  • Wait until state data satisfy a certain condition (in both blocking and async variants)

The following WNF features are currently not supported:

  • Subscriptions in meta-notification mode, i.e. subscribing to consumers becoming active or inactive or publishers terminating
  • Event aggregation through the Common Event Aggregator to subscribe to updates of one out of multiple states
  • Kernel mode

Representing states

There are two types in this crate that represent states: OwnedState<T> and BorrowedState<'_, T>. They work in a similar way as the OwnedHandle and BorrowedHandle<'_> types from the standard library:

Note that copying/cloning a BorrowedState<'_, T> just copies the borrow, returning another borrow of the same underlying state, rather than cloning the state itself.

You can abstract over ownership (i.e. whether a state is owned or borrowed) through the AsState trait and its as_state method. This trait is similar to the AsHandle trait in the standard library and is implemented by both OwnedState<T> and BorrowedState<'_, T> as well as any type that derefs to one of these types. Calling as_state on an OwnedState<T> borrows it as a BorrowedState<'_, T> while calling it on a BorrowedState<'_, T> just copies the borrow.

You can obtain an instance of OwnedState<T> or BorrowedState<'_, T> in the following ways:

An owned state can be “leaked” as a statically borrowed state through the OwnedState::leak method, while a borrowed state can be turned into an owned state through the BorrowedState::to_owned_state method.

Representing state data

The types OwnedState<T> and BorrowedState<'_, T> are generic over a type T that describes the shape of the data associated with the state.

The state types themselves impose no trait bounds on the data type. However, in order for querying or updating state data to be memory-safe, the data type needs to satisfy certain conditions:

  • Querying state data as a T requires that any byte slice whose length is the size of T represent a valid T or that it can at least be checked at runtime whether it represents a valid T.
  • Updating state data from a T requires that the type T contain no uninitialized (i.e. padding) bytes.

These conditions cannot be checked at runtime and hence need to be encoded in the type system.

Note that querying state data as a T also requires that the size of the state data match the size of T in the first place, but this condition can be checked at runtime. In fact, the data type can also be a slice type [T], in which case the size of the state data is required to be a multiple of the size of T.

Defining how to properly encode the above conditions in the type system is part of the scope of the Project “safe transmute”, which is still in RFC stage. However, there are various third-party crates that define (unsafe) traits encoding the above conditions, among them being the bytemuck and zerocopy crates. Both of them implement the appropriate traits for many standard types and also provide macros to derive them for your own types, checking at compile-time whether a type satisfies the necessary conditions and enabling you to avoid unsafe code in most cases.

The wnf crate does not have a hard dependency on any of these crates. Instead, it defines its own (unsafe) traits that are modelled after the traits from the bytemuck crate with the same names:

These traits are already implemented for many standard types. In case your code already makes use of one of the bytemuck or zerocopy crates or you want to take advantage of the derive macros provided by either of those crates, you can do the following:

  • Enable the bytemuck_v1 resp. zerocopy feature of this crate (producing a dependency on bytemuck v1 resp. zerocopy)
  • Implement the appropriate trait from one of these crates for your type, e.g. by using a derive macro
  • Derive the corresponding trait from the wnf crate using the derive_from_bytemuck_v1 resp. derive_from_zerocopy macros. See the documentations of these macros for examples.

All methods that query state data require the data type to

In addition, they exist in non-boxed and boxed variants, e.g. OwnedState::get and OwnedState::get_boxed. The non-boxed variants query the data by value (i.e. on the stack), but require the data type T to be Sized. The boxed variants work for both sized and unsized data types T and query the data as a Box<T> (i.e. allocated on the heap). All of this is encapsulated in the Read<T> trait where

  • T: Read<T> means that T can be read by value
  • T: Read<Box<T>> means that T can be read as a box

Note that methods that update state data don’t make a distinction between sized and unsized types/slices or boxed and non-boxed variants because they take the data by reference.

If you want to be able to support arbitrary state data without any restriction on the size (apart from the upper bound of 4 KB), you can always use a byte slice [u8] as the data type. In the rare case that you want to query a state without caring about the content of the data at all, you can use the OpaqueData type. This is useful e.g. if you just want to query the size or if you want to check if you have the right permissions to query the state.

Examples

For more detailed examples, see the examples folder in the crate repository. Some common use cases:

Creating a state and querying/updating its data

use wnf::{CreatableStateLifetime, DataScope, OwnedState, StateCreation};

let state: OwnedState<u32> = StateCreation::new()
    .lifetime(CreatableStateLifetime::Temporary)
    .scope(DataScope::Machine)
    .create_owned()?;

state.set(&42)?;

assert_eq!(state.get()?, 42);

Reading a wide string from a well-known state

use std::ffi::{OsStr, OsString};
use std::os::windows::ffi::OsStringExt;

use wnf::BorrowedState;

const WNF_SHEL_DESKTOP_APPLICATION_STARTED: u64 = 0x0D83063EA3BE5075;

let state = BorrowedState::<[u16]>::from_state_name(WNF_SHEL_DESKTOP_APPLICATION_STARTED);

let last_application_started_wide = {
    let data = state.get_boxed()?;
    OsString::from_wide(&data)
};

println!("{}", last_application_started_wide.to_string_lossy());

Subscribing to a well-known state

This requires the subscribe feature flag to be enabled.

use std::io::{stdin, Read};

use wnf::{BorrowedState, DataAccessor, OwnedState, SeenChangeStamp};

const WNF_PO_DISCHARGE_ESTIMATE: u64 = 0x41C6013DA3BC5075;

let state = BorrowedState::<u64>::from_state_name(WNF_PO_DISCHARGE_ESTIMATE);

let subscription = state.subscribe(
    |accessor: DataAccessor<'_, _>| {
        println!("Estimated battery duration in seconds: {}", accessor.get().unwrap());
    },
    SeenChangeStamp::Current,
)?;

stdin().read_exact(&mut [0u8])?; // wait for keypress

subscription.unsubscribe()?;

Tracing

This crate emits diagnostic information using the tracing crate whenever there is an interaction with the WNF API. For guidance on how to subscribe to this information, consult the tracing documentation. The general structure is like this:

  • For every invocation of a WNF API function by the wnf crate, an Event with the following payload is emitted:
    • The target is always wnf::ntapi.
    • The level is DEBUG.
    • The message is the name of the WNF API routine.
    • The fields consist of three groups:
      • result: The result (return code) of the invocation
      • input.*: Inputs of the invocation, depending on the routine
      • output.*: Outputs of the invocation, depending on the routine
  • For every invocation of a callback function in the wnf crate, a Span with the following payload is emitted:
    • The target is always wnf::ntapi.
    • The level is TRACE.
    • The name is WnfUserCallback.
    • The fields are all named input.* and contain the inputs of the invocation.

See the examples folder in the crate repository for examples on how to subscribe to these events and spans.

Cargo features

This crate has various feature flags, none of which are enabled by default. They fall into two groups:

  • Features enabling compatibility with other crates:

  • Features enabling functionality that uses the higher-level Rtl* functions from ntdll.dll (see above):

    • subscribe: Enables subscribing to state updates
    • wait_blocking: Enables blocking waits for state updates, implies the subscribe feature
    • wait_async: Enables async waits for state updates, implies the subscribe feature

Stability

Since this crate depends on the WNF API, which is undocumented and hence must be considered unstable, it will probably stay on an unstable 0.x version forever.

Minimum Supported Rust Version (MSRV) Policy

The current MSRV of this crate is 1.62.

Increasing the MSRV of this crate is not considered a breaking change. However, in such cases there will be at least a minor version bump.

Each version of this crate will support at least the four latest stable Rust versions at the time it is published.

Macros

Macro for deriving wnf traits from bytemuck traits
Macro for deriving wnf traits from zerocopy traits

Structs

A borrowed state
An owned security descriptor allocated on the local heap
The change stamp of a state
DataAccessorsubscribe
A handle to state data passed to state listeners
A Globally Unique Identifier (GUID)
A placeholder for state data whose content is irrelevant
An owned state
A Windows security descriptor
State data together with a change stamp
A builder type for creating states
A state name
The descriptor of a state name
Subscriptionsubscribe
A subscription of a listener to updates of a state
A marker type for an unspecified lifetime when creating a state
A marker type for an unspecified scope when creating a state
A marker type for an unspecified security descriptor when creating a state
Waitwait_async
The future returned by wait_async methods
WaitUntilwait_async
The future returned by wait_until_async methods
WaitUntilBoxedwait_async
The future returned by wait_until_boxed_async methods

Enums

The lifetime of a state when specified upon creation
The data scope of a state
An error reading state data
The change stamp that a state listener has last seen
The lifetime of a state

Constants

The maximum size of a state in bytes

Traits

A marker trait for types for which any bit pattern is valid
A trait for types that can be borrowed as a state
A trait for types that can be checked for valid bit patterns at runtime
A marker trait for types without uninitialized (padding) bytes
A trait for types that can be read from state data
StateListenersubscribe
A trait for types that are capable of listening to state updates
A trait for types that can be fallibly converted into a security descriptor

Functions

Returns whether the current process has the SeCreatePermanentPrivilege privilege