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
use crate::co;
use crate::decl::*;
use crate::kernel::{ffi_types::*, privs::*};

/// Variable parameter for:
///
/// * [`CLAIM_SECURITY_ATTRIBUTE_V1`](crate::CLAIM_SECURITY_ATTRIBUTE_V1).
pub enum ClaimSecurityAttr<'a> {
	Int64(&'a [i64]),
	Uint64(&'a [u64]),
	String(Vec<String>),
	Fbqn(&'a [CLAIM_SECURITY_ATTRIBUTE_FQBN_VALUE<'a>]),
	OctetString(&'a [CLAIM_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE<'a>]),
}

/// Variable parameter for:
///
/// * [`HACCESSTOKEN::AdjustTokenPrivileges`](crate::prelude::kernel_Haccesstoken::AdjustTokenPrivileges).
pub enum DisabPriv<'a> {
	/// Disables all privileges.
	Disab,
	/// An array of privileges and its attributes.
	Privs(&'a TOKEN_PRIVILEGES)
}

/// A resource identifier.
///
/// Variable parameter for:
///
/// * [`HINSTANCE::CreateDialogParam`](crate::prelude::user_Hinstance::CreateDialogParam);
/// * [`HINSTANCE::EnumResourceLanguages`](crate::prelude::kernel_Hinstance::EnumResourceLanguages);
/// * [`HINSTANCE::EnumResourceNames`](crate::prelude::kernel_Hinstance::EnumResourceNames);
/// * [`HINSTANCE::FindResource`](crate::prelude::kernel_Hinstance::FindResource);
/// * [`HINSTANCE::FindResourceEx`](crate::prelude::kernel_Hinstance::FindResourceEx);
/// * [`HINSTANCE::LoadAccelerators`](crate::prelude::user_Hinstance::LoadAccelerators);
/// * [`HINSTANCE::LoadMenu`](crate::prelude::user_Hinstance::LoadMenu);
/// * [`HUPDATERSRC::UpdateResource`](crate::prelude::kernel_Hupdatersrc::UpdateResource);
/// * [`BmpIdbRes`](crate::BmpIdbRes);
/// * [`IconRes`](crate::IconRes);
/// * [`ResStrs`](crate::ResStrs).
#[derive(Clone)]
pub enum IdStr {
	/// A resource ID.
	Id(u16),
	/// A resource string identifier.
	Str(WString),
}

impl std::fmt::Display for IdStr {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			Self::Id(rt) => write!(f, "ID: {}", rt),
			Self::Str(str) => write!(f, "Str: {}", str),
		}
	}
}

impl IdStr {
	/// Constructs the enum directly from a string.
	#[must_use]
	pub fn from_str(v: &str) -> Self {
		Self::Str(WString::from_str(v))
	}

	/// Constructs the enum from a raw pointer.
	///
	/// # Safety
	///
	/// If string, be sure it is null-terminated, otherwise an invalid memory
	/// location might be read.
	#[must_use]
	pub unsafe fn from_ptr(ptr: *const u16) -> IdStr {
		if IS_INTRESOURCE(ptr) {
			Self::Id(ptr as _)
		} else {
			Self::Str(WString::from_wchars_nullt(ptr))
		}
	}

	/// Returns a pointer to the raw data content, or null if no content.
	#[must_use]
	pub fn as_ptr(&self) -> *const u16 {
		match self {
			Self::Id(id) => MAKEINTRESOURCE(*id as _),
			Self::Str(ws) => ws.as_ptr(),
		}
	}
}

/// Variant parameter for:
///
/// * [`POWERBROADCAST_SETTING`](crate::POWERBROADCAST_SETTING).
pub enum PowerSetting {
	AcDcPowerSource(co::SYSTEM_POWER_CONDITION),
	BatteryPercentageRemaining(u8),
	ConsoleDisplayState(co::MONITOR_DISPLAY_STATE),
	GlobalUserPresence(co::USER_ACTIVITY_PRESENCE),
	IdleBackgroundTask,
	MonitorPowerOn(bool),
	PowerSavingStatus(bool),
	PowerSchemePersonality(co::POWER_SAVINGS),
	SessionDisplayStatus(co::MONITOR_DISPLAY_STATE),
	SessionUserPresence(co::USER_ACTIVITY_PRESENCE),
	LidSwitchStateChange(PowerSettingLid),
	SystemAwayMode(PowerSettingAwayMode),
}

