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
//! First sketch of NBD (Network block device) protocol support in Rust
//! API is not stable yet, obviously
//!
//! https://github.com/NetworkBlockDevice/nbd/blob/master/doc/proto.md

#![deny(missing_docs)]
#![forbid(unsafe_code)]

extern crate byteorder;


/// Items for implementing NBD server
pub mod server {

    use self::consts::*;
    use byteorder::{BigEndian as BE, ReadBytesExt, WriteBytesExt};
    use std::io::{Error, ErrorKind, Read, Result, Seek, SeekFrom, Write};

    #[doc(hidden)]
    pub fn oldstyle_header<W: Write>(mut c: W, size: u64, flags: u32) -> Result<()> {
        c.write_all(b"NBDMAGIC")?;
        c.write_all(b"\x00\x42\x02\x81\x86\x12\x53")?;
        c.write_u64::<BE>(size)?;
        c.write_u32::<BE>(flags)?;
        c.flush()?;
        Ok(())
    }

    fn strerror(s: &'static str) -> Result<()> {
        let stderr: Box<::std::error::Error + Send + Sync> = s.into();
        Err(Error::new(ErrorKind::InvalidData, stderr))
    }

    fn reply<IO: Write + Read>(mut c: IO, clopt: u32, rtype: u32, data: &[u8]) -> Result<()> {
        c.write_u64::<BE>(0x3e889045565a9)?;
        c.write_u32::<BE>(clopt)?;
        c.write_u32::<BE>(rtype)?;
        c.write_u32::<BE>(data.len() as u32)?;
        c.write_all(data)?;
        c.flush()?;
        Ok(())
    }

    /// Information about an export (currently only one export is supported), for handshake
    #[derive(Debug, Default)]
    pub struct Export {
        /// Size of the underlying data, in bytes
        pub size: u64,
        /// Tell client it's readonly
        pub readonly: bool,
        /// Tell that NBD_CMD_RESIZE should be supported. Not implemented in this library currently
        pub resizeable: bool,
        /// Tell that the exposed device has slow seeks, hence clients should use elevator algorithm
        pub rotational: bool,
        /// Tell that NBD_CMD_TRIM operation is supported. Not implemented in this library currently
        pub send_trim: bool,
    }

    /// Ignores incoming export name, accepts everything
    pub fn handshake<IO: Write + Read>(mut c: IO, export: &Export) -> Result<()> {
        //let hs_flags = NBD_FLAG_FIXED_NEWSTYLE;
        let hs_flags = NBD_FLAG_FIXED_NEWSTYLE;

        c.write_all(b"NBDMAGIC")?;
        c.write_all(b"IHAVEOPT")?;
        c.write_u16::<BE>(hs_flags)?;
        c.flush()?;

        let client_flags = c.read_u32::<BE>()?;

        if client_flags != NBD_FLAG_C_FIXED_NEWSTYLE {
            strerror("Invalid client flag")?;
        }

        let client_optmagic = c.read_u64::<BE>()?;

        if client_optmagic != 0x49484156454F5054 {
            // IHAVEOPT
            strerror("Invalid client optmagic")?;
        }

        loop {
            let clopt = c.read_u32::<BE>()?;
            let optlen = c.read_u32::<BE>()?;

            if optlen > 100000 {
                strerror("Suspiciously big option length")?;
            }

            let mut opt = vec![0; optlen as usize];
            c.read_exact(&mut opt)?;

            match clopt {
                NBD_OPT_EXPORT_NAME => {
                    c.write_u64::<BE>(export.size)?;
                    let mut flags = NBD_FLAG_HAS_FLAGS;
                    if export.readonly {
                        flags |= NBD_FLAG_READ_ONLY
                    } else {
                        flags |= NBD_FLAG_SEND_FLUSH
                    };
                    if export.resizeable {
                        flags |= NBD_FLAG_READ_ONLY
                    };
                    if export.rotational {
                        flags |= NBD_FLAG_ROTATIONAL
                    };
                    if export.send_trim {
                        flags |= NBD_FLAG_SEND_TRIM
                    };
                    c.write_u16::<BE>(flags)?;
                    c.write_all(&[0; 124])?;
                    c.flush()?;
                    return Ok(());
                }
                NBD_OPT_ABORT => {
                    reply(&mut c, clopt, NBD_REP_ACK, b"")?;
                    strerror("Client abort")?;
                }
                NBD_OPT_LIST => {
                    if optlen != 0 {
                        strerror("NBD_OPT_LIST with content")?;
                    }

                    reply(&mut c, clopt, NBD_REP_SERVER, b"\x00\x00\x00\x07rustnbd")?;
                    reply(&mut c, clopt, NBD_REP_ACK, b"")?;
                }
                NBD_OPT_STARTTLS => {
                    strerror("TLS not supported")?;
                }
                NBD_OPT_INFO => {
                    reply(&mut c, clopt, NBD_REP_ERR_UNSUP, b"")?;
                }
                NBD_OPT_GO => {
                    reply(&mut c, clopt, NBD_REP_ERR_UNSUP, b"")?;
                }
                _ => {
                    strerror("Invalid client option type")?;
                }
            }
        }
    }

