blib/lib/AnyEvent/Util.pm untested

filter: Statementstmt 0.0% 0 / 278 Branchbran 0.0% 0 / 104 Conditioncond 0.0% 0 / 94 MC/DCmcdc 0.0% 0 / 53 Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 571 CC 48 SCAR 49.9
CC
48
Cov
0%
run_cmd
420.0
_fork_schedule
132.0
BEGIN
72.0
CRAP 146.5
1 =head1 NAME
2  
3 AnyEvent::Util - various utility functions.
4  
5 =head1 SYNOPSIS
6  
7 use AnyEvent::Util;
8  
9 =head1 DESCRIPTION
10  
11 This module implements various utility functions, mostly replacing
12 well-known functions by event-ised counterparts.
13  
14 All functions documented without C<AnyEvent::Util::> prefix are exported
15 by default.
16  
17 =over 4
18  
19 =cut
20  
21 package AnyEvent::Util;
22  
23 use Carp ();
24 use Errno ();
25 use Socket ();
26  
27 use AnyEvent (); BEGIN { AnyEvent::common_sense }
28  
29 use base 'Exporter';
30  
31 our @EXPORT = qw(fh_nonblocking guard fork_call portable_pipe portable_socketpair run_cmd);
32 our @EXPORT_OK = qw(AF_INET6 WSAEWOULDBLOCK WSAEINPROGRESS WSAEINVAL close_all_fds_except);
33  
34 our $VERSION = $AnyEvent::VERSION;
35  
36 BEGIN {
37 my $af_inet6 = eval { local $SIG{__DIE__}; &Socket::AF_INET6 };
38  
39 # uhoh
40 $af_inet6 ||= 10 if $^O =~ /linux/;
41 $af_inet6 ||= 23 if $^O =~ /cygwin/i;
42 $af_inet6 ||= 23 if AnyEvent::WIN32;
43 $af_inet6 ||= 24 if $^O =~ /openbsd|netbsd/;
44 $af_inet6 ||= 28 if $^O =~ /freebsd/;
45  
46 $af_inet6 && socket my $ipv6_socket, $af_inet6, &Socket::SOCK_STREAM, 0 # check if they can be created
47 or $af_inet6 = 0;
48  
49 eval "sub AF_INET6() { $af_inet6 }"; die if $@;
50  
51 delete $AnyEvent::PROTOCOL{ipv6} unless $af_inet6;
52 }
53  
54 BEGIN {
55 # broken windows perls use undocumented error codes...
56 if (AnyEvent::WIN32) {
57 eval "sub WSAEINVAL () { 10022 }";
58 eval "sub WSAEWOULDBLOCK () { 10035 }";
59 eval "sub WSAEINPROGRESS () { 10036 }";
60 } else {
61 # these should never match any errno value
62 eval "sub WSAEINVAL () { -1e99 }";
63 eval "sub WSAEWOULDBLOCK () { -1e99 }";
64 eval "sub WSAEINPROGRESS () { -1e99 }";
65 }
66  
67 # fix buggy Errno on some non-POSIX platforms
68 # such as openbsd and windows.
69 my %ERR = (
70 EBADMSG => Errno::EDOM (),
71 EPROTO => Errno::ESPIPE (),
72 );
73  
74 while (my ($k, $v) = each %ERR) {
75 next if eval "Errno::$k ()";
76 warn "AnyEvent::Util: broken Errno module, adding Errno::$k.\n" if $AnyEvent::VERBOSE >= 8;
77  
78 eval "sub Errno::$k () { $v }";
79 push @Errno::EXPORT_OK, $k;
80 push @{ $Errno::EXPORT_TAGS{POSIX} }, $k;
81 }
82 }
83  
84 =item ($r, $w) = portable_pipe
85  
86 Calling C<pipe> in Perl is portable - except it doesn't really work on
87 sucky windows platforms (at least not with most perls - cygwin's perl
88 notably works fine): On windows, you actually get two file handles you
89 cannot use select on.
90  
91 This function gives you a pipe that actually works even on the broken
92 windows platform (by creating a pair of TCP sockets on windows, so do not
93 expect any speed from that, and using C<pipe> everywhere else).
94  
95 See C<portable_socketpair>, below, for a bidirectional "pipe".
96  
97 Returns the empty list on any errors.
98  
99 =item ($fh1, $fh2) = portable_socketpair
100  
101 Just like C<portable_pipe>, above, but returns a bidirectional pipe
102 (usually by calling C<socketpair> to create a local loopback socket pair,
103 except on windows, where it again returns two interconnected TCP sockets).
104  
105 Returns the empty list on any errors.
106  
107 =cut
108  
109 sub _win32_socketpair {
110 # perl's socketpair emulation fails on many vista machines, because
111 # vista returns fantasy port numbers.
112  
113 for (1..10) {
114 socket my $l, &Socket::AF_INET, &Socket::SOCK_STREAM, 0
115 or next;
116  
117 bind $l, Socket::pack_sockaddr_in 0, "\x7f\x00\x00\x01"
118 or next;
119  
120 my $sa = getsockname $l
121 or next;
122  
123 listen $l, 1
124 or next;
125  
126 socket my $r, &Socket::AF_INET, &Socket::SOCK_STREAM, 0
127 or next;
128  
129 bind $r, Socket::pack_sockaddr_in 0, "\x7f\x00\x00\x01"
130 or next;
131  
132 connect $r, $sa
133 or next;
134  
135 accept my $w, $l
136 or next;
137  
138 # vista has completely broken peername/sockname that return
139 # fantasy ports. this combo seems to work, though.
140 #
141 (Socket::unpack_sockaddr_in getpeername $r)[0]
142 == (Socket::unpack_sockaddr_in getsockname $w)[0]
143 or (($! = WSAEINVAL), next);
144  
145 # vista example (you can't make this shit up...):
146 #(Socket::unpack_sockaddr_in getsockname $r)[0] == 53364
147 #(Socket::unpack_sockaddr_in getpeername $r)[0] == 53363
148 #(Socket::unpack_sockaddr_in getsockname $w)[0] == 53363
149 #(Socket::unpack_sockaddr_in getpeername $w)[0] == 53365
150  
151 return ($r, $w);
152 }
153  
154 ()
155 }
156  
157 sub portable_pipe() {
158 return _win32_socketpair
159 if AnyEvent::WIN32;
160  
161 my ($r, $w);
162  
163 pipe $r, $w
164 or return;
165  
166 ($r, $w);
167 }
168  
169 sub portable_socketpair() {
170 return _win32_socketpair
171 if AnyEvent::WIN32;
172  
173 socketpair my $fh1, my $fh2, &Socket::AF_UNIX, &Socket::SOCK_STREAM, &Socket::PF_UNSPEC
174 or return;
175  
176 ($fh1, $fh2)
177 }
178  
179 =item fork_call { CODE } @args, $cb->(@res)
180  
181 Executes the given code block asynchronously, by forking. Everything the
182 block returns will be transferred to the calling process (by serialising and
183 deserialising via L<Storable>).
184  
185 If there are any errors, then the C<$cb> will be called without any
186 arguments. In that case, either C<$@> contains the exception (and C<$!> is
187 irrelevant), or C<$!> contains an error number. In all other cases, C<$@>
188 will be C<undef>ined.
189  
190 The code block must not ever call an event-polling function or use
191 event-based programming that might cause any callbacks registered in the
192 parent to run.
193  
194 Win32 spoilers: Due to the endlessly sucky and broken native windows
195 perls (there is no way to cleanly exit a child process on that platform
196 that doesn't also kill the parent), you have to make sure that your main
197 program doesn't exit as long as any C<fork_calls> are still in progress,
198 otherwise the program won't exit. Also, on most windows platforms some
199 memory will leak for every invocation. We are open for improvements that
200 don't require XS hackery.
201  
202 Note that forking can be expensive in large programs (RSS 200MB+). On
203 windows, it is abysmally slow, do not expect more than 5..20 forks/s on
204 that sucky platform (note this uses perl's pseudo-threads, so avoid those
205 like the plague).
206  
207 Example: poor man's async disk I/O (better use L<IO::AIO>).
208  
209 fork_call {
210 open my $fh, "</etc/passwd"
211 or die "passwd: $!";
212 local $/;
213 <$fh>
214 } sub {
215 my ($passwd) = @_;
216 ...
217 };
218  
219 =item $AnyEvent::Util::MAX_FORKS [default: 10]
220  
221 The maximum number of child processes that C<fork_call> will fork in
222 parallel. Any additional requests will be queued until a slot becomes free
223 again.
224  
225 The environment variable C<PERL_ANYEVENT_MAX_FORKS> is used to initialise
226 this value.
227  
228 =cut
229  
230 our $MAX_FORKS = int 1 * $ENV{PERL_ANYEVENT_MAX_FORKS};
231 $MAX_FORKS = 10 if $MAX_FORKS <= 0;
232  
233 my $forks;
234 my @fork_queue;
235  
236 sub _fork_schedule;
237 sub _fork_schedule {
238 require Storable;
239 require POSIX;
240  
241 while ($forks < $MAX_FORKS) {
242 my $job = shift @fork_queue
243 or last;
244  
245 ++$forks;
246  
247 my $coderef = shift @$job;
248 my $cb = pop @$job;
249
250 # gimme a break...
251 my ($r, $w) = portable_pipe
252 or ($forks and last) # allow failures when we have at least one job
253 or die "fork_call: $!";
254  
255 my $pid = fork;
256  
257 if ($pid != 0) {
258 # parent
259 close $w;
260  
261 my $buf;
262  
263 my $ww; $ww = AE::io $r, 0, sub {
264 my $len = sysread $r, $buf, 65536, length $buf;
265  
266 if ($len <= 0) {
267 undef $ww;
268 close $r;
269 --$forks;
270 _fork_schedule;
271
272 my $result = eval { Storable::thaw ($buf) };
273 $result = [$@] unless $result;
274 $@ = shift @$result;
275  
276 $cb->(@$result);
277  
278 # work around the endlessly broken windows perls
279 kill 9, $pid if AnyEvent::WIN32;
280  
281 # clean up the pid
282 waitpid $pid, 0;
283 }
284 };
285  
286 } elsif (defined $pid) {
287 # child
288 close $r;
289  
290 my $result = eval {
291 local $SIG{__DIE__};
292  
293 Storable::freeze ([undef, $coderef->(@$job)])
294 };
295  
296 $result = Storable::freeze (["$@"])
297 if $@;
298  
299 # windows forces us to these contortions
300 my $ofs;
301  
302 while () {
303 my $len = (length $result) - $ofs
304 or last;
305  
306 $len = syswrite $w, $result, $len < 65536 ? $len : 65536, $ofs;
307  
308 last if $len <= 0;
309  
310 $ofs += $len;
311 }
312  
313 # on native windows, _exit KILLS YOUR FORKED CHILDREN!
314 if (AnyEvent::WIN32) {
315 shutdown $w, 1; # signal parent to please kill us
316 sleep 10; # give parent a chance to clean up
317 sysread $w, (my $buf), 1; # this *might* detect the parent exiting in some cases.
318 }
319 POSIX::_exit (0);
320 exit 1;
321
322 } elsif (($! != &Errno::EAGAIN && $! != &Errno::ENOMEM) || !$forks) {
323 # we ignore some errors as long as we can run at least one job
324 # maybe we should wait a few seconds and retry instead
325 die "fork_call: $!";
326 }
327 }
328 }
329  
330 sub fork_call(&@) {
331 push @fork_queue, [@_];
332 _fork_schedule;
333 }
334  
335 END {
336 if (AnyEvent::WIN32) {
337 while ($forks) {
338 @fork_queue = ();
339 AnyEvent->one_event;
340 }
341 }
342 }
343  
344 # to be removed
345 sub dotted_quad($) {
346 $_[0] =~ /^(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9][0-9]?)
347 \.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9][0-9]?)
348 \.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9][0-9]?)
349 \.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9][0-9]?)$/x
350 }
351  
352 # just a forwarder
353 sub inet_aton {
354 require AnyEvent::Socket;
355 *inet_aton = \&AnyEvent::Socket::inet_aton;
356 goto &inet_aton
357 }
358  
359 =item fh_nonblocking $fh, $nonblocking
360  
361 Sets the blocking state of the given filehandle (true == nonblocking,
362 false == blocking). Uses fcntl on anything sensible and ioctl FIONBIO on
363 broken (i.e. windows) platforms.
364  
365 =cut
366  
367 sub fh_nonblocking($$) {
368 my ($fh, $nb) = @_;
369  
370 require Fcntl;
371  
372 if (AnyEvent::WIN32) {
373 $nb = (! ! $nb) + 0;
374 ioctl $fh, 0x8004667e, \$nb; # FIONBIO
375 } else {
376 fcntl $fh, &Fcntl::F_SETFL, $nb ? &Fcntl::O_NONBLOCK : 0;
377 }
378 }
379  
380 =item $guard = guard { CODE }
381  
382 This function creates a special object that, when called, will execute the
383 code block.
384  
385 This is often handy in continuation-passing style code to clean up some
386 resource regardless of where you break out of a process.
387  
388 The L<Guard> module will be used to implement this function, if it is
389 available. Otherwise a pure-perl implementation is used.
390  
391 You can call one method on the returned object:
392  
393 =item $guard->cancel
394  
395 This simply causes the code block not to be invoked: it "cancels" the
396 guard.
397  
398 =cut
399  
400 if (!$ENV{PERL_ANYEVENT_AVOID_GUARD} && eval { require Guard; $Guard::VERSION >= 0.5 }) {
401 warn "AnyEvent::Util: using Guard module to implement guards.\n" if $AnyEvent::VERBOSE >= 8;
402 *guard = \&Guard::guard;
403 } else {
404 warn "AnyEvent::Util: using pure-perl guard implementation.\n" if $AnyEvent::VERBOSE >= 8;
405  
406 *AnyEvent::Util::guard::DESTROY = sub {
407 local $@;
408  
409 eval {
410 local $SIG{__DIE__};
411 ${$_[0]}->();
412 };
413  
414 warn "runtime error in AnyEvent::guard callback: $@" if $@;
415 };
416  
417 *AnyEvent::Util::guard::cancel = sub ($) {
418 ${$_[0]} = sub { };
419 };
420  
421 *guard = sub (&) {
422 bless \(my $cb = shift), "AnyEvent::Util::guard"
423 };
424 }
425  
426 =item AnyEvent::Util::close_all_fds_except @fds
427  
428 This rarely-used function simply closes all file descriptors (or tries to)
429 of the current process except the ones given as arguments.
430  
431 When you want to start a long-running background server, then it is often
432 beneficial to do this, as too many C-libraries are too stupid to mark
433 their internal fd's as close-on-exec.
434  
435 The function expects to be called shortly before an C<exec> call.
436  
437 Example: close all fds except 0, 1, 2.
438  
439 close_all_fds_except 0, 2, 1;
440  
441 =cut
442  
443 sub close_all_fds_except {
444 my %except; @except{@_} = ();
445  
446 require POSIX;
447  
448 # some OSes have a usable /dev/fd, sadly, very few
449 if ($^O =~ /(freebsd|cygwin|linux)/) {
450 # netbsd, openbsd, solaris have a broken /dev/fd
451 my $dir;
452 if (opendir $dir, "/dev/fd" or opendir $dir, "/proc/self/fd") {
453 my @fds = sort { $a <=> $b } grep /^\d+$/, readdir $dir;
454 # broken OS's have device nodes for 0..63 usually, solaris 0..255
455 if (@fds < 20 or "@fds" ne join " ", 0..$#fds) {
456 # assume the fds array is valid now
457 exists $except{$_} or POSIX::close ($_)
458 for @fds;
459 return;
460 }
461 }
462 }
463  
464 my $fd_max = eval { POSIX::sysconf (POSIX::_SC_OPEN_MAX ()) - 1 } || 1023;
465  
466 exists $except{$_} or POSIX::close ($_)
467 for 0..$fd_max;
468 }
469  
470 =item $cv = run_cmd $cmd, key => value...
471  
472 Run a given external command, potentially redirecting file descriptors and
473 return a condition variable that gets sent the exit status (like C<$?>)
474 when the program exits I<and> all redirected file descriptors have been
475 exhausted.
476  
477 The C<$cmd> is either a single string, which is then passed to a shell, or
478 an arrayref, which is passed to the C<execvp> function.
479  
480 The key-value pairs can be:
481  
482 =over 4
483  
484 =item ">" => $filename
485  
486 Redirects program standard output into the specified filename, similar to C<<
487 >filename >> in the shell.
488  
489 =item ">" => \$data
490  
491 Appends program standard output to the referenced scalar. The condvar will
492 not be signalled before EOF or an error is signalled.
493  
494 =item ">" => $filehandle
495  
496 Redirects program standard output to the given filehandle (or actually its
497 underlying file descriptor).
498  
499 =item ">" => $callback->($data)
500  
501 Calls the given callback each time standard output receives some data,
502 passing it the data received. On EOF or error, the callback will be
503 invoked once without any arguments.
504  
505 The condvar will not be signalled before EOF or an error is signalled.
506  
507 =item "fd>" => $see_above
508  
509 Like ">", but redirects the specified fd number instead.
510  
511 =item "<" => $see_above
512  
513 The same, but redirects the program's standard input instead. The same
514 forms as for ">" are allowed.
515  
516 In the callback form, the callback is supposed to return data to be
517 written, or the empty list or C<undef> or a zero-length scalar to signal
518 EOF.
519  
520 Similarly, either the write data must be exhausted or an error is to be
521 signalled before the condvar is signalled, for both string-reference and
522 callback forms.
523  
524 =item "fd<" => $see_above
525  
526 Like "<", but redirects the specified file descriptor instead.
527  
528 =item on_prepare => $cb
529  
530 Specify a callback that is executed just before the comamnd is C<exec>'ed,
531 in the child process. Be careful not to use any event handling or other
532 services not available in the child.
533  
534 This can be useful to set up the environment in special ways, such as
535 changing the priority of the command.
536  
537 =item close_all => $boolean
538  
539 When C<close_all> is enabled (default is disabled), then all extra file
540 descriptors will be closed, except the ones that were redirected and C<0>,
541 C<1> and C<2>.
542  
543 See C<close_all_fds_except> for more details.
544  
545 =item '$$' => \$pid
546  
547 A reference to a scalar which will receive the PID of the newly-created
548 subprocess after C<run_cmd> returns.
549  
550 Note the the PID might already have been recycled and used by an unrelated
551 process at the time C<run_cmd> returns, so it's not useful to send
552 signals, use a unique key in data structures and so on.
553  
554 =back
555  
556 Example: run C<rm -rf />, redirecting standard input, output and error to
557 F</dev/null>.
558  
559 my $cv = run_cmd [qw(rm -rf /)],
560 "<", "/dev/null",
561 ">", "/dev/null",
562 "2>", "/dev/null";
563 $cv->recv and die "d'oh! something survived!"
564  
565 Example: run F<openssl> and create a self-signed certificate and key,
566 storing them in C<$cert> and C<$key>. When finished, check the exit status
567 in the callback and print key and certificate.
568  
569 my $cv = run_cmd [qw(openssl req
570 -new -nodes -x509 -days 3650
571 -newkey rsa:2048 -keyout /dev/fd/3
572 -batch -subj /CN=AnyEvent
573 )],
574 "<", "dev/null",
575 ">" , \my $cert,
576 "3>", \my $key,
577 "2>", "/dev/null";
578  
579 $cv->cb (sub {
580 shift->recv and die "openssl failed";
581  
582 print "$key\n$cert\n";
583 });
584  
585 =cut
586  
587 sub run_cmd {
588 my $cmd = shift;
589  
590 require POSIX;
591  
592 my $cv = AE::cv;
593  
594 my %arg;
595 my %redir;
596 my @exe;
597  
598 while (@_) {
599 my ($type, $ob) = splice @_, 0, 2;
600  
601 my $fd = $type =~ s/^(\d+)// ? $1 : undef;
602  
603 if ($type eq ">") {
604 $fd = 1 unless defined $fd;
605  
606 if (defined eval { fileno $ob }) {
607 $redir{$fd} = $ob;
608 } elsif (ref $ob) {
609 my ($pr, $pw) = AnyEvent::Util::portable_pipe;
610 $cv->begin;
611 my $w; $w = AE::io $pr, 0,
612 "SCALAR" eq ref $ob
613 ? sub {
614 sysread $pr, $$ob, 16384, length $$ob
615 and return;
616 undef $w; $cv->end;
617 }
618 : sub {
619 my $buf;
620 sysread $pr, $buf, 16384
621 and return $ob->($buf);
622 undef $w; $cv->end;
623 $ob->();
624 }
625 ;
626 $redir{$fd} = $pw;
627 } else {
628 push @exe, sub {
629 open my $fh, ">", $ob
630 or POSIX::_exit (125);
631 $redir{$fd} = $fh;
632 };
633 }
634  
635 } elsif ($type eq "<") {
636 $fd = 0 unless defined $fd;
637  
638 if (defined eval { fileno $ob }) {
639 $redir{$fd} = $ob;
640 } elsif (ref $ob) {
641 my ($pr, $pw) = AnyEvent::Util::portable_pipe;
642 $cv->begin;
643  
644 my $data;
645 if ("SCALAR" eq ref $ob) {
646 $data = $$ob;
647 $ob = sub { };
648 } else {
649 $data = $ob->();
650 }
651  
652 my $w; $w = AE::io $pw, 1, sub {
653 my $len = syswrite $pw, $data;
654  
655 if ($len <= 0) {
656 undef $w; $cv->end;
657 } else {
658 substr $data, 0, $len, "";
659 unless (length $data) {
660 $data = $ob->();
661 unless (length $data) {
662 undef $w; $cv->end
663 }
664 }
665 }
666 };
667  
668 $redir{$fd} = $pr;
669 } else {
670 push @exe, sub {
671 open my $fh, "<", $ob
672 or POSIX::_exit (125);
673 $redir{$fd} = $fh;
674 };
675 }
676  
677 } else {
678 $arg{$type} = $ob;
679 }
680 }
681  
682 my $pid = fork;
683  
684 defined $pid
685 or Carp::croak "fork: $!";
686  
687 unless ($pid) {
688 # step 1, execute
689 $_->() for @exe;
690  
691 # step 2, move any existing fd's out of the way
692 # this also ensures that dup2 is never called with fd1==fd2
693 # so the cloexec flag is always cleared
694 my (@oldfh, @close);
695 for my $fh (values %redir) {
696 push @oldfh, $fh; # make sure we keep it open
697 $fh = fileno $fh; # we only want the fd
698  
699 # dup if we are in the way
700 # if we "leak" fds here, they will be dup2'ed over later
701 defined ($fh = POSIX::dup ($fh)) or POSIX::_exit (124)
702 while exists $redir{$fh};
703 }
704  
705 # step 3, execute redirects
706 while (my ($k, $v) = each %redir) {
707 defined POSIX::dup2 ($v, $k)
708 or POSIX::_exit (123);
709 }
710  
711 # step 4, close everything else, except 0, 1, 2
712 if ($arg{close_all}) {
713 close_all_fds_except 0, 1, 2, keys %redir
714 } else {
715 POSIX::close ($_)
716 for values %redir;
717 }
718  
719 eval { $arg{on_prepare}(); 1 } or POSIX::_exit (123)
720 if exists $arg{on_prepare};
721  
722 ref $cmd
723 ? exec {$cmd->[0]} @$cmd
724 : exec $cmd;
725  
726 POSIX::_exit (126);
727 }
728  
729 ${$arg{'$$'}} = $pid
730 if $arg{'$$'};
731  
732 %redir = (); # close child side of the fds
733  
734 my $status;
735 $cv->begin (sub { shift->send ($status) });
736 my $cw; $cw = AE::child $pid, sub {
737 $status = $_[1];
738 undef $cw; $cv->end;
739 };
740  
741 $cv
742 }
743 1;
744  
745 =back
746  
747 =head1 AUTHOR
748  
749 Marc Lehmann <schmorp@schmorp.de>
750 http://home.schmorp.de/
751  
752 =cut
753