| 1 | package Protocol::DBus::WriteMsg; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use parent qw( IO::Framed::Write ); | ||
| 7 | |||
| 8 | use Socket; | ||
| 9 | use Socket::MsgHdr; | ||
| 10 | |||
| 11 | my %fh_fds; | ||
| 12 | |||
| 13 | sub DESTROY { | ||
| 14 | my ($self) = @_; | ||
| 15 | |||
| 16 | my $fh = delete $fh_fds{ $self->get_write_fh() }; | ||
| 17 | |||
| 18 | return; | ||
| 19 | } | ||
| 20 | |||
| 21 | sub enqueue_message { | ||
| 22 | my ($self, $buf_sr, $fds_ar) = @_; | ||
| 23 | |||
| 24 | push @{ $fh_fds{$self->get_write_fh()} }, ($fds_ar && @$fds_ar) ? $fds_ar : undef; | ||
| 25 | |||
| 26 | $self->write( | ||
| 27 | $$buf_sr, | ||
| 28 | sub { | ||
| 29 | |||
| 30 | # Weâre done with the message, so we remove the FDs entry, | ||
| 31 | # which by here should be undef. | ||
| 32 | shift @{ $fh_fds{$self->get_write_fh()} }; | ||
| 33 | }, | ||
| 34 | ); | ||
| 35 | |||
| 36 | return $self; | ||
| 37 | } | ||
| 38 | |||
| 39 | # Receives ($fh, $buf) | ||
| 40 | sub WRITE { | ||
| 41 | |||
| 42 | # Only use sendmsg if we actually need to. | ||
| 43 | if (my $fds_ar = $fh_fds{ $_[0] }[0]) { | ||
| 44 | my $msg = Socket::MsgHdr->new( buf => $_[1] ); | ||
| 45 | |||
| 46 | $msg->cmsghdr( | ||
| 47 | Socket::SOL_SOCKET(), Socket::SCM_RIGHTS(), | ||
| 48 | pack( 'I!*', @$fds_ar ), | ||
| 49 | ); | ||
| 50 | |||
| 51 | my $bytes = Socket::MsgHdr::sendmsg( $_[0], $msg ); | ||
| 52 | |||
| 53 | # NOTE: This assumes that, on an incomplete write, the ancillary | ||
| 54 | # data (i.e., the FDs) will have been sent, and there is no need | ||
| 55 | # to resend. That appears to be the case on Linux and MacOS, but | ||
| 56 | # I canât find any actual documentation to that effect. <shrug> | ||
| 57 | if ($bytes) { | ||
| 58 | undef $fh_fds{ $_[0] }[0]; | ||
| 59 | } | ||
| 60 | |||
| 61 | return $bytes; | ||
| 62 | } | ||
| 63 | |||
| 64 | goto &IO::Framed::Write::WRITE; | ||
| 65 | } | ||
| 66 | |||
| 67 | 1; |