    fn replyt<IO: Write + Read>(mut c: IO, error: u32, handle: u64) -> Result<()> {
        c.write_u32::<BE>(0x67446698)?;
        c.write_u32::<BE>(error)?;
        c.write_u64::<BE>(handle)?;
        Ok(())
    }

    fn replyte<IO: Write + Read>(mut c: IO, error: Error, handle: u64) -> Result<()> {
        let ec = if let Some(x) = error.raw_os_error() {
            if (x as u32) != 0 {
                x as u32
            } else {
                5
            }
        } else {
            5
        };
        replyt(&mut c, ec, handle)
    }

    // based on https://doc.rust-lang.org/src/std/io/util.rs.html#48
    fn mycopy<R: ?Sized, W: ?Sized>(
        reader: &mut R,
        writer: &mut W,
        buf: &mut [u8],
        mut limit: usize,
    ) -> Result<u64>
    where
        R: Read,
        W: Write,
    {
        let mut written = 0;
        loop {
            let to_read = buf.len().min(limit);
            let len = match reader.read(&mut buf[0..to_read]) {
                Ok(0) => return Ok(written),
                Ok(len) => len,
                Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
                Err(e) => return Err(e),
            };
            writer.write_all(&buf[..len])?;
            written += len as u64;
            //eprintln!("written={} limit={} len={}", written, limit, len);
            limit -= len;
            if limit == 0 {
                return Ok(written);
            }
        }
    }

    /// Serve given data. If readonly, use a dummy `Write` implementation.
    ///
    /// Should be used after `handshake`
    pub fn transmission<IO, D>(mut c: IO, mut data: D) -> Result<()>
    where
        IO: Read + Write,
        D: Read + Write + Seek,
    {
        let mut buf = vec![0; 65536];
        loop {
            let magic = c.read_u32::<BE>()?;
            if magic != 0x25609513 {
                strerror("Invalid request magic")?;
            }
            let _flags = c.read_u16::<BE>()?;
            let typ = c.read_u16::<BE>()?;
            let handle = c.read_u64::<BE>()?;
            let offset = c.read_u64::<BE>()?;
            let length = c.read_u32::<BE>()?;

            //eprintln!("typ={} handle={} off={} len={}", typ, handle, offset, length);
            match typ {
                NBD_CMD_READ => {
                    if let Err(e) = data.seek(SeekFrom::Start(offset)) {
                        replyte(&mut c, e, handle)?;
                    } else {
                        replyt(&mut c, 0, handle)?;
                        match mycopy(&mut data, &mut c, &mut buf, length as usize) {
                            Err(e) => replyte(&mut c, e, handle)?,
                            Ok(x) if x == (length as u64) => {}
                            Ok(_) => {
                                strerror("sudden EOF")?;
                            }
                        }
                    }
                }
                NBD_CMD_WRITE => {
                    if let Err(e) = data.seek(SeekFrom::Start(offset)) {
                        replyte(&mut c, e, handle)?;
                    } else {
                        replyt(&mut c, 0, handle)?;
                        match mycopy(&mut c, &mut data, &mut buf, length as usize) {
                            Err(e) => replyte(&mut c, e, handle)?,
                            Ok(x) if x == (length as u64) => {}
                            Ok(_) => {
                                strerror("sudden EOF")?;
                            }
                        }
                    }
                }
                NBD_CMD_DISC => {
                    return Ok(());
                }
                NBD_CMD_FLUSH => {
                    data.flush()?;
                    replyt(&mut c, 0, handle)?;
                }
                NBD_CMD_TRIM => {
                    replyt(&mut c, 38, handle)?;
                }
                NBD_CMD_WRITE_ZEROES => {
                    replyt(&mut c, 38, handle)?;
                }
                _ => strerror("Unknown command from client")?,
            }
            c.flush()?;
        }
    }

