1 //! The `pxar` encoder state machine.
3 //! This is the implementation used by both the synchronous and async pxar wrappers.
6 use std
::mem
::{forget, size_of, size_of_val, take}
;
7 use std
::os
::unix
::ffi
::OsStrExt
;
10 use std
::sync
::{Arc, Mutex}
;
11 use std
::task
::{Context, Poll}
;
13 use endian_trait
::Endian
;
15 use crate::binary_tree_array
;
16 use crate::decoder
::{self, SeqRead}
;
17 use crate::format
::{self, GoodbyeItem}
;
18 use crate::poll_fn
::poll_fn
;
25 pub use sync
::Encoder
;
27 /// File reference used to create hard links.
28 #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
29 pub struct LinkOffset(u64);
33 pub fn raw(self) -> u64 {
38 /// Sequential write interface used by the encoder's state machine.
40 /// This is our internal writer trait which is available for `std::io::Write` types in the
41 /// synchronous wrapper and for both `tokio` and `future` `AsyncWrite` types in the asynchronous
48 ) -> Poll
<io
::Result
<usize>>;
50 fn poll_flush(self: Pin
<&mut Self>, cx
: &mut Context
) -> Poll
<io
::Result
<()>>;
52 /// To avoid recursively borrowing each time we nest into a subdirectory we add this helper.
53 /// Otherwise starting a subdirectory will get a trait object pointing to `T`, nesting another
54 /// subdirectory in that would have a trait object pointing to the trait object, and so on.
55 fn as_trait_object(&mut self) -> &mut dyn SeqWrite
59 self as &mut dyn SeqWrite
63 /// Allow using trait objects for generics taking a `SeqWrite`.
64 impl<'a
> SeqWrite
for &mut (dyn SeqWrite
+ 'a
) {
69 ) -> Poll
<io
::Result
<usize>> {
71 self.map_unchecked_mut(|this
| &mut **this
)
72 .poll_seq_write(cx
, buf
)
76 fn poll_flush(self: Pin
<&mut Self>, cx
: &mut Context
) -> Poll
<io
::Result
<()>> {
77 unsafe { self.map_unchecked_mut(|this| &mut **this).poll_flush(cx) }
80 fn as_trait_object(&mut self) -> &mut dyn SeqWrite
88 /// awaitable verison of `poll_seq_write`.
89 async
fn seq_write
<T
: SeqWrite
+ ?Sized
>(
93 ) -> io
::Result
<usize> {
95 poll_fn(|cx
| unsafe { Pin::new_unchecked(&mut *output).poll_seq_write(cx, buf) }
).await?
;
96 *position
+= put
as u64;
100 /// Write the entire contents of a buffer, handling short writes.
101 async
fn seq_write_all
<T
: SeqWrite
+ ?Sized
>(
105 ) -> io
::Result
<()> {
106 while !buf
.is_empty() {
107 let got
= seq_write(&mut *output
, buf
, &mut *position
).await?
;
113 /// Write an endian-swappable struct.
114 async
fn seq_write_struct
<E
: Endian
, T
>(
120 T
: SeqWrite
+ ?Sized
,
122 let data
= data
.to_le();
124 unsafe { std::slice::from_raw_parts(&data as *const E as *const u8, size_of_val(&data)) }
;
125 seq_write_all(output
, buf
, position
).await
128 /// Write a pxar entry.
129 async
fn seq_write_pxar_entry
<T
>(
136 T
: SeqWrite
+ ?Sized
,
138 let header
= format
::Header
::with_content_size(htype
, data
.len() as u64);
139 header
.check_header_size()?
;
141 seq_write_struct(&mut *output
, header
, &mut *position
).await?
;
142 seq_write_all(output
, data
, position
).await
145 /// Write a pxar entry terminated by an additional zero which is not contained in the provided
147 async
fn seq_write_pxar_entry_zero
<T
>(
154 T
: SeqWrite
+ ?Sized
,
156 let header
= format
::Header
::with_content_size(htype
, 1 + data
.len() as u64);
157 header
.check_header_size()?
;
159 seq_write_struct(&mut *output
, header
, &mut *position
).await?
;
160 seq_write_all(&mut *output
, data
, &mut *position
).await?
;
161 seq_write_all(output
, &[0u8], position
).await
164 /// Write a pxar entry consiting of an endian-swappable struct.
165 async
fn seq_write_pxar_struct_entry
<E
, T
>(
172 T
: SeqWrite
+ ?Sized
,
175 let data
= data
.to_le();
177 unsafe { std::slice::from_raw_parts(&data as *const E as *const u8, size_of_val(&data)) }
;
178 seq_write_pxar_entry(output
, htype
, buf
, position
).await
181 /// Error conditions caused by wrong usage of this crate.
182 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
183 pub enum EncodeError
{
184 /// The user dropped a `File` without without finishing writing all of its contents.
186 /// This is required because the payload lengths is written out at the begining and decoding
187 /// requires there to follow the right amount of data.
190 /// The user dropped a directory without finalizing it.
192 /// Finalizing is required to build the goodbye table at the end of a directory.
197 struct EncoderState
{
198 /// Goodbye items for this directory, excluding the tail.
199 items
: Vec
<GoodbyeItem
>,
201 /// User caused error conditions.
202 encode_error
: Option
<EncodeError
>,
204 /// Offset of this directory's ENTRY.
207 /// Offset to this directory's first FILENAME.
210 /// If this is a subdirectory, this points to the this directory's FILENAME.
211 file_offset
: Option
<u64>,
213 /// If this is a subdirectory, this contains this directory's hash for the goodbye item.
216 /// We need to keep track how much we have written to get offsets.
221 fn merge_error(&mut self, error
: Option
<EncodeError
>) {
222 // one error is enough:
223 if self.encode_error
.is_none() {
224 self.encode_error
= error
;
228 fn add_error(&mut self, error
: EncodeError
) {
229 self.merge_error(Some(error
));
233 /// The encoder state machine implementation for a directory.
235 /// We use `async fn` to implement the encoder state machine so that we can easily plug in both
236 /// synchronous or `async` I/O objects in as output.
237 pub(crate) struct EncoderImpl
<'a
, T
: SeqWrite
+ 'a
> {
240 parent
: Option
<&'a
mut EncoderState
>,
243 /// Since only the "current" entry can be actively writing files, we share the file copy
245 file_copy_buffer
: Arc
<Mutex
<Vec
<u8>>>,
248 impl<'a
, T
: SeqWrite
+ 'a
> Drop
for EncoderImpl
<'a
, T
> {
250 if let Some(ref mut parent
) = self.parent
{
252 parent
.merge_error(self.state
.encode_error
);
254 parent
.add_error(EncodeError
::IncompleteDirectory
);
256 } else if !self.finished
{
257 // FIXME: how do we deal with this?
258 // eprintln!("Encoder dropped without finishing!");
263 impl<'a
, T
: SeqWrite
+ 'a
> EncoderImpl
<'a
, T
> {
264 pub async
fn new(output
: T
, metadata
: &Metadata
) -> io
::Result
<EncoderImpl
<'a
, T
>> {
265 if !metadata
.is_dir() {
266 io_bail
!("directory metadata must contain the directory mode flag");
268 let mut this
= Self {
269 output
: Some(output
),
270 state
: EncoderState
::default(),
273 file_copy_buffer
: Arc
::new(Mutex
::new(crate::util
::vec_new(1024 * 1024))),
276 this
.encode_metadata(metadata
).await?
;
277 this
.state
.files_offset
= this
.position();
282 fn check(&self) -> io
::Result
<()> {
283 match self.state
.encode_error
{
284 Some(EncodeError
::IncompleteFile
) => io_bail
!("incomplete file"),
285 Some(EncodeError
::IncompleteDirectory
) => io_bail
!("directory not finalized"),
290 pub async
fn create_file
<'b
>(
295 ) -> io
::Result
<FileImpl
<'b
>>
299 self.create_file_do(metadata
, file_name
.as_os_str().as_bytes(), file_size
)
303 async
fn create_file_do
<'b
>(
308 ) -> io
::Result
<FileImpl
<'b
>>
314 let file_offset
= self.position();
315 self.start_file_do(Some(metadata
), file_name
).await?
;
317 let header
= format
::Header
::with_content_size(format
::PXAR_PAYLOAD
, file_size
);
318 header
.check_header_size()?
;
321 self.output
.as_mut().unwrap(),
323 &mut self.state
.write_position
,
327 let payload_data_offset
= self.position();
329 let meta_size
= payload_data_offset
- file_offset
;
332 output
: self.output
.as_mut().unwrap(),
333 goodbye_item
: GoodbyeItem
{
334 hash
: format
::hash_filename(file_name
),
336 size
: file_size
+ meta_size
,
338 remaining_size
: file_size
,
339 parent
: &mut self.state
,
343 /// Return a file offset usable with `add_hardlink`.
344 pub async
fn add_file(
349 content
: &mut dyn SeqRead
,
350 ) -> io
::Result
<LinkOffset
> {
351 let buf
= Arc
::clone(&self.file_copy_buffer
);
352 let mut file
= self.create_file(metadata
, file_name
, file_size
).await?
;
353 let mut buf
= buf
.lock().expect("failed to lock temporary buffer mutex");
355 let got
= decoder
::seq_read(&mut *content
, &mut buf
[..]).await?
;
359 file
.write_all(&buf
[..got
]).await?
;
362 Ok(file
.file_offset())
365 /// Return a file offset usable with `add_hardlink`.
366 pub async
fn add_symlink(
371 ) -> io
::Result
<()> {
372 let target
= target
.as_os_str().as_bytes();
373 let mut data
= Vec
::with_capacity(target
.len() + 1);
376 let _ofs
: LinkOffset
= self
380 Some((format
::PXAR_SYMLINK
, &data
)),
386 /// Return a file offset usable with `add_hardlink`.
387 pub async
fn add_hardlink(
391 target_offset
: LinkOffset
,
392 ) -> io
::Result
<()> {
393 let current_offset
= self.position();
394 if current_offset
<= target_offset
.0 {
395 io_bail
!("invalid hardlink offset, can only point to prior files");
398 let offset_bytes
= (current_offset
- target_offset
.0).to_le_bytes();
399 let target_bytes
= target
.as_os_str().as_bytes();
400 let mut hardlink
= Vec
::with_capacity(offset_bytes
.len() + target_bytes
.len() + 1);
401 hardlink
.extend(&offset_bytes
);
402 hardlink
.extend(target_bytes
);
404 let _this_offset
: LinkOffset
= self
405 .add_file_entry(None
, file_name
, Some((format
::PXAR_HARDLINK
, &hardlink
)))
410 /// Return a file offset usable with `add_hardlink`.
411 pub async
fn add_device(
415 device
: format
::Device
,
416 ) -> io
::Result
<()> {
417 if !metadata
.is_device() {
418 io_bail
!("entry added via add_device must have a device mode in its metadata");
421 let device
= device
.to_le();
422 let device
= unsafe {
423 std
::slice
::from_raw_parts(
424 &device
as *const format
::Device
as *const u8,
425 size_of
::<format
::Device
>(),
428 let _ofs
: LinkOffset
= self
432 Some((format
::PXAR_DEVICE
, device
)),
438 /// Return a file offset usable with `add_hardlink`.
439 pub async
fn add_fifo(&mut self, metadata
: &Metadata
, file_name
: &Path
) -> io
::Result
<()> {
440 if !metadata
.is_fifo() {
441 io_bail
!("entry added via add_device must be of type fifo in its metadata");
444 let _ofs
: LinkOffset
= self.add_file_entry(Some(metadata
), file_name
, None
).await?
;
448 /// Return a file offset usable with `add_hardlink`.
449 pub async
fn add_socket(&mut self, metadata
: &Metadata
, file_name
: &Path
) -> io
::Result
<()> {
450 if !metadata
.is_socket() {
451 io_bail
!("entry added via add_device must be of type socket in its metadata");
454 let _ofs
: LinkOffset
= self.add_file_entry(Some(metadata
), file_name
, None
).await?
;
458 /// Return a file offset usable with `add_hardlink`.
459 async
fn add_file_entry(
461 metadata
: Option
<&Metadata
>,
463 entry_htype_data
: Option
<(u64, &[u8])>,
464 ) -> io
::Result
<LinkOffset
> {
467 let file_offset
= self.position();
469 let file_name
= file_name
.as_os_str().as_bytes();
471 self.start_file_do(metadata
, file_name
).await?
;
472 if let Some((htype
, entry_data
)) = entry_htype_data
{
473 seq_write_pxar_entry(
474 self.output
.as_mut().unwrap(),
477 &mut self.state
.write_position
,
482 let end_offset
= self.position();
484 self.state
.items
.push(GoodbyeItem
{
485 hash
: format
::hash_filename(file_name
),
487 size
: end_offset
- file_offset
,
490 Ok(LinkOffset(file_offset
))
494 fn position(&mut self) -> u64 {
495 self.state
.write_position
498 pub async
fn create_directory
<'b
>(
502 ) -> io
::Result
<EncoderImpl
<'b
, &'b
mut dyn SeqWrite
>>
508 if !metadata
.is_dir() {
509 io_bail
!("directory metadata must contain the directory mode flag");
512 let file_name
= file_name
.as_os_str().as_bytes();
513 let file_hash
= format
::hash_filename(file_name
);
515 let file_offset
= self.position();
516 self.encode_filename(file_name
).await?
;
518 let entry_offset
= self.position();
519 self.encode_metadata(&metadata
).await?
;
521 let files_offset
= self.position();
523 // the child will write to OUR state now:
524 let write_position
= self.position();
527 output
: self.output
.as_mut().map(SeqWrite
::as_trait_object
),
528 state
: EncoderState
{
531 file_offset
: Some(file_offset
),
536 parent
: Some(&mut self.state
),
538 file_copy_buffer
: Arc
::clone(&self.file_copy_buffer
),
542 async
fn start_file_do(
544 metadata
: Option
<&Metadata
>,
546 ) -> io
::Result
<()> {
547 self.encode_filename(file_name
).await?
;
548 if let Some(metadata
) = metadata
{
549 self.encode_metadata(&metadata
).await?
;
554 async
fn encode_metadata(&mut self, metadata
: &Metadata
) -> io
::Result
<()> {
555 seq_write_pxar_struct_entry(
556 self.output
.as_mut().unwrap(),
558 metadata
.stat
.clone(),
559 &mut self.state
.write_position
,
563 for xattr
in &metadata
.xattrs
{
564 self.write_xattr(xattr
).await?
;
567 self.write_acls(&metadata
.acl
).await?
;
569 if let Some(fcaps
) = &metadata
.fcaps
{
570 self.write_file_capabilities(fcaps
).await?
;
573 if let Some(qpid
) = &metadata
.quota_project_id
{
574 self.write_quota_project_id(qpid
).await?
;
580 async
fn write_xattr(&mut self, xattr
: &format
::XAttr
) -> io
::Result
<()> {
581 seq_write_pxar_entry(
582 self.output
.as_mut().unwrap(),
585 &mut self.state
.write_position
,
590 async
fn write_acls(&mut self, acl
: &crate::Acl
) -> io
::Result
<()> {
591 for acl
in &acl
.users
{
592 seq_write_pxar_struct_entry(
593 self.output
.as_mut().unwrap(),
594 format
::PXAR_ACL_USER
,
596 &mut self.state
.write_position
,
601 for acl
in &acl
.groups
{
602 seq_write_pxar_struct_entry(
603 self.output
.as_mut().unwrap(),
604 format
::PXAR_ACL_GROUP
,
606 &mut self.state
.write_position
,
611 if let Some(acl
) = &acl
.group_obj
{
612 seq_write_pxar_struct_entry(
613 self.output
.as_mut().unwrap(),
614 format
::PXAR_ACL_GROUP_OBJ
,
616 &mut self.state
.write_position
,
621 if let Some(acl
) = &acl
.default {
622 seq_write_pxar_struct_entry(
623 self.output
.as_mut().unwrap(),
624 format
::PXAR_ACL_DEFAULT
,
626 &mut self.state
.write_position
,
631 for acl
in &acl
.default_users
{
632 seq_write_pxar_struct_entry(
633 self.output
.as_mut().unwrap(),
634 format
::PXAR_ACL_DEFAULT_USER
,
636 &mut self.state
.write_position
,
641 for acl
in &acl
.default_groups
{
642 seq_write_pxar_struct_entry(
643 self.output
.as_mut().unwrap(),
644 format
::PXAR_ACL_DEFAULT_GROUP
,
646 &mut self.state
.write_position
,
654 async
fn write_file_capabilities(&mut self, fcaps
: &format
::FCaps
) -> io
::Result
<()> {
655 seq_write_pxar_entry(
656 self.output
.as_mut().unwrap(),
659 &mut self.state
.write_position
,
664 async
fn write_quota_project_id(
666 quota_project_id
: &format
::QuotaProjectId
,
667 ) -> io
::Result
<()> {
668 seq_write_pxar_struct_entry(
669 self.output
.as_mut().unwrap(),
670 format
::PXAR_QUOTA_PROJID
,
672 &mut self.state
.write_position
,
677 async
fn encode_filename(&mut self, file_name
: &[u8]) -> io
::Result
<()> {
678 crate::util
::validate_filename(file_name
)?
;
679 seq_write_pxar_entry_zero(
680 self.output
.as_mut().unwrap(),
681 format
::PXAR_FILENAME
,
683 &mut self.state
.write_position
,
688 pub async
fn finish(mut self) -> io
::Result
<T
> {
689 let tail_bytes
= self.finish_goodbye_table().await?
;
690 seq_write_pxar_entry(
691 self.output
.as_mut().unwrap(),
692 format
::PXAR_GOODBYE
,
694 &mut self.state
.write_position
,
698 // done up here because of the self-borrow and to propagate
699 let end_offset
= self.position();
701 if let Some(parent
) = &mut self.parent
{
702 parent
.write_position
= end_offset
;
704 let file_offset
= self
707 .expect("internal error: parent set but no file_offset?");
709 parent
.items
.push(GoodbyeItem
{
710 hash
: self.state
.file_hash
,
712 size
: end_offset
- file_offset
,
715 self.finished
= true;
716 Ok(self.output
.take().unwrap())
719 pub fn into_writer(mut self) -> T
{
720 self.output
.take().unwrap()
723 async
fn finish_goodbye_table(&mut self) -> io
::Result
<Vec
<u8>> {
724 let goodbye_offset
= self.position();
726 // "take" out the tail (to not leave an array of endian-swapped structs in `self`)
727 let mut tail
= take(&mut self.state
.items
);
728 let tail_size
= (tail
.len() + 1) * size_of
::<GoodbyeItem
>();
729 let goodbye_size
= tail_size
as u64 + size_of
::<format
::Header
>() as u64;
731 // sort, then create a BST
732 tail
.sort_unstable_by(|a
, b
| a
.hash
.cmp(&b
.hash
));
734 let mut bst
= Vec
::with_capacity(tail
.len() + 1);
736 bst
.set_len(tail
.len());
738 binary_tree_array
::copy(tail
.len(), |src
, dest
| {
739 let mut item
= tail
[src
].clone();
740 // fixup the goodbye table offsets to be relative and with the right endianess
741 item
.offset
= goodbye_offset
- item
.offset
;
743 std
::ptr
::write(&mut bst
[dest
], item
.to_le());
750 hash
: format
::PXAR_GOODBYE_TAIL_MARKER
,
751 offset
: goodbye_offset
- self.state
.entry_offset
,
757 // turn this into a byte vector since after endian-swapping we can no longer guarantee that
758 // the items make sense:
759 let data
= bst
.as_mut_ptr() as *mut u8;
760 let capacity
= bst
.capacity() * size_of
::<GoodbyeItem
>();
762 Ok(unsafe { Vec::from_raw_parts(data, tail_size, capacity) }
)
766 /// Writer for a file object in a directory.
767 pub struct FileImpl
<'a
> {
768 output
: &'a
mut dyn SeqWrite
,
770 /// This file's `GoodbyeItem`. FIXME: We currently don't touch this, can we just push it
771 /// directly instead of on Drop of FileImpl?
772 goodbye_item
: GoodbyeItem
,
774 /// While writing data to this file, this is how much space we still have left, this must reach
778 /// The directory containing this file. This is where we propagate the `IncompleteFile` error
779 /// to, and where we insert our `GoodbyeItem`.
780 parent
: &'a
mut EncoderState
,
783 impl<'a
> Drop
for FileImpl
<'a
> {
785 if self.remaining_size
!= 0 {
786 self.parent
.add_error(EncodeError
::IncompleteFile
);
789 self.parent
.items
.push(self.goodbye_item
.clone());
793 impl<'a
> FileImpl
<'a
> {
794 /// Get the file offset to be able to reference it with `add_hardlink`.
795 pub fn file_offset(&self) -> LinkOffset
{
796 LinkOffset(self.goodbye_item
.offset
)
799 fn check_remaining(&self, size
: usize) -> io
::Result
<()> {
800 if size
as u64 > self.remaining_size
{
801 io_bail
!("attempted to write more than previously allocated");
807 /// Poll write interface to more easily connect to tokio/futures.
808 #[cfg(feature = "tokio-io")]
810 self: Pin
<&mut Self>,
813 ) -> Poll
<io
::Result
<usize>> {
814 let this
= self.get_mut();
815 this
.check_remaining(data
.len())?
;
816 let output
= unsafe { Pin::new_unchecked(&mut *this.output) }
;
817 match output
.poll_seq_write(cx
, data
) {
818 Poll
::Ready(Ok(put
)) => {
819 this
.remaining_size
-= put
as u64;
820 this
.parent
.write_position
+= put
as u64;
827 /// Poll flush interface to more easily connect to tokio/futures.
828 #[cfg(feature = "tokio-io")]
829 pub fn poll_flush(self: Pin
<&mut Self>, cx
: &mut Context
) -> Poll
<io
::Result
<()>> {
831 self.map_unchecked_mut(|this
| &mut this
.output
)
836 /// Poll close/shutdown interface to more easily connect to tokio/futures.
838 /// This just calls flush, though, since we're just a virtual writer writing to the file
839 /// provided by our encoder.
840 #[cfg(feature = "tokio-io")]
841 pub fn poll_close(self: Pin
<&mut Self>, cx
: &mut Context
) -> Poll
<io
::Result
<()>> {
843 self.map_unchecked_mut(|this
| &mut this
.output
)
848 /// Write file data for the current file entry in a pxar archive.
850 /// This forwards to the output's `SeqWrite::poll_seq_write` and may write fewer bytes than
851 /// requested. Check the return value for how many. There's also a `write_all` method available
853 pub async
fn write(&mut self, data
: &[u8]) -> io
::Result
<usize> {
854 self.check_remaining(data
.len())?
;
856 poll_fn(|cx
| unsafe { Pin::new_unchecked(&mut self.output).poll_seq_write(cx, data) }
)
858 //let put = seq_write(self.output.as_mut().unwrap(), data).await?;
859 self.remaining_size
-= put
as u64;
860 self.parent
.write_position
+= put
as u64;
864 /// Completely write file data for the current file entry in a pxar archive.
865 pub async
fn write_all(&mut self, data
: &[u8]) -> io
::Result
<()> {
866 self.check_remaining(data
.len())?
;
867 seq_write_all(&mut self.output
, data
, &mut self.parent
.write_position
).await?
;
868 self.remaining_size
-= data
.len() as u64;
873 #[cfg(feature = "tokio-io")]
874 impl<'a
> tokio
::io
::AsyncWrite
for FileImpl
<'a
> {
875 fn poll_write(self: Pin
<&mut Self>, cx
: &mut Context
, buf
: &[u8]) -> Poll
<io
::Result
<usize>> {
876 FileImpl
::poll_write(self, cx
, buf
)
879 fn poll_flush(self: Pin
<&mut Self>, cx
: &mut Context
) -> Poll
<io
::Result
<()>> {
880 FileImpl
::poll_flush(self, cx
)
883 fn poll_shutdown(self: Pin
<&mut Self>, cx
: &mut Context
) -> Poll
<io
::Result
<()>> {
884 FileImpl
::poll_close(self, cx
)