
package Proc::Prefork;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(initialisation_complete);

use Carp;
use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
use POSIX;
use Sys::Syslog;

our $logger;

our $env_name = 'PREFORK_INTERP';

our @call_fds;
our $socket_path;

sub server_quit ($) {
  my ($m) = @_;
  syslog(LOG_INFO, "$0 prefork [$$]: $m, quitting");
  _exit(0);
}

# Returns in the executor process
sub become_monitor () {
  my $child = fork // fail("fork executor: $!");
  if (!$child) {
    #---- executor ----
    open ::STDIN , "<& $call_fds[0]" or fail("dup for fd0");
    open ::STDOUT, ">& $call_fds[1]" or fail("dup for fd1");
    open ::STDERR, ">& $call_fds[2]" or fail("dup for fd2");
    POSIX::close($_) foreach @call_fds;
    close CALL;
    return;
  }

  #---- monitor [2] ----
  my $got = waitpid $child, 0 // fail("wait for executor: $!");
  $got == $child or fail("wait for esecutor gave $got, expected $child");

  protocol_write(pack "L", $?);
  _exit(0);
}

sub protocol_write ($) {
  my ($d) = @_;
  return if (print CALL $d and flush CALL);
  _exit(0) if $!==EPIPE || $!==ECONNRESET;
  fail("protocol write: $!");
}

sub eintr_retry ($) {
  my ($f) = @_;
  for (;;) {
    my $r = $f->();
    return $r if defined $r;
    next if $!==EINTR;
    return $r;
  }
}

sub protocol_read_fail ($) {
  my ($what) = @_;
  _exit(0) if $!==ECONNRESET;
  fail("recv $what: $!");
}

sub protocol_exchange () {
  protocol_write('\n');

  @call_fds = map {
    my $r;
    for (;;) {
      $! = 0;
      $r = IO::FDPass::recv(fileno(CALL));
      last if $r >= 0;
      _exit(0) if $!==0;
      protocol_read_fail("fd $_");
    }
    $r;
  } 0..2;

  my $len;
  $r = read(CALL, $len, 4) // protocol_read_fail("message length");
  $r == 4 or _exit(0);

  $len = unpack "L", $len;
  my $data;
  $r = read(CALL, $data, $len) // protocol_read_fail("message data ($len)");
  $r == $len or _exit(0);

  @ARGV = split /\0/, $data;
  @ARGV >= 2 or fail("message data has too few strings");
  length(pop(@ARGV)) and fail("message data missing trailing nul");
  %ENV = ();
  while (my $s = shift @ARGV) {
    last if !length $s;
    $s =~ m/=/ or fail("message data env var missing equals");
    $ENV{$`} = $';
  }
}

sub initialisation_complete {
  my %opts = @_;

  # if env var not set, we're not running under prefork-interp
  my @env_params = split /,/, ($ENV{$env_name} // return), 5;
  croak "$env_name has too few entries" unless @env_params == 5;

  $num_servers = $opts{max_servers} // 4;

  #---- setup (pm) [1] ----

  $socket_path = pop @env_params;
  foreach (@env_params) {
    $_ eq ($_+0) or croak "$env_name contains $_, not a number";
  }
  open LISTEN, "+>&=$env_params[0]" or croak "listen fd: $!";
  open CALL,   "+>&=$env_params[1]" or croak "listen fd: $!";
  @call_fds = ($env_params[2], $env_params[3], 2);

  if (!$opts{no_openlog}) {
    openlog("prefork-interp $0", 'ndelay,nofatal,pid',
	    $opts{log_facility} // 'log_user');
  }

  open NULL, "+>/dev/null" or croak "open /dev/null: $!";

  #---- fork for server ----

  my $child = fork // croak "first fork failed: $!";
  if ($child) {
    #---- setup (pm) [2], exits ----
    _exit(0);
  }

  #---- server(pm) [1] ----

  $child = fork // croak "second fork failed: $!";
  if (!$child) {
    # we are the child, i.e. the one fa-monitor
    return become_monitor();
  }

  our %children;
  $children{$child} = 1;
  
  # --- server(pm) [2] ----

  setsid() > 0 or fail("setsid: $!");
  open STDIN, "<&NULL" or fail("dup null onto stdin: $!");
  open STDOUT, ">&NULL" or fail("dup null onto stdout: $!");
  open STDERR, ">&NULL" or fail("dup null onto stderr: $!");
  close NULL;

  POSIX::close($_) foreach @call_fds;
  close CALL;

  my $flags = fcntl(LISTEN, F_GETFL, 0) or fail("F_GETFL listen socket: $!");
  $flags |= O_NONBLOCK;
  fcntl(LISTEN, F_SETFL, $flags) or fail("F_SETFL listen socket: $!");

  my $errcount = 0;

  for (;;) {
    # reap children
    if (%children) {
      my $full = %children >= $num_servers;
      my $got = waitpid -1, ($full ? 0 : WNOHANG);
      if ($?) {
	syslog(LOG_WARNING,
 "$0 prefork [$$]: monitor process [$got] failed with wait status $?");
      }
      if (!exists $children{$got}) {
	syslog(LOG_WARNING,
 "$0 prefork [$$]: monitor process [$got] wasn't one of ours?!");
      }
      delete $children{$got};
      next;
    }

    # select for accepting or housekeeping timeout
    my $rbits = '';
    vec($rbits, fileno(LISTEN), 1) = 1;
    my $ebits = $rbits;
    my $nfound = select($rbits, '', $ebits, ($opts{check_interval} // 300));

    if ($nfound) {
      if (accept(CALL, LISTEN)) {
	$child = fork // fail("fork for accepted call failed: $!");
	if (!$child) {
	  #---- monitor [1] ----
	  close LISTEN;
	  protocol_exchange();
	  return become_monitor();
	}
	close(CALL);
	$errcount = 0;
	$children{$child} = 1;
      } elsif ($! == EINTR || $! == EAGAIN || $! == EWOULDBLOCK) {
      } else {
	syslog(LOG_WARNING, "$0 prefork [$$]: accept failed: $!");
	if ($errcount > ($opts{max_errors} // 100)) {
	  syslog(LOG_ERR,
		 "$0 prefork [$$]: too many accept failures, quitting");
	  _exit(16);
	}
      }
      next;
    }

    # are we still live?
    my @st_listen = stat(LISTEN) // fail("fstat listening socket: $!");
    my @st_socket = stat($socket_path) // do {
      if ($! == ENOENT) { server_quit("socket $socket is ENOENT"); }
      fail("stat socket $socket: $!");
    };
    if ("@st_listen[0..2]" ne "@st_socket[0..2]") {
      server_quit("socket $socket is no longer ours");
    }
  }
}

1;

__END__
