nfs 0.1.0

A userspace NFSv3 and NFSv4 client library.
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
#![cfg_attr(not(feature = "blocking"), allow(dead_code))]

use std::io::{self, Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use crate::error::{Error, Result};
use crate::xdr::{Decoder, Encode, Encoder};

pub const RPC_VERSION: u32 = 2;
pub const AUTH_NONE: u32 = 0;
pub const AUTH_SYS: u32 = 1;
/// Maximum number of auxiliary groups carried by AUTH_SYS credentials.
pub const AUTH_SYS_MAX_GROUPS: usize = 16;

const MSG_CALL: u32 = 0;
const MSG_REPLY: u32 = 1;
const REPLY_ACCEPTED: u32 = 0;
const REPLY_DENIED: u32 = 1;
const ACCEPT_SUCCESS: u32 = 0;
const ACCEPT_PROG_MISMATCH: u32 = 2;
const REJECT_RPC_MISMATCH: u32 = 0;
const REJECT_AUTH_ERROR: u32 = 1;
pub(crate) const LAST_FRAGMENT: u32 = 0x8000_0000;
pub(crate) const FRAGMENT_LEN_MASK: u32 = 0x7fff_ffff;
pub(crate) const DEFAULT_MAX_RECORD_SIZE: usize = 64 * 1024 * 1024;
const MAX_RECORD_HEADROOM: usize = 1024 * 1024;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Auth {
    None,
    Sys(AuthSys),
}

impl Auth {
    pub fn none() -> Self {
        Self::None
    }

    pub fn sys(auth: AuthSys) -> Self {
        Self::Sys(auth)
    }

    pub(crate) fn encode_opaque_auth(&self, encoder: &mut Encoder) -> Result<()> {
        match self {
            Self::None => {
                encoder.write_u32(AUTH_NONE);
                encoder.write_opaque(&[], 400)?;
            }
            Self::Sys(auth) => {
                let body = crate::xdr::to_bytes(auth)?;
                encoder.write_u32(AUTH_SYS);
                encoder.write_opaque(&body, 400)?;
            }
        }
        Ok(())
    }
}

/// AUTH_SYS credential used for ONC RPC calls.
///
/// AUTH_SYS carries a machine name, uid, primary gid, and supplementary gids.
/// It is the default authentication flavor for the high-level clients. It is
/// not cryptographically secure; deployments that require Kerberos/RPCSEC_GSS
/// need support outside the current high-level API.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthSys {
    /// Credential stamp used by the RPC request.
    pub stamp: u32,
    /// Caller machine name.
    pub machine_name: String,
    /// Caller uid.
    pub uid: u32,
    /// Caller primary gid.
    pub gid: u32,
    /// Caller supplementary gids.
    pub gids: Vec<u32>,
}

impl AuthSys {
    /// Builds an AUTH_SYS credential from explicit identity fields.
    ///
    /// At encode time the supplementary group list is limited by
    /// [`AUTH_SYS_MAX_GROUPS`].
    pub fn new(machine_name: impl Into<String>, uid: u32, gid: u32, gids: Vec<u32>) -> Self {
        Self {
            stamp: default_stamp(),
            machine_name: machine_name.into(),
            uid,
            gid,
            gids,
        }
    }

    /// Builds an AUTH_SYS credential from the current process identity.
    ///
    /// On Unix this reads the current uid, primary gid, and supplementary
    /// groups. On unsupported platforms the platform shims provide the best
    /// available values.
    pub fn current() -> Self {
        let machine_name = std::env::var("HOSTNAME").unwrap_or_else(|_| "localhost".to_owned());
        let gid = current_gid();
        Self::new(
            machine_name,
            current_uid(),
            gid,
            current_auxiliary_gids(gid),
        )
    }
}

impl Default for AuthSys {
    fn default() -> Self {
        Self::current()
    }
}

impl Encode for AuthSys {
    fn encode(&self, encoder: &mut Encoder) -> crate::xdr::Result<()> {
        encoder.write_u32(self.stamp);
        encoder.write_string(&self.machine_name, 255)?;
        encoder.write_u32(self.uid);
        encoder.write_u32(self.gid);
        encoder.write_array(&self.gids, AUTH_SYS_MAX_GROUPS)?;
        Ok(())
    }
}

#[derive(Debug)]
pub struct RpcClient {
    stream: TcpStream,
    xid: u32,
    auth: Auth,
    max_record_size: usize,
}

impl RpcClient {
    pub fn connect_with_timeout<A: ToSocketAddrs>(
        addr: A,
        auth: Auth,
        timeout: Option<Duration>,
    ) -> Result<Self> {
        let stream = connect_tcp_stream(addr, timeout)?;
        let client = Self::new(stream, auth)?;
        client.set_timeout(timeout)?;
        Ok(client)
    }

    pub fn new(stream: TcpStream, auth: Auth) -> Result<Self> {
        stream.set_nodelay(true)?;
        Ok(Self {
            stream,
            xid: default_stamp(),
            auth,
            max_record_size: DEFAULT_MAX_RECORD_SIZE,
        })
    }