/// Variant parameter for:
///
/// * [`PowerSetting::SystemAwayMode`](crate::PowerSetting::SystemAwayMode).
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum PowerSettingAwayMode {
	Exiting,
	Entering,
}

/// Variant parameter for:
///
/// * [`PowerSetting::LidSwitchStateChange`](crate::PowerSetting::LidSwitchStateChange).
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum PowerSettingLid {
	Closed,
	Opened,
}

/// Registry value types.
///
/// This is a high-level abstraction over the [`co::REG`](crate::co::REG)
/// constants, plus the value they carry.
#[derive(Clone, Debug)]
pub enum RegistryValue {
	/// Binary value, defined as [`REG::BINARY`](crate::co::REG::BINARY).
	Binary(Vec<u8>),
	/// An `u32` integer value, defined as [`REG::DWORD`](crate::co::REG::DWORD).
	Dword(u32),
	/// An `u64` integer value, defined as [`REG::QWORD`](crate::co::REG::QWORD).
	Qword(u64),
	/// String value, defined as [`REG::SZ`](crate::co::REG::SZ).
	Sz(String),
	/// String value that contains unexpanded references to environment
	/// variables, for example, `%PATH%`. To expand the environment variable
	/// references, use
	/// [`ExpandEnvironmentStrings`](crate::ExpandEnvironmentStrings).
	ExpandSz(String),
	/// Multiple strings, defined as [`REG::MULTI_SZ`](crate::co::REG::MULTI_SZ).
	MultiSz(Vec<String>),
	/// No value, defined as [`REG::NONE`](crate::co::REG::NONE). Also used for
	/// non-implemented value types.
	None,
}

impl std::fmt::Display for RegistryValue {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			Self::Binary(b) => write!(
				f,
				"[REG_BINARY] {}",
				b.iter()
					.map(|n| format!("{:02}", *n))
					.collect::<Vec<_>>()
					.join(" "),
			),
			Self::Dword(n) => write!(f, "[REG_DWORD] {}", *n),
			Self::Qword(n) => write!(f, "[REG_QWORD] {}", *n),
			Self::Sz(s) => write!(f, "[REG_SZ] \"{}\"", s),
			Self::ExpandSz(s) => write!(f, "[REG_EXPAND_SZ] \"{}\"", s),
			Self::MultiSz(v) => write!(
				f,
				"[REG_MULTI_SZ] {}",
				v.iter()
					.map(|s| format!("\"{}\"", s))
					.collect::<Vec<_>>()
					.join(", "),
			),
			Self::None => write!(f, "[REG_NONE]"),
		}
	}
}

impl RegistryValue {
	/// Parses a binary data block as a `RegistryValue`.
	///
	/// This method can be used as an escape hatch to interoperate with other
	/// libraries.
	///
	/// # Safety
	///
	/// Assumes the binary data block has the correct content, according to the
	/// informed [`co::REG`](crate::co::REG).
	#[must_use]
	pub unsafe fn from_raw(buf: Vec<u8>, reg_type: co::REG) -> RegistryValue {
		match reg_type {
			co::REG::NONE => RegistryValue::None,
			co::REG::DWORD => RegistryValue::Dword(
				u32::from_ne_bytes(unsafe {
					*std::mem::transmute::<_, *const [u8; 4]>(buf.as_ptr())
				})
			),
			co::REG::QWORD => RegistryValue::Qword(
				u64::from_ne_bytes(unsafe {
					*std::mem::transmute::<_, *const [u8; 8]>(buf.as_ptr())
				})
			),
			co::REG::SZ => {
				let (_, vec16, _) = unsafe { buf.align_to::<u16>() };
				RegistryValue::Sz(WString::from_wchars_slice(&vec16).to_string())
			},
			co::REG::EXPAND_SZ => {
				let (_, vec16, _) = unsafe { buf.align_to::<u16>() };
				RegistryValue::Sz(WString::from_wchars_slice(&vec16).to_string())
			},
			co::REG::MULTI_SZ => {
				let (_, vec16, _) = unsafe { buf.align_to::<u16>() };
				RegistryValue::MultiSz(parse_multi_z_str(vec16.as_ptr()))
			},
			co::REG::BINARY => RegistryValue::Binary(buf),
			_ => RegistryValue::None, // other types not implemented yet
		}
	}

