# This module allows a CGI Perl script to be remotely-debugged. # # It's designed to be run this way, from a CGI script: # our $DEBUG_PORT = 49999; # do '/home/newcum/perl_CGI_debug.pl'; # These two lines should be placed at the VERY TOP of the CGI script -- the Perl # script that it's placed in will be restarted under debug mode if necessary. # # Then, install one of these in your favorite browser: # https://chrome.google.com/webstore/detail/user-agent-switcher-for-c/djflhoibgkdhkhhcedjiklpkjnoahfmg?hl=en-US # https://addons.mozilla.org/en-US/firefox/addon/uaswitcher/ # and configure your browser to send a User-Agent string that includes "<>". This is the # signal that triggers the Perl debugger to be started. use Sys::Hostname (); # Perl core use POSIX (); # Perl core if (!$DEBUG_PORT) { print "Content-Type: text/plain\n\n"; print "Error: \$DEBUG_PORT wasn't set before do '", __FILE__, "' was called.\n"; exit; } # Did the user try to trigger a remote debugging session? if ($ENV{HTTP_USER_AGENT} =~ /<>/ && !$INC{'perl5db.pl'}) { my $pid = fork(); defined($pid) or die "couldn't fork: $!"; if (!$pid) { # detach from the parent process (somewhat) open STDIN, '<', '/dev/null'; open STDOUT, '>', '/dev/null'; # Restart Perl with debugging mode enabled. # 'Enbugger' would be *really* handy here, but unfortunately it hasn't # been updated in 8 years, and appears to have stopped working a while # ago. # http://matrix.cpantesters.org/?dist=Enbugger $ENV{PERLDB_OPTS} = "RemotePort=127.0.0.1:$DEBUG_PORT"; exec("perl", "-d", $0, '-emacs', @ARGV); die "Couldn't exec perl -d: $!"; } else { # Okay, we're going to send a CGI response to the websever. But first, # hang around for a few seconds to see if the child dies prematurely. sleep(2); # Check if the Perl debugger is still running. my $ret = waitpid($pid, POSIX::WNOHANG); print "Content-Type: text/plain\n\n"; if ($ret == $pid) { print "The Perl debugger exited prematurely. You will need to have this running on ", Sys::Hostname::hostname(), " BEFORE running this CGI script:\n"; print " while true; do nc -l $DEBUG_PORT; echo 'Disconnected. Waiting for another connection...'; done\n"; } else { print "The debugger successfully connected to localhost:$DEBUG_PORT.\n"; } exit(0); } }