    pub fn set_timeout(&self, timeout: Option<Duration>) -> Result<()> {
        self.stream.set_read_timeout(timeout)?;
        self.stream.set_write_timeout(timeout)?;
        Ok(())
    }

    pub fn set_max_record_size(&mut self, max_record_size: usize) {
        self.max_record_size = max_record_size;
    }

    pub fn call<T: Encode + ?Sized>(
        &mut self,
        program: u32,
        version: u32,
        procedure: u32,
        args: &T,
    ) -> Result<Vec<u8>> {
        let xid = self.next_xid();
        let request = encode_call(xid, program, version, procedure, &self.auth, args)?;
        self.write_record(&request)?;
        let reply = self.read_record()?;
        decode_reply(xid, &reply)
    }

    fn next_xid(&mut self) -> u32 {
        self.xid = self.xid.wrapping_add(1);
        if self.xid == 0 {
            self.xid = 1;
        }
        self.xid
    }

    fn write_record(&mut self, payload: &[u8]) -> Result<()> {
        if payload.len() > FRAGMENT_LEN_MASK as usize {
            return Err(Error::RpcRecordTooLarge {
                len: payload.len(),
                max: FRAGMENT_LEN_MASK as usize,
            });
        }

        let len = u32::try_from(payload.len()).map_err(|_| Error::RpcRecordTooLarge {
            len: payload.len(),
            max: FRAGMENT_LEN_MASK as usize,
        })?;
        let header = LAST_FRAGMENT | len;
        self.stream.write_all(&header.to_be_bytes())?;
        self.stream.write_all(payload)?;
        self.stream.flush()?;
        Ok(())
    }

    fn read_record(&mut self) -> Result<Vec<u8>> {
        let mut record = Vec::new();
        loop {
            let mut header_bytes = [0; 4];
            self.stream.read_exact(&mut header_bytes)?;
            let header = u32::from_be_bytes(header_bytes);
            let is_last = (header & LAST_FRAGMENT) != 0;
            let fragment_len = (header & FRAGMENT_LEN_MASK) as usize;

            if record.len().saturating_add(fragment_len) > self.max_record_size {
                return Err(Error::RpcRecordTooLarge {
                    len: record.len().saturating_add(fragment_len),
                    max: self.max_record_size,
                });
            }

            let start = record.len();
            record.resize(start + fragment_len, 0);
            self.stream.read_exact(&mut record[start..])?;

            if is_last {
                return Ok(record);
            }
        }
    }
}

fn connect_tcp_stream<A: ToSocketAddrs>(addr: A, timeout: Option<Duration>) -> Result<TcpStream> {
    let Some(timeout) = timeout else {
        return Ok(TcpStream::connect(addr)?);
    };

    let mut last_error = None;
    for socket_addr in addr.to_socket_addrs()? {
        match TcpStream::connect_timeout(&socket_addr, timeout) {
            Ok(stream) => return Ok(stream),
            Err(err) => last_error = Some(err),
        }
    }

    Err(last_error
        .unwrap_or_else(|| {
            io::Error::new(io::ErrorKind::InvalidInput, "no socket address resolved")
        })
        .into())
}

pub(crate) fn encode_call<T: Encode + ?Sized>(
    xid: u32,
    program: u32,
    version: u32,
    procedure: u32,
    auth: &Auth,
    args: &T,
) -> Result<Vec<u8>> {
    let mut encoder = Encoder::new();
    encoder.write_u32(xid);
    encoder.write_u32(MSG_CALL);
    encoder.write_u32(RPC_VERSION);
    encoder.write_u32(program);
    encoder.write_u32(version);
    encoder.write_u32(procedure);
    auth.encode_opaque_auth(&mut encoder)?;
    Auth::None.encode_opaque_auth(&mut encoder)?;
    args.encode(&mut encoder)?;
    Ok(encoder.into_bytes())
}

pub(crate) fn decode_reply(expected_xid: u32, reply: &[u8]) -> Result<Vec<u8>> {
    let mut decoder = Decoder::new(reply);
    let actual_xid = decoder.read_u32()?;
    if actual_xid != expected_xid {
        return Err(Error::RpcMismatch {
            expected: expected_xid,
            actual: actual_xid,
        });
    }

    let message_type = decoder.read_u32()?;
    if message_type != MSG_REPLY {
        return Err(Error::RpcUnexpectedMessageType(message_type));
    }

    match decoder.read_u32()? {
        REPLY_ACCEPTED => decode_accepted_reply(&mut decoder),
        REPLY_DENIED => decode_denied_reply(&mut decoder),
        value => Err(Error::RpcDenied {
            reject_stat: value,
            detail: 0,
        }),
    }
}

fn decode_accepted_reply(decoder: &mut Decoder<'_>) -> Result<Vec<u8>> {
    read_opaque_auth(decoder)?;
    match decoder.read_u32()? {
        ACCEPT_SUCCESS => {
            let remaining = decoder.remaining();
            let payload = decoder.read_fixed_opaque_unpadded(remaining)?;
            Ok(payload.to_vec())
        }
        ACCEPT_PROG_MISMATCH => {
            let low = decoder.read_u32()?;
            let high = decoder.read_u32()?;
            Err(Error::RpcProgramMismatch { low, high })
        }
        accept_stat => Err(Error::RpcAcceptedError { accept_stat }),
    }
}