	/// Returns a pointer to the raw data, along with the raw data length.
	#[must_use]
	pub fn as_ptr_with_len(&self,
		str_buf: &mut WString,
	) -> (*const std::ffi::c_void, u32)
	{
		match self {
			Self::Binary(b) => (b.as_ptr() as _, b.len() as _),
			Self::Dword(n) => (n as *const _ as _, std::mem::size_of::<u32>() as _),
			Self::Qword(n) => (n as *const _ as _, std::mem::size_of::<u64>() as _),
			Self::Sz(s) => {
				*str_buf = WString::from_str(s);
				Self::as_ptr_with_len_str(&str_buf)
			},
			Self::ExpandSz(s) => {
				*str_buf = WString::from_str(s);
				Self::as_ptr_with_len_str(&str_buf)
			},
			Self::MultiSz(v) => {
				*str_buf = WString::from_str_vec(v);
				Self::as_ptr_with_len_str(&str_buf)
			},
			Self::None => (std::ptr::null(), 0),
		}
	}

	fn as_ptr_with_len_str(str_buf: &WString) -> (*const std::ffi::c_void, u32) {
		(
			str_buf.as_ptr() as _,
			(str_buf.buf_len() * std::mem::size_of::<u16>()) as _, // will include terminating null
		)
	}

	/// Returns the correspondent [`co::REG`](crate::co::REG) constant.
	#[must_use]
	pub const fn reg_type(&self) -> co::REG {
		match self {
			Self::Binary(_) => co::REG::BINARY,
			Self::Dword(_) => co::REG::DWORD,
			Self::Qword(_) => co::REG::QWORD,
			Self::Sz(_) => co::REG::SZ,
			Self::ExpandSz(_) => co::REG::EXPAND_SZ,
			Self::MultiSz(_) => co::REG::MULTI_SZ,
			Self::None => co::REG::NONE,
		}
	}
}

/// A predefined resource identifier.
///
/// Variant parameter for:
///
/// * [`HINSTANCE::EnumResourceLanguages`](crate::prelude::kernel_Hinstance::EnumResourceLanguages);
/// * [`HINSTANCE::EnumResourceNames`](crate::prelude::kernel_Hinstance::EnumResourceNames);
/// * [`HINSTANCE::EnumResourceTypes`](crate::prelude::kernel_Hinstance::EnumResourceTypes);
/// * [`HINSTANCE::FindResource`](crate::prelude::kernel_Hinstance::FindResource);
/// * [`HINSTANCE::FindResourceEx`](crate::prelude::kernel_Hinstance::FindResourceEx);
/// * [`HUPDATERSRC`](crate::prelude::kernel_Hupdatersrc::UpdateResource).
#[derive(Clone)]
pub enum RtStr {
	/// A predefined resource ID.
	Rt(co::RT),
	/// A resource string identifier.
	Str(WString),
}

impl std::fmt::Display for RtStr {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			Self::Rt(rt) => write!(f, "RT: {}", rt),
			Self::Str(str) => write!(f, "Str: {}", str),
		}
	}
}

impl RtStr {
	/// Constructs the enum directly from a string.
	#[must_use]
	pub fn from_str(v: &str) -> Self {
		Self::Str(WString::from_str(v))
	}

	/// Constructs the enum from a pointer to raw data.
	///
	/// # Safety
	///
	/// If string, be sure it is null-terminated, otherwise an invalid memory
	/// location might be read.
	#[must_use]
	pub unsafe fn from_ptr(ptr: *const u16) -> RtStr {
		if IS_INTRESOURCE(ptr) {
			Self::Rt(unsafe { co::RT::from_raw(ptr as _) })
		} else {
			Self::Str(WString::from_wchars_nullt(ptr))
		}
	}

	/// Returns a pointer to the raw data content, or null if no content.
	#[must_use]
	pub fn as_ptr(&self) -> *const u16 {
		match self {
			Self::Rt(id) => MAKEINTRESOURCE(id.raw() as _),
			Self::Str(ws) => ws.as_ptr(),
		}
	}
}

