| 1 | package Net::Curl::Promiser::FDFHStore; | ||
| 2 | |||
| 3 | # Mojo::IOLoop doesn’t track FDs, just Perl filehandles. That means | ||
| 4 | # that, in order to track libcurl’s file descriptors, we have to | ||
| 5 | # create Perl filehandles for them. But we also have to ensure that | ||
| 6 | # those filehandles aren’t garbage-collected (GC) because GC will | ||
| 7 | # cause Perl to close() the file descriptors, which will break | ||
| 8 | # libcurl. | ||
| 9 | # | ||
| 10 | # So we keep a reference to each created socket via this object. | ||
| 11 | # | ||
| 12 | # The above problem appears to affect IO::Async as well, | ||
| 13 | # but not AnyEvent. | ||
| 14 | |||
| 15 | sub new { bless {}, shift } | ||
| 16 | |||
| 17 | sub _create { | ||
| 18 | open my $s, '+>>&=' . $_[0] or die "FD ($_[0]) to Perl FH failed: $!"; | ||
| 19 | $s; | ||
| 20 | } | ||
| 21 | |||
| 22 | sub get_checked { | ||
| 23 | if (my $s = $_[0]->{ $_[1] }) { | ||
| 24 | |||
| 25 | # What if libcurl has closed the underlying file descriptor, though? | ||
| 26 | # We need to ensure that that hasn’t happened; if it has, then | ||
| 27 | # get rid of the filehandle and create a new one. This incurs an | ||
| 28 | # unfortunate overhead, but is there a better way? | ||
| 29 | return $s if _fh_is_active($s); | ||
| 30 | } | ||
| 31 | |||
| 32 | return $_[0]->{ $_[1] } = _create( $_[1] ); | ||
| 33 | } | ||
| 34 | |||
| 35 | sub _fh_is_active { | ||
| 36 | local $!; | ||
| 37 | |||
| 38 | stat $_[0] or do { | ||
| 39 | return 0 if $!{'EBADF'}; | ||
| 40 | die "stat() on socket: $!"; | ||
| 41 | }; | ||
| 42 | |||
| 43 | return 1; | ||
| 44 | } | ||
| 45 | |||
| 46 | 1; |