    /// Recommended port for NBD servers, especially with new handshake format.
    /// There is some untested, doc-hidden old handshake support in this library.
    pub const DEFAULT_TCP_PORT: u16 = 10809;

    #[allow(dead_code)]
    mod consts {
        pub const NBD_OPT_EXPORT_NAME: u32 = 1;
        pub const NBD_OPT_ABORT: u32 = 2;
        pub const NBD_OPT_LIST: u32 = 3;
        pub const NBD_OPT_STARTTLS: u32 = 5;
        pub const NBD_OPT_INFO: u32 = 6;
        pub const NBD_OPT_GO: u32 = 7;

        pub const NBD_REP_ACK: u32 = 1;
        pub const NBD_REP_SERVER: u32 = 2;
        pub const NBD_REP_INFO: u32 = 3;
        pub const NBD_REP_FLAG_ERROR: u32 = (1 << 31);
        pub const NBD_REP_ERR_UNSUP: u32 = (1 | NBD_REP_FLAG_ERROR);
        pub const NBD_REP_ERR_POLICY: u32 = (2 | NBD_REP_FLAG_ERROR);
        pub const NBD_REP_ERR_INVALID: u32 = (3 | NBD_REP_FLAG_ERROR);
        pub const NBD_REP_ERR_PLATFORM: u32 = (4 | NBD_REP_FLAG_ERROR);
        pub const NBD_REP_ERR_TLS_REQD: u32 = (5 | NBD_REP_FLAG_ERROR);
        pub const NBD_REP_ERR_UNKNOWN: u32 = (6 | NBD_REP_FLAG_ERROR);
        pub const NBD_REP_ERR_BLOCK_SIZE_REQD: u32 = (8 | NBD_REP_FLAG_ERROR);

        pub const NBD_FLAG_FIXED_NEWSTYLE: u16 = (1 << 0);
        pub const NBD_FLAG_NO_ZEROES: u16 = (1 << 1);

        pub const NBD_FLAG_C_FIXED_NEWSTYLE: u32 = NBD_FLAG_FIXED_NEWSTYLE as u32;
        pub const NBD_FLAG_C_NO_ZEROES: u32 = NBD_FLAG_NO_ZEROES as u32;

        pub const NBD_INFO_EXPORT: u16 = 0;
        pub const NBD_INFO_NAME: u16 = 1;
        pub const NBD_INFO_DESCRIPTION: u16 = 2;
        pub const NBD_INFO_BLOCK_SIZE: u16 = 3;

        pub const NBD_FLAG_HAS_FLAGS: u16 = (1 << 0);
        pub const NBD_FLAG_READ_ONLY: u16 = (1 << 1);
        pub const NBD_FLAG_SEND_FLUSH: u16 = (1 << 2);
        pub const NBD_FLAG_SEND_FUA: u16 = (1 << 3);
        pub const NBD_FLAG_ROTATIONAL: u16 = (1 << 4);
        pub const NBD_FLAG_SEND_TRIM: u16 = (1 << 5);
        pub const NBD_FLAG_SEND_WRITE_ZEROES: u16 = (1 << 6);
        pub const NBD_FLAG_CAN_MULTI_CONN: u16 = (1 << 8);