/// Notification content for
/// [`HSERVICESTATUS::RegisterServiceCtrlHandlerEx`](crate::prelude::kernel_Hservicestatus::RegisterServiceCtrlHandlerEx)
/// callback, describing [`co::SERVICE_CONTROL`](crate::co::SERVICE_CONTROL).
pub enum SvcCtl<'a> {
	Continue,
	Interrogate,
	NetBindAdd,
	NetBindDisable,
	NetBindEnable,
	NetBindRemove,
	ParamChange,
	Pause,
	PreShutdown,
	Shutdown,
	Stop,

	DeviceEvent(co::DBT, SvcCtlDeviceEvent<'a>),
	HardwareProfileChange(co::DBT),
	PowerEvent(SvcCtlPowerEvent<'a>),
	SessionChange(co::WTS, &'a WTSSESSION_NOTIFICATION),
	TimeChange(&'a SERVICE_TIMECHANGE_INFO),
	TriggerEvent,
	UserModeReboot,

	UserDefined(u8, u32, usize),
}

impl<'a> SvcCtl<'a> {
	/// Constructs the enum according to the raw data.
	///
	/// # Safety
	///
	/// This enum is constructed when building the output of
	/// [`HSERVICESTATUS::RegisterServiceCtrlHandlerEx`](crate::prelude::kernel_Hservicestatus::RegisterServiceCtrlHandlerEx)
	/// callback, make sure all parameters are correct.
	#[must_use]
	pub unsafe fn from_raw(
		control: u32,
		event_type: u32,
		event_data: PVOID,
	) -> Self
	{
		match co::SERVICE_CONTROL::from_raw(control) {
			co::SERVICE_CONTROL::CONTINUE => Self::Continue,
			co::SERVICE_CONTROL::INTERROGATE => Self::Interrogate,
			co::SERVICE_CONTROL::NETBINDADD => Self::NetBindAdd,
			co::SERVICE_CONTROL::NETBINDDISABLE => Self::NetBindDisable,
			co::SERVICE_CONTROL::NETBINDENABLE => Self::NetBindEnable,
			co::SERVICE_CONTROL::NETBINDREMOVE => Self::NetBindRemove,
			co::SERVICE_CONTROL::PARAMCHANGE => Self::ParamChange,
			co::SERVICE_CONTROL::PAUSE => Self::Pause,
			co::SERVICE_CONTROL::PRESHUTDOWN => Self::PreShutdown,
			co::SERVICE_CONTROL::SHUTDOWN => Self::Shutdown,
			co::SERVICE_CONTROL::STOP => Self::Stop,

			co::SERVICE_CONTROL::DEVICEEVENT => Self::DeviceEvent(
				co::DBT::from_raw(event_type as _),
				SvcCtlDeviceEvent::from_raw(&*(event_data as *const _)),
			),
			co::SERVICE_CONTROL::HARDWAREPROFILECHANGE => Self::HardwareProfileChange(
				co::DBT::from_raw(event_type as _),
			),
			co::SERVICE_CONTROL::POWEREVENT => Self::PowerEvent(
				SvcCtlPowerEvent::from_raw(co::PBT::from_raw(event_type), event_data),
			),
			co::SERVICE_CONTROL::SESSIONCHANGE => Self::SessionChange(
				co::WTS::from_raw(event_type as _),
				&*(event_data as *const _),
			),
			co::SERVICE_CONTROL::TIMECHANGE => Self::TimeChange(
				&*(event_data as *const _),
			),
			co::SERVICE_CONTROL::TRIGGEREVENT => Self::TriggerEvent,
			co::SERVICE_CONTROL::USERMODEREBOOT => Self::UserModeReboot,

			_ => Self::UserDefined(control as _, event_type, event_data as _),
		}
	}
}

/// Notification content for [`SvcCtl`](crate::SvcCtl).
pub enum SvcCtlDeviceEvent<'a> {
	Interface(&'a DEV_BROADCAST_DEVICEINTERFACE),
	Handle(&'a DEV_BROADCAST_HANDLE),
	Oem(&'a DEV_BROADCAST_OEM),
	Port(&'a DEV_BROADCAST_PORT),
	Volume(&'a DEV_BROADCAST_VOLUME),
}

impl<'a> SvcCtlDeviceEvent<'a> {
	/// Constructs the enum according to the raw data.
	///
	/// # Panics
	///
	/// Panics if `dbch_devicetype` field is invalid.
	///
	/// # Safety
	///
	/// This enum is constructed when building the output of
	/// [`HSERVICESTATUS::RegisterServiceCtrlHandlerEx`](crate::prelude::kernel_Hservicestatus::RegisterServiceCtrlHandlerEx)
	/// callback, make sure all parameters are correct.
	#[must_use]
	pub unsafe fn from_raw(event_data: &DEV_BROADCAST_HDR) -> Self {
		let ptr = event_data as *const DEV_BROADCAST_HDR;
		match event_data.dbch_devicetype {
			co::DBT_DEVTYP::DEVICEINTERFACE => Self::Interface(&*(ptr as *const _)),
			co::DBT_DEVTYP::HANDLE => Self::Handle(&*(ptr as *const _)),
			co::DBT_DEVTYP::OEM => Self::Oem(&*(ptr as *const _)),
			co::DBT_DEVTYP::PORT => Self::Port(&*(ptr as *const _)),
			co::DBT_DEVTYP::VOLUME => Self::Volume(&*(ptr as *const _)),
			_ => panic!("Invalid co::DBT_DEVTYP."),
		}
	}
}

/// Notification content for [`SvcCtl`](crate::SvcCtl).
pub enum SvcCtlPowerEvent<'a> {
	StatusChange,
	ResumeAutomatic,
	ResumeSuspend,
	Suspend,
	PowerSettingChange(&'a POWERBROADCAST_SETTING),
}

impl<'a> SvcCtlPowerEvent<'a> {
	/// Constructs the enum according to the raw data.
	///
	/// # Panics
	///
	/// Panics if `event` is invalid.
	///
	/// # Safety
	///
	/// This enum is constructed when building the output of
	/// [`HSERVICESTATUS::RegisterServiceCtrlHandlerEx`](crate::prelude::kernel_Hservicestatus::RegisterServiceCtrlHandlerEx)
	/// callback, make sure all parameters are correct.
	#[must_use]
	pub unsafe fn from_raw(event: co::PBT, event_data: PVOID) -> Self {
		match event {
			co::PBT::APMPOWERSTATUSCHANGE => Self::StatusChange,
			co::PBT::APMRESUMEAUTOMATIC => Self::ResumeAutomatic,
			co::PBT::APMRESUMESUSPEND => Self::ResumeSuspend,
			co::PBT::APMSUSPEND => Self::Suspend,
			co::PBT::POWERSETTINGCHANGE => Self::PowerSettingChange(&*(event_data as *const _)),
			_ => panic!("Invalid co::PBT."),
		}
	}
}

/// Variant parameter for:
///
/// * [`HACCESSTOKEN::GetTokenInformation`](crate::prelude::kernel_Haccesstoken::GetTokenInformation).
///
/// The enum values match those in
/// [`co::TOKEN_INFORMATION_CLASS`](crate::co::TOKEN_INFORMATION_CLASS) constant
/// type.
pub enum TokenInfo<'a, 'b, 'c, 'd, 'e, 'f> {
	User(Box<TOKEN_USER<'a>>),
	Groups(Box<TOKEN_GROUPS<'a>>),
	Privileges(Box<TOKEN_PRIVILEGES>),
	Owner(Box<TOKEN_OWNER<'a>>),
	PrimaryGroup(Box<TOKEN_PRIMARY_GROUP<'a>>),
	DefaultDacl(Box<TOKEN_DEFAULT_DACL<'a>>),
	Source(Box<TOKEN_SOURCE>),
	Type(Box<co::TOKEN_TYPE>),
	ImpersonationLevel(Box<co::SECURITY_IMPERSONATION>),
	Statistics(Box<TOKEN_STATISTICS>),
	RestrictedSids(Box<TOKEN_GROUPS<'a>>),
	SessionId(Box<u32>),
	GroupsAndPrivileges(Box<TOKEN_GROUPS_AND_PRIVILEGES<'a, 'b, 'c>>),
	SandBoxInert(Box<u32>),
	Origin(Box<TOKEN_ORIGIN>),
	ElevationType(Box<co::TOKEN_ELEVATION_TYPE>),
	LinkedToken(Box<TOKEN_LINKED_TOKEN>),
	Elevation(Box<TOKEN_ELEVATION>),
	HasRestrictions(Box<u32>),
	AccessInformation(Box<TOKEN_ACCESS_INFORMATION<'a, 'b, 'c, 'd, 'e, 'f>>),
	VirtualizationAllowed(Box<u32>),
	VirtualizationEnabled(Box<u32>),
	IntegrityLevel(Box<TOKEN_MANDATORY_LABEL<'a>>),
	UIAccess(Box<u32>),
	MandatoryPolicy(Box<TOKEN_MANDATORY_POLICY>),
	LogonSid(Box<TOKEN_GROUPS<'a>>),
	IsAppContainer(Box<u32>),
	Capabilities(Box<TOKEN_GROUPS<'a>>),
	AppContainerNumber(Box<u32>),
	DeviceClaimAttributes(Box<CLAIM_SECURITY_ATTRIBUTES_INFORMATION<'a, 'b>>),
	DeviceGroups(Box<TOKEN_GROUPS<'a>>),
	RestrictedDeviceGroups(Box<TOKEN_GROUPS<'a>>),
}