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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use crate::Instance;
use crate::Scope;
use crate::ValueRef;
use crate::error::HandleCreateError;
use crate::error::InstanceFromEnvError;
use crate::error::InstanceFromFmriError;
use crate::error::InstanceOpError;
use crate::error::LibscfError;
use crate::error::ScfEntity;
use crate::error::ScfError;
use crate::error::ScopeError;
use crate::value::ScfValue;
use std::marker::PhantomData;
use std::ptr::NonNull;
#[cfg(feature = "smf-by-instance")]
use crate::Service;
#[cfg(feature = "smf-by-instance")]
use crate::error::ServiceRefreshAllError;
mod object;
pub(crate) use object::ScfObject;
pub(crate) use object::ScfObjectType;
#[cfg(any(test, feature = "testing"))]
use crate::isolated::IsolatedConfigd;
/// Entry-point handle to `libscf`.
// We intentionally do not impl `Send` or `Sync` for `Scf`. Errors flow out
// through the thread-local `scf_error()` function, so we don't want to mix
// use of the same handle across different threads.
#[derive(Debug)]
pub struct Scf<'a> {
did_bind_handle: bool,
handle: NonNull<libscf_sys::scf_handle_t>,
refresher: RefreshMechanism<'a>,
}
impl Drop for Scf<'_> {
fn drop(&mut self) {
// We bind the handle in `connect_common()`, but only at the end: it's
// possible we could fail partway through `connect_common()` and drop an
// `Scf` before we bind it. If so, don't try to unbind it. (libscf
// guards against this, so unbinding an unbound handle doesn't cause
// undefined behavior, but (a) it does return an error and (b) that's an
// undocumented implementation detail.)
if self.did_bind_handle {
unsafe { libscf_sys::scf_handle_unbind(self.handle.as_ptr()) };
}
unsafe { libscf_sys::scf_handle_destroy(self.handle.as_ptr()) };
}
}
impl Scf<'static> {
/// Connect to the `svc.configd` instance in the current zone.
pub fn connect_current_zone() -> Result<Self, ScfError> {
Self::connect_common(
ConnectMode::Current,
RefreshMechanism::Libscf(PhantomData),
)
}
/// Connect to the `svc.configd` instance in a named zone.
pub fn connect_zone(zonename: &str) -> Result<Self, ScfError> {
Self::connect_common(
ConnectMode::Zone(zonename),
RefreshMechanism::Libscf(PhantomData),
)
}
}
#[cfg(any(test, feature = "testing"))]
impl<'a> Scf<'a> {
/// Connect to the `svc.configd` running inside an [`IsolatedConfigd`].
pub fn connect_isolated(
configd: &'a IsolatedConfigd,
) -> Result<Self, ScfError> {
Self::connect_common(
ConnectMode::from(configd),
RefreshMechanism::Isolated(configd),
)
}
}
impl<'a> Scf<'a> {
fn connect_common(
mode: ConnectMode<'_>,
refresher: RefreshMechanism<'a>,
) -> Result<Self, ScfError> {
let handle =
unsafe { libscf_sys::scf_handle_create(libscf_sys::SCF_VERSION) };
let handle = LibscfError::from_ptr(handle)
.map_err(|err| HandleCreateError { entity: ScfEntity::Scf, err })?;
// Create the Scf object immediately so we clean up on drop on any error
// below. We don't bind it until the end, though.
let mut scf = Self { did_bind_handle: false, handle, refresher };
// Both the `Zone` (available in prod and tests) and `DoorPath`
// (available only in tests) connect modes rely on undocumented and
// uncommitted interfaces. These match the way `svccfg` implements the
// same techniques: after creating an `scf_handle_t` but before binding
// it, decorating it with either the "zone" (with an astring-typed value
// specifying the name of the zone) or "door_path" decoration (with an
// astring-typed value containing a path to the door) will cause us to
// either connect to the svc.configd instance inside a zone or at a
// specific door path, respectively.
//
// In both cases, we can destroy the value after calling
// `scf_handle_decorate()`; we do that implicitly here by dropping them.
match mode {
ConnectMode::Current => {
// Nothing special to do.
}
ConnectMode::Zone(zonename) => {
let mut value = ScfValue::new(&scf)?;
value.set(ValueRef::AString(zonename)).map_err(|err| {
ScfError::SetZoneName { zonename: Box::from(zonename), err }
})?;
unsafe {
value.scf_apply_as_decoration(
scf.handle.as_ptr(),
libscf_sys::decorations::ZONE.as_ptr().cast::<i8>(),
)
}
.map_err(|err| {
ScfError::SetDecorationZoneName {
zonename: Box::from(zonename),
err,
}
})?;
}
#[cfg(any(test, feature = "testing"))]
ConnectMode::DoorPath(door_path) => {
let mut value = ScfValue::new(&scf)?;
value.set(ValueRef::AString(door_path)).map_err(|err| {
ScfError::SetDoorPath {
door_path: Box::from(door_path),
err,
}
})?;
unsafe {
value.scf_apply_as_decoration(
scf.handle.as_ptr(),
decorations::DOOR_PATH.as_ptr().cast::<i8>(),
)
}
.map_err(|err| {
ScfError::SetDecorationDoorPath {
door_path: Box::from(door_path),
err,
}
})?;
}
}
let ret = unsafe { libscf_sys::scf_handle_bind(scf.handle.as_ptr()) };
() = LibscfError::from_ret(ret).map_err(ScfError::HandleBind)?;
scf.did_bind_handle = true;
Ok(scf)
}
/// Get a handle to the local scope.
///
/// `libscf` currently does not support any other scopes.
pub fn scope_local(&self) -> Result<Scope<'_>, ScopeError> {
Scope::new_local(self)
}
/// Obtain an [`Instance`] handle identified by its FMRI.
pub fn instance_from_fmri(
&self,
fmri: &str,
) -> Result<Instance<'_>, InstanceFromFmriError> {
Instance::from_fmri(self, fmri)
}
/// From within a running service instance, get our own [`Instance`].
///
/// If you are using this to look up the current value of your properties,
/// you almost certainly want to call [`Instance::snapshot("running")`]
/// on the returned instance.
///
/// This method looks up our own FMRI via the `SMF_FMRI` environment
/// variable, which is supplied by SMF to running instances.
///
/// [`Instance::snapshot("running")`]: Instance::snapshot
pub fn self_instance_from_env(
&self,
) -> Result<Instance<'_>, InstanceFromEnvError> {
// From `man smf_method`:
//
// > Environment Variables
// >
// > The restarter provides four environment variables to the method
// > that determine the context in which the method is invoked.
// >
// > SMF_FMRI
// >
// > The service fault management resource identifier (FMRI) of the
// > instance for which the method is invoked.
//
// If this process was started under SMF, it can look up its own
// instance FMRI via that env var.
const SELF_FMRI_ENV_VAR: &str = "SMF_FMRI";
let fmri = std::env::var(SELF_FMRI_ENV_VAR).map_err(|err| {
InstanceFromEnvError::EnvLookup { env_var: SELF_FMRI_ENV_VAR, err }
})?;
Ok(self.instance_from_fmri(&fmri)?)
}
pub(crate) fn refresh_instance(
&self,
instance: &mut Instance<'_>,
) -> Result<(), InstanceOpError> {
self.refresher.refresh_instance(instance)
}
#[cfg(feature = "smf-by-instance")]
pub(crate) fn refresh_all_instances(
&self,
service: &mut Service<'_>,
) -> Result<(), ServiceRefreshAllError> {
self.refresher.refresh_all_instances(service)
}
#[cfg(feature = "smf-by-instance")]
pub(crate) fn fail_instance_op_if_isolated_configd(
&self,
) -> Result<(), InstanceOpError> {
self.refresher.fail_instance_op_if_isolated_configd()
}
pub(crate) unsafe fn scf_get_scope_local(
&self,
scope: *mut libscf_sys::scf_scope_t,
) -> Result<(), LibscfError> {
LibscfError::from_ret(unsafe {
libscf_sys::scf_handle_get_scope(
self.handle.as_ptr(),
libscf_sys::SCF_SCOPE_LOCAL.as_ptr().cast::<i8>(),
scope,
)
})
}
pub(crate) unsafe fn scf_decode_fmri_exact_instance(
&self,
fmri: *const libc::c_char,
instance: *mut libscf_sys::scf_instance_t,
) -> Result<(), LibscfError> {
// Require `fmri` to describe exactly an instance.
let flags = libscf_sys::SCF_DECODE_FMRI_REQUIRE_INSTANCE
| libscf_sys::SCF_DECODE_FMRI_EXACT;
LibscfError::from_ret(unsafe {
libscf_sys::scf_handle_decode_fmri(
self.handle.as_ptr(),
fmri,
std::ptr::null_mut(), // scope
std::ptr::null_mut(), // service
instance,
std::ptr::null_mut(), // property group
std::ptr::null_mut(), // property
flags,
)
})
}
}
enum ConnectMode<'a> {
Current,
Zone(&'a str),
#[cfg(any(test, feature = "testing"))]
DoorPath(&'a str),
}
#[cfg(any(test, feature = "testing"))]
impl<'a> From<&'a IsolatedConfigd> for ConnectMode<'a> {
fn from(configd: &'a IsolatedConfigd) -> Self {
Self::DoorPath(configd.door_path().as_str())
}
}
#[derive(Debug)]
enum RefreshMechanism<'a> {
// This variant stores a `PhantomData` so we don't get an unused lifetime
// error in non-test builds, which only have this variant.
Libscf(PhantomData<&'a ()>),
#[cfg(any(test, feature = "testing"))]
Isolated(&'a IsolatedConfigd),
}
impl RefreshMechanism<'_> {
fn refresh_instance(
&self,
instance: &mut Instance<'_>,
) -> Result<(), InstanceOpError> {
match self {
RefreshMechanism::Libscf(_) => {
// The primary interface for refreshing instances is
// `smf_refresh_instance()`, which doesn't go through our SCF
// handle at all, and therefore can only refresh instances in
// the current zone. If we were created via
// `Scf::connect_zone()`, that won't work - it'd try to refresh
// an instance of the same FMRI in the gz instead of the named
// zone.
//
// Instead, we either use a private API (from `libscf_priv.h`)
// that allows refreshing directly via the instance handle, or
// if the `smf-by-instance` feature is enabled, we use the newer
// `smf_refresh_instance_by_instance()` function that takes an
// instance handle instead of an FMRI.
instance.scf_refresh()
}
#[cfg(any(test, feature = "testing"))]
RefreshMechanism::Isolated(configd) => {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let fmri = OsStr::from_bytes(instance.fmri_c_str().to_bytes());
configd.refresh(fmri).map_err(From::from)
}
}
}
#[cfg(feature = "smf-by-instance")]
pub(crate) fn refresh_all_instances(
&self,
service: &mut Service<'_>,
) -> Result<(), ServiceRefreshAllError> {
match self {
RefreshMechanism::Libscf(_) => {
service.smf_refresh_all_instances_impl()
}
#[cfg(any(test, feature = "testing"))]
RefreshMechanism::Isolated(configd) => {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let fmri = OsStr::from_bytes(service.fmri_c_str().to_bytes());
configd.refresh(fmri).map_err(From::from)
}
}
}
#[cfg(feature = "smf-by-instance")]
pub(crate) fn fail_instance_op_if_isolated_configd(
&self,
) -> Result<(), InstanceOpError> {
match self {
RefreshMechanism::Libscf(_) => Ok(()),
#[cfg(any(test, feature = "testing"))]
RefreshMechanism::Isolated(_) => {
Err(InstanceOpError::UnsupportedIsolated)
}
}
}
}
#[cfg(any(test, feature = "testing"))]
mod decorations {
pub const DOOR_PATH: &[u8] = b"door_path\0";
}