        pub const NBD_CMD_READ: u16 = 0;
        pub const NBD_CMD_WRITE: u16 = 1;
        pub const NBD_CMD_DISC: u16 = 2;
        pub const NBD_CMD_FLUSH: u16 = 3;
        pub const NBD_CMD_TRIM: u16 = 4;
        pub const NBD_CMD_WRITE_ZEROES: u16 = 6;
    }

} // mod server

/*
// Options that the client can select to the server 
#define NBD_OPT_EXPORT_NAME     (1)     // Client wants to select a named export (is followed by name of export) 
#define NBD_OPT_ABORT           (2)     // Client wishes to abort negotiation 
#define NBD_OPT_LIST            (3)     // Client request list of supported exports (not followed by data) 
#define NBD_OPT_STARTTLS        (5)     // Client wishes to initiate TLS 
#define NBD_OPT_INFO            (6)     // Client wants information about the given export 
#define NBD_OPT_GO              (7)     // Client wants to select the given and move to the transmission phase 

// Replies the server can send during negotiation 
#define NBD_REP_ACK             (1)     // ACK a request. Data: option number to be acked 
#define NBD_REP_SERVER          (2)     // Reply to NBD_OPT_LIST (one of these per server; must be followed by NBD_REP_ACK to signal the end of the list 
#define NBD_REP_INFO            (3)     // Reply to NBD_OPT_INFO 
#define NBD_REP_FLAG_ERROR      (1 << 31)       // If the high bit is set, the reply is an error 
#define NBD_REP_ERR_UNSUP       (1 | NBD_REP_FLAG_ERROR)        // Client requested an option not understood by this version of the server 
#define NBD_REP_ERR_POLICY      (2 | NBD_REP_FLAG_ERROR)        // Client requested an option not allowed by server configuration. (e.g., the option was disabled) 
#define NBD_REP_ERR_INVALID     (3 | NBD_REP_FLAG_ERROR)        // Client issued an invalid request 
#define NBD_REP_ERR_PLATFORM    (4 | NBD_REP_FLAG_ERROR)        // Option not supported on this platform 
#define NBD_REP_ERR_TLS_REQD    (5 | NBD_REP_FLAG_ERROR)        // TLS required 
#define NBD_REP_ERR_UNKNOWN     (6 | NBD_REP_FLAG_ERROR)        // NBD_OPT_INFO or ..._GO requested on unknown export 
#define NBD_REP_ERR_BLOCK_SIZE_REQD (8 | NBD_REP_FLAG_ERROR)    // Server is not willing to serve the export without the block size being negotiated 

// Global flags 
#define NBD_FLAG_FIXED_NEWSTYLE (1 << 0)        // new-style export that actually supports extending 
#define NBD_FLAG_NO_ZEROES      (1 << 1)        // we won't send the 128 bits of zeroes if the client sends NBD_FLAG_C_NO_ZEROES 
// Flags from client to server. 
#define NBD_FLAG_C_FIXED_NEWSTYLE NBD_FLAG_FIXED_NEWSTYLE
#define NBD_FLAG_C_NO_ZEROES    NBD_FLAG_NO_ZEROES

// Info types 
#define NBD_INFO_EXPORT         (0)
#define NBD_INFO_NAME           (1)
#define NBD_INFO_DESCRIPTION    (2)
#define NBD_INFO_BLOCK_SIZE     (3)

// values for flags field
#define NBD_FLAG_HAS_FLAGS      (1 << 0)        // Flags are there 
#define NBD_FLAG_READ_ONLY      (1 << 1)        // Device is read-only 
#define NBD_FLAG_SEND_FLUSH     (1 << 2)        // Send FLUSH 
#define NBD_FLAG_SEND_FUA       (1 << 3)        // Send FUA (Force Unit Access) 
#define NBD_FLAG_ROTATIONAL     (1 << 4)        // Use elevator algorithm - rotational media 
#define NBD_FLAG_SEND_TRIM      (1 << 5)        // Send TRIM (discard) 
#define NBD_FLAG_SEND_WRITE_ZEROES (1 << 6)     // Send NBD_CMD_WRITE_ZEROES 
#define NBD_FLAG_CAN_MULTI_CONN (1 << 8)        // multiple connections are okay 


*/

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}