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
<()>>;
53 /// Allow using trait objects for generics taking a `SeqWrite`.
54 impl<S
> SeqWrite
for &mut S
62 ) -> Poll
<io
::Result
<usize>> {
64 self.map_unchecked_mut(|this
| &mut **this
)
65 .poll_seq_write(cx
, buf
)
69 fn poll_flush(self: Pin
<&mut Self>, cx
: &mut Context
) -> Poll
<io
::Result
<()>> {
70 unsafe { self.map_unchecked_mut(|this| &mut **this).poll_flush(cx) }
74 /// awaitable verison of `poll_seq_write`.
75 async
fn seq_write
<T
: SeqWrite
+ ?Sized
>(
79 ) -> io
::Result
<usize> {
81 poll_fn(|cx
| unsafe { Pin::new_unchecked(&mut *output).poll_seq_write(cx, buf) }
).await?
;
82 *position
+= put
as u64;
86 /// Write the entire contents of a buffer, handling short writes.
87 async
fn seq_write_all
<T
: SeqWrite
+ ?Sized
>(
92 while !buf
.is_empty() {
93 let got
= seq_write(&mut *output
, buf
, &mut *position
).await?
;
99 /// Write an endian-swappable struct.
100 async
fn seq_write_struct
<E
: Endian
, T
>(
106 T
: SeqWrite
+ ?Sized
,
108 let data
= data
.to_le();
110 unsafe { std::slice::from_raw_parts(&data as *const E as *const u8, size_of_val(&data)) }
;
111 seq_write_all(output
, buf
, position
).await
114 /// Write a pxar entry.
115 async
fn seq_write_pxar_entry
<T
>(
122 T
: SeqWrite
+ ?Sized
,
124 let header
= format
::Header
::with_content_size(htype
, data
.len() as u64);
125 header
.check_header_size()?
;
127 seq_write_struct(&mut *output
, header
, &mut *position
).await?
;
128 seq_write_all(output
, data
, position
).await
131 /// Write a pxar entry terminated by an additional zero which is not contained in the provided
133 async
fn seq_write_pxar_entry_zero
<T
>(
140 T
: SeqWrite
+ ?Sized
,
142 let header
= format
::Header
::with_content_size(htype
, 1 + data
.len() as u64);
143 header
.check_header_size()?
;
145 seq_write_struct(&mut *output
, header
, &mut *position
).await?
;
146 seq_write_all(&mut *output
, data
, &mut *position
).await?
;
147 seq_write_all(output
, &[0u8], position
).await
150 /// Write a pxar entry consiting of an endian-swappable struct.
151 async
fn seq_write_pxar_struct_entry
<E
, T
>(
158 T
: SeqWrite
+ ?Sized
,
161 let data
= data
.to_le();
163 unsafe { std::slice::from_raw_parts(&data as *const E as *const u8, size_of_val(&data)) }
;
164 seq_write_pxar_entry(output
, htype
, buf
, position
).await
167 /// Error conditions caused by wrong usage of this crate.
168 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
169 pub enum EncodeError
{
170 /// The user dropped a `File` without without finishing writing all of its contents.
172 /// This is required because the payload lengths is written out at the begining and decoding
173 /// requires there to follow the right amount of data.
176 /// The user dropped a directory without finalizing it.
178 /// Finalizing is required to build the goodbye table at the end of a directory.
183 struct EncoderState
{
184 /// Goodbye items for this directory, excluding the tail.
185 items
: Vec
<GoodbyeItem
>,
187 /// User caused error conditions.
188 encode_error
: Option
<EncodeError
>,
190 /// Offset of this directory's ENTRY.
193 /// Offset to this directory's first FILENAME.
196 /// If this is a subdirectory, this points to the this directory's FILENAME.
197 file_offset
: Option
<u64>,
199 /// If this is a subdirectory, this contains this directory's hash for the goodbye item.
202 /// We need to keep track how much we have written to get offsets.
207 fn merge_error(&mut self, error
: Option
<EncodeError
>) {
208 // one error is enough:
209 if self.encode_error
.is_none() {
210 self.encode_error
= error
;
214 fn add_error(&mut self, error
: EncodeError
) {
215 self.merge_error(Some(error
));
219 pub(crate) enum EncoderOutput
<'a
, T
> {
224 impl<'a
, T
> EncoderOutput
<'a
, T
> {
226 fn to_borrowed
<'s
>(&'s
mut self) -> EncoderOutput
<'s
, T
>
230 EncoderOutput
::Borrowed(self.as_mut())
234 impl<'a
, T
> std
::convert
::AsMut
<T
> for EncoderOutput
<'a
, T
> {
235 fn as_mut(&mut self) -> &mut T
{
237 EncoderOutput
::Owned(o
) => o
,
238 EncoderOutput
::Borrowed(b
) => b
,
243 impl<'a
, T
> std
::convert
::From
<T
> for EncoderOutput
<'a
, T
> {
244 fn from(t
: T
) -> Self {
245 EncoderOutput
::Owned(t
)
249 impl<'a
, T
> std
::convert
::From
<&'a
mut T
> for EncoderOutput
<'a
, T
> {
250 fn from(t
: &'a
mut T
) -> Self {
251 EncoderOutput
::Borrowed(t
)
255 /// The encoder state machine implementation for a directory.
257 /// We use `async fn` to implement the encoder state machine so that we can easily plug in both
258 /// synchronous or `async` I/O objects in as output.
259 pub(crate) struct EncoderImpl
<'a
, T
: SeqWrite
+ 'a
> {
260 output
: EncoderOutput
<'a
, T
>,
262 parent
: Option
<&'a
mut EncoderState
>,
265 /// Since only the "current" entry can be actively writing files, we share the file copy
267 file_copy_buffer
: Arc
<Mutex
<Vec
<u8>>>,
270 impl<'a
, T
: SeqWrite
+ 'a
> Drop
for EncoderImpl
<'a
, T
> {
272 if let Some(ref mut parent
) = self.parent
{
274 parent
.merge_error(self.state
.encode_error
);
276 parent
.add_error(EncodeError
::IncompleteDirectory
);
278 } else if !self.finished
{
279 // FIXME: how do we deal with this?
280 // eprintln!("Encoder dropped without finishing!");
285 impl<'a
, T
: SeqWrite
+ 'a
> EncoderImpl
<'a
, T
> {
287 output
: EncoderOutput
<'a
, T
>,
289 ) -> io
::Result
<EncoderImpl
<'a
, T
>> {
290 if !metadata
.is_dir() {
291 io_bail
!("directory metadata must contain the directory mode flag");
293 let mut this
= Self {
295 state
: EncoderState
::default(),
298 file_copy_buffer
: Arc
::new(Mutex
::new(crate::util
::vec_new(1024 * 1024))),
301 this
.encode_metadata(metadata
).await?
;
302 this
.state
.files_offset
= this
.position();
307 fn check(&self) -> io
::Result
<()> {
308 match self.state
.encode_error
{
309 Some(EncodeError
::IncompleteFile
) => io_bail
!("incomplete file"),
310 Some(EncodeError
::IncompleteDirectory
) => io_bail
!("directory not finalized"),
315 pub async
fn create_file
<'b
>(
320 ) -> io
::Result
<FileImpl
<'b
, T
>>
324 self.create_file_do(metadata
, file_name
.as_os_str().as_bytes(), file_size
)
328 async
fn create_file_do
<'b
>(
333 ) -> io
::Result
<FileImpl
<'b
, T
>>
339 let file_offset
= self.position();
340 self.start_file_do(Some(metadata
), file_name
).await?
;
342 let header
= format
::Header
::with_content_size(format
::PXAR_PAYLOAD
, file_size
);
343 header
.check_header_size()?
;
345 seq_write_struct(self.output
.as_mut(), header
, &mut self.state
.write_position
).await?
;
347 let payload_data_offset
= self.position();
349 let meta_size
= payload_data_offset
- file_offset
;
352 output
: self.output
.as_mut(),
353 goodbye_item
: GoodbyeItem
{
354 hash
: format
::hash_filename(file_name
),
356 size
: file_size
+ meta_size
,
358 remaining_size
: file_size
,
359 parent
: &mut self.state
,
363 /// Return a file offset usable with `add_hardlink`.
364 pub async
fn add_file(
369 content
: &mut dyn SeqRead
,
370 ) -> io
::Result
<LinkOffset
> {
371 let buf
= Arc
::clone(&self.file_copy_buffer
);
372 let mut file
= self.create_file(metadata
, file_name
, file_size
).await?
;
373 let mut buf
= buf
.lock().expect("failed to lock temporary buffer mutex");
375 let got
= decoder
::seq_read(&mut *content
, &mut buf
[..]).await?
;
379 file
.write_all(&buf
[..got
]).await?
;
382 Ok(file
.file_offset())
385 /// Return a file offset usable with `add_hardlink`.
386 pub async
fn add_symlink(
391 ) -> io
::Result
<()> {
392 let target
= target
.as_os_str().as_bytes();
393 let mut data
= Vec
::with_capacity(target
.len() + 1);
396 let _ofs
: LinkOffset
= self
400 Some((format
::PXAR_SYMLINK
, &data
)),
406 /// Return a file offset usable with `add_hardlink`.
407 pub async
fn add_hardlink(
411 target_offset
: LinkOffset
,
412 ) -> io
::Result
<()> {
413 let current_offset
= self.position();
414 if current_offset
<= target_offset
.0 {
415 io_bail
!("invalid hardlink offset, can only point to prior files");
418 let offset_bytes
= (current_offset
- target_offset
.0).to_le_bytes();
419 let target_bytes
= target
.as_os_str().as_bytes();
420 let mut hardlink
= Vec
::with_capacity(offset_bytes
.len() + target_bytes
.len() + 1);
421 hardlink
.extend(&offset_bytes
);
422 hardlink
.extend(target_bytes
);
424 let _this_offset
: LinkOffset
= self
425 .add_file_entry(None
, file_name
, Some((format
::PXAR_HARDLINK
, &hardlink
)))
430 /// Return a file offset usable with `add_hardlink`.
431 pub async
fn add_device(
435 device
: format
::Device
,
436 ) -> io
::Result
<()> {
437 if !metadata
.is_device() {
438 io_bail
!("entry added via add_device must have a device mode in its metadata");
441 let device
= device
.to_le();
442 let device
= unsafe {
443 std
::slice
::from_raw_parts(
444 &device
as *const format
::Device
as *const u8,
445 size_of
::<format
::Device
>(),
448 let _ofs
: LinkOffset
= self
452 Some((format
::PXAR_DEVICE
, device
)),
458 /// Return a file offset usable with `add_hardlink`.
459 pub async
fn add_fifo(&mut self, metadata
: &Metadata
, file_name
: &Path
) -> io
::Result
<()> {
460 if !metadata
.is_fifo() {
461 io_bail
!("entry added via add_device must be of type fifo in its metadata");
464 let _ofs
: LinkOffset
= self.add_file_entry(Some(metadata
), file_name
, None
).await?
;
468 /// Return a file offset usable with `add_hardlink`.
469 pub async
fn add_socket(&mut self, metadata
: &Metadata
, file_name
: &Path
) -> io
::Result
<()> {
470 if !metadata
.is_socket() {
471 io_bail
!("entry added via add_device must be of type socket in its metadata");
474 let _ofs
: LinkOffset
= self.add_file_entry(Some(metadata
), file_name
, None
).await?
;
478 /// Return a file offset usable with `add_hardlink`.
479 async
fn add_file_entry(
481 metadata
: Option
<&Metadata
>,
483 entry_htype_data
: Option
<(u64, &[u8])>,
484 ) -> io
::Result
<LinkOffset
> {
487 let file_offset
= self.position();
489 let file_name
= file_name
.as_os_str().as_bytes();
491 self.start_file_do(metadata
, file_name
).await?
;
492 if let Some((htype
, entry_data
)) = entry_htype_data
{
493 seq_write_pxar_entry(
494 self.output
.as_mut(),
497 &mut self.state
.write_position
,
502 let end_offset
= self.position();
504 self.state
.items
.push(GoodbyeItem
{
505 hash
: format
::hash_filename(file_name
),
507 size
: end_offset
- file_offset
,
510 Ok(LinkOffset(file_offset
))
514 fn position(&mut self) -> u64 {
515 self.state
.write_position
518 pub async
fn create_directory(
522 ) -> io
::Result
<EncoderImpl
<'_
, T
>> {
525 if !metadata
.is_dir() {
526 io_bail
!("directory metadata must contain the directory mode flag");
529 let file_name
= file_name
.as_os_str().as_bytes();
530 let file_hash
= format
::hash_filename(file_name
);
532 let file_offset
= self.position();
533 self.encode_filename(file_name
).await?
;
535 let entry_offset
= self.position();
536 self.encode_metadata(&metadata
).await?
;
538 let files_offset
= self.position();
540 // the child will write to OUR state now:
541 let write_position
= self.position();
543 let file_copy_buffer
= Arc
::clone(&self.file_copy_buffer
);
546 // always forward as Borrowed(), to avoid stacking references on nested calls
547 output
: self.output
.to_borrowed(),
548 state
: EncoderState
{
551 file_offset
: Some(file_offset
),
556 parent
: Some(&mut self.state
),
562 async
fn start_file_do(
564 metadata
: Option
<&Metadata
>,
566 ) -> io
::Result
<()> {
567 self.encode_filename(file_name
).await?
;
568 if let Some(metadata
) = metadata
{
569 self.encode_metadata(&metadata
).await?
;
574 async
fn encode_metadata(&mut self, metadata
: &Metadata
) -> io
::Result
<()> {
575 seq_write_pxar_struct_entry(
576 self.output
.as_mut(),
578 metadata
.stat
.clone(),
579 &mut self.state
.write_position
,
583 for xattr
in &metadata
.xattrs
{
584 self.write_xattr(xattr
).await?
;
587 self.write_acls(&metadata
.acl
).await?
;
589 if let Some(fcaps
) = &metadata
.fcaps
{
590 self.write_file_capabilities(fcaps
).await?
;
593 if let Some(qpid
) = &metadata
.quota_project_id
{
594 self.write_quota_project_id(qpid
).await?
;
600 async
fn write_xattr(&mut self, xattr
: &format
::XAttr
) -> io
::Result
<()> {
601 seq_write_pxar_entry(
602 self.output
.as_mut(),
605 &mut self.state
.write_position
,
610 async
fn write_acls(&mut self, acl
: &crate::Acl
) -> io
::Result
<()> {
611 for acl
in &acl
.users
{
612 seq_write_pxar_struct_entry(
613 self.output
.as_mut(),
614 format
::PXAR_ACL_USER
,
616 &mut self.state
.write_position
,
621 for acl
in &acl
.groups
{
622 seq_write_pxar_struct_entry(
623 self.output
.as_mut(),
624 format
::PXAR_ACL_GROUP
,
626 &mut self.state
.write_position
,
631 if let Some(acl
) = &acl
.group_obj
{
632 seq_write_pxar_struct_entry(
633 self.output
.as_mut(),
634 format
::PXAR_ACL_GROUP_OBJ
,
636 &mut self.state
.write_position
,
641 if let Some(acl
) = &acl
.default {
642 seq_write_pxar_struct_entry(
643 self.output
.as_mut(),
644 format
::PXAR_ACL_DEFAULT
,
646 &mut self.state
.write_position
,
651 for acl
in &acl
.default_users
{
652 seq_write_pxar_struct_entry(
653 self.output
.as_mut(),
654 format
::PXAR_ACL_DEFAULT_USER
,
656 &mut self.state
.write_position
,
661 for acl
in &acl
.default_groups
{
662 seq_write_pxar_struct_entry(
663 self.output
.as_mut(),
664 format
::PXAR_ACL_DEFAULT_GROUP
,
666 &mut self.state
.write_position
,
674 async
fn write_file_capabilities(&mut self, fcaps
: &format
::FCaps
) -> io
::Result
<()> {
675 seq_write_pxar_entry(
676 self.output
.as_mut(),
679 &mut self.state
.write_position
,
684 async
fn write_quota_project_id(
686 quota_project_id
: &format
::QuotaProjectId
,
687 ) -> io
::Result
<()> {
688 seq_write_pxar_struct_entry(
689 self.output
.as_mut(),
690 format
::PXAR_QUOTA_PROJID
,
692 &mut self.state
.write_position
,
697 async
fn encode_filename(&mut self, file_name
: &[u8]) -> io
::Result
<()> {
698 crate::util
::validate_filename(file_name
)?
;
699 seq_write_pxar_entry_zero(
700 self.output
.as_mut(),
701 format
::PXAR_FILENAME
,
703 &mut self.state
.write_position
,
708 pub async
fn finish(mut self) -> io
::Result
<()> {
709 let tail_bytes
= self.finish_goodbye_table().await?
;
710 seq_write_pxar_entry(
711 self.output
.as_mut(),
712 format
::PXAR_GOODBYE
,
714 &mut self.state
.write_position
,
718 // done up here because of the self-borrow and to propagate
719 let end_offset
= self.position();
721 if let Some(parent
) = &mut self.parent
{
722 parent
.write_position
= end_offset
;
724 let file_offset
= self
727 .expect("internal error: parent set but no file_offset?");
729 parent
.items
.push(GoodbyeItem
{
730 hash
: self.state
.file_hash
,
732 size
: end_offset
- file_offset
,
735 self.finished
= true;
739 async
fn finish_goodbye_table(&mut self) -> io
::Result
<Vec
<u8>> {
740 let goodbye_offset
= self.position();
742 // "take" out the tail (to not leave an array of endian-swapped structs in `self`)
743 let mut tail
= take(&mut self.state
.items
);
744 let tail_size
= (tail
.len() + 1) * size_of
::<GoodbyeItem
>();
745 let goodbye_size
= tail_size
as u64 + size_of
::<format
::Header
>() as u64;
747 // sort, then create a BST
748 tail
.sort_unstable_by(|a
, b
| a
.hash
.cmp(&b
.hash
));
750 let mut bst
= Vec
::with_capacity(tail
.len() + 1);
752 bst
.set_len(tail
.len());
754 binary_tree_array
::copy(tail
.len(), |src
, dest
| {
755 let mut item
= tail
[src
].clone();
756 // fixup the goodbye table offsets to be relative and with the right endianess
757 item
.offset
= goodbye_offset
- item
.offset
;
759 std
::ptr
::write(&mut bst
[dest
], item
.to_le());
766 hash
: format
::PXAR_GOODBYE_TAIL_MARKER
,
767 offset
: goodbye_offset
- self.state
.entry_offset
,
773 // turn this into a byte vector since after endian-swapping we can no longer guarantee that
774 // the items make sense:
775 let data
= bst
.as_mut_ptr() as *mut u8;
776 let capacity
= bst
.capacity() * size_of
::<GoodbyeItem
>();
778 Ok(unsafe { Vec::from_raw_parts(data, tail_size, capacity) }
)
782 /// Writer for a file object in a directory.
783 pub struct FileImpl
<'a
, S
: SeqWrite
> {
786 /// This file's `GoodbyeItem`. FIXME: We currently don't touch this, can we just push it
787 /// directly instead of on Drop of FileImpl?
788 goodbye_item
: GoodbyeItem
,
790 /// While writing data to this file, this is how much space we still have left, this must reach
794 /// The directory containing this file. This is where we propagate the `IncompleteFile` error
795 /// to, and where we insert our `GoodbyeItem`.
796 parent
: &'a
mut EncoderState
,
799 impl<'a
, S
: SeqWrite
> Drop
for FileImpl
<'a
, S
> {
801 if self.remaining_size
!= 0 {
802 self.parent
.add_error(EncodeError
::IncompleteFile
);
805 self.parent
.items
.push(self.goodbye_item
.clone());
809 impl<'a
, S
: SeqWrite
> FileImpl
<'a
, S
> {
810 /// Get the file offset to be able to reference it with `add_hardlink`.
811 pub fn file_offset(&self) -> LinkOffset
{
812 LinkOffset(self.goodbye_item
.offset
)
815 fn check_remaining(&self, size
: usize) -> io
::Result
<()> {
816 if size
as u64 > self.remaining_size
{
817 io_bail
!("attempted to write more than previously allocated");
823 /// Poll write interface to more easily connect to tokio/futures.
824 #[cfg(feature = "tokio-io")]
826 self: Pin
<&mut Self>,
829 ) -> Poll
<io
::Result
<usize>> {
830 let this
= self.get_mut();
831 this
.check_remaining(data
.len())?
;
832 let output
= unsafe { Pin::new_unchecked(&mut *this.output) }
;
833 match output
.poll_seq_write(cx
, data
) {
834 Poll
::Ready(Ok(put
)) => {
835 this
.remaining_size
-= put
as u64;
836 this
.parent
.write_position
+= put
as u64;
843 /// Poll flush interface to more easily connect to tokio/futures.
844 #[cfg(feature = "tokio-io")]
845 pub fn poll_flush(self: Pin
<&mut Self>, cx
: &mut Context
) -> Poll
<io
::Result
<()>> {
846 unsafe { self.map_unchecked_mut(|this| this.output).poll_flush(cx) }
849 /// Poll close/shutdown interface to more easily connect to tokio/futures.
851 /// This just calls flush, though, since we're just a virtual writer writing to the file
852 /// provided by our encoder.
853 #[cfg(feature = "tokio-io")]
854 pub fn poll_close(self: Pin
<&mut Self>, cx
: &mut Context
) -> Poll
<io
::Result
<()>> {
855 unsafe { self.map_unchecked_mut(|this| this.output).poll_flush(cx) }
858 /// Write file data for the current file entry in a pxar archive.
860 /// This forwards to the output's `SeqWrite::poll_seq_write` and may write fewer bytes than
861 /// requested. Check the return value for how many. There's also a `write_all` method available
863 pub async
fn write(&mut self, data
: &[u8]) -> io
::Result
<usize> {
864 self.check_remaining(data
.len())?
;
866 poll_fn(|cx
| unsafe { Pin::new_unchecked(&mut self.output).poll_seq_write(cx, data) }
)
868 //let put = seq_write(self.output.as_mut().unwrap(), data).await?;
869 self.remaining_size
-= put
as u64;
870 self.parent
.write_position
+= put
as u64;
874 /// Completely write file data for the current file entry in a pxar archive.
875 pub async
fn write_all(&mut self, data
: &[u8]) -> io
::Result
<()> {
876 self.check_remaining(data
.len())?
;
877 seq_write_all(self.output
, data
, &mut self.parent
.write_position
).await?
;
878 self.remaining_size
-= data
.len() as u64;
883 #[cfg(feature = "tokio-io")]
884 impl<'a
, S
: SeqWrite
> tokio
::io
::AsyncWrite
for FileImpl
<'a
, S
> {
885 fn poll_write(self: Pin
<&mut Self>, cx
: &mut Context
, buf
: &[u8]) -> Poll
<io
::Result
<usize>> {
886 FileImpl
::poll_write(self, cx
, buf
)
889 fn poll_flush(self: Pin
<&mut Self>, cx
: &mut Context
) -> Poll
<io
::Result
<()>> {
890 FileImpl
::poll_flush(self, cx
)
893 fn poll_shutdown(self: Pin
<&mut Self>, cx
: &mut Context
) -> Poll
<io
::Result
<()>> {
894 FileImpl
::poll_close(self, cx
)