fn decode_denied_reply(decoder: &mut Decoder<'_>) -> Result<Vec<u8>> {
    match decoder.read_u32()? {
        REJECT_RPC_MISMATCH => {
            let low = decoder.read_u32()?;
            let high = decoder.read_u32()?;
            Err(Error::RpcProgramMismatch { low, high })
        }
        REJECT_AUTH_ERROR => {
            let auth_stat = decoder.read_u32()?;
            Err(Error::RpcDenied {
                reject_stat: REJECT_AUTH_ERROR,
                detail: auth_stat,
            })
        }
        reject_stat => Err(Error::RpcDenied {
            reject_stat,
            detail: 0,
        }),
    }
}

pub(crate) fn read_opaque_auth(decoder: &mut Decoder<'_>) -> Result<(u32, Vec<u8>)> {
    let flavor = decoder.read_u32()?;
    let body = decoder.read_opaque(400)?.to_vec();
    Ok((flavor, body))
}

pub(crate) fn max_record_size_for_payloads(payload_sizes: &[u32]) -> usize {
    let configured = payload_sizes
        .iter()
        .map(|size| *size as usize)
        .max()
        .unwrap_or(0)
        .saturating_add(MAX_RECORD_HEADROOM);
    configured.max(DEFAULT_MAX_RECORD_SIZE)
}

pub(crate) fn default_stamp() -> u32 {
    let duration = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();
    (duration.as_secs() as u32) ^ duration.subsec_nanos()
}

#[cfg(unix)]
fn current_uid() -> u32 {
    // SAFETY: geteuid has no preconditions and does not dereference pointers.
    unsafe { libc::geteuid() as u32 }
}

#[cfg(not(unix))]
fn current_uid() -> u32 {
    0
}

#[cfg(unix)]
fn current_gid() -> u32 {
    // SAFETY: getegid has no preconditions and does not dereference pointers.
    unsafe { libc::getegid() as u32 }
}

#[cfg(not(unix))]
fn current_gid() -> u32 {
    0
}

#[cfg(unix)]
fn current_auxiliary_gids(primary_gid: u32) -> Vec<u32> {
    // SAFETY: getgroups is called with size 0 and a null pointer to query the
    // required group count, as specified by POSIX.
    let count = unsafe { libc::getgroups(0, std::ptr::null_mut()) };
    if count <= 0 {
        return Vec::new();
    }

    let mut groups = vec![0 as libc::gid_t; count as usize];
    // SAFETY: groups has capacity for `count` gid_t values and the pointer is
    // valid for writes of that length.
    let count = unsafe { libc::getgroups(groups.len() as libc::c_int, groups.as_mut_ptr()) };
    if count <= 0 {
        return Vec::new();
    }

    groups.truncate(count as usize);
    normalize_auxiliary_gids(primary_gid, groups)
}

#[cfg(not(unix))]
fn current_auxiliary_gids(_primary_gid: u32) -> Vec<u32> {
    Vec::new()
}

fn normalize_auxiliary_gids(primary_gid: u32, groups: impl IntoIterator<Item = u32>) -> Vec<u32> {
    let mut normalized = Vec::new();
    for gid in groups {
        if gid == primary_gid || normalized.contains(&gid) {
            continue;
        }
        normalized.push(gid);
        if normalized.len() == AUTH_SYS_MAX_GROUPS {
            break;
        }
    }
    normalized
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::TcpListener;

    #[test]
    fn record_limit_keeps_default_for_small_payloads() {
        assert_eq!(
            max_record_size_for_payloads(&[128 * 1024]),
            DEFAULT_MAX_RECORD_SIZE
        );
    }

    #[test]
    fn record_limit_adds_headroom_for_large_payloads() {
        assert_eq!(
            max_record_size_for_payloads(&[DEFAULT_MAX_RECORD_SIZE as u32]),
            DEFAULT_MAX_RECORD_SIZE + MAX_RECORD_HEADROOM
        );
    }

    #[test]
    fn connects_with_configured_timeout() {
        let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
        let addr = listener.local_addr().unwrap();
        let accept = std::thread::spawn(move || {
            let _ = listener.accept();
        });

        let client =
            RpcClient::connect_with_timeout(addr, Auth::none(), Some(Duration::from_secs(1)))
                .unwrap();
        drop(client);
        accept.join().unwrap();
    }

    #[test]
    fn normalizes_auxiliary_groups_for_auth_sys() {
        let groups = normalize_auxiliary_gids(
            10,
            [
                10, 1, 2, 1, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18,
            ],
        );

        assert_eq!(
            groups,
            vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17]
        );
        assert_eq!(groups.len(), AUTH_SYS_MAX_GROUPS);
        assert!(!groups.contains(&10));
    }

    #[test]
    fn current_auth_sys_has_bounded_auxiliary_groups() {
        let auth = AuthSys::current();
        assert!(auth.gids.len() <= AUTH_SYS_MAX_GROUPS);
        assert!(!auth.gids.contains(&auth.gid));
    }
}