The most Interesting Code I Have Ever Written

I wrote this about a month back, and Honestly blew my own mind with it. Its far from the best code I have ever written, something which is further exacerbated by the fact that I was shooting to keep it short and small, which never makes your code good, I was also aiming not to use anything that is not a core function in PHP. The flip side is that I used a lot of really uncommon php calls that do some very, very cool things. At one point this was an ajax app, but I discovered that it could be smaller and cleaner by just using frames.

This will be the first post in a series where I go through this code and explain it, and some of the cooler calls that it is using, as well as some advanced php and programming concepts. But for now I’m just going to give a one paragraph overview of what the code does and get it into the post. There is one other file which I will also post and explain at some point.

So read On to take a look at the nitty-gritty, and get a feel for what it does in total

I call this program the introspective debugger. The basic Idea is that you include this file as the first line of any script you are running, and then when you visit the page, rather than getting a normal page, you end up with an interactive debugger. This is done with frames. In one frame you can look at all of the variables, or at the source code with your current line highlighted or the stack trace, In another you can look at the output so far. Sadly at this time you can’t change variables on the fly. You can then tell the program to run again until it hits the next break-point, or until it ends.

Here is the full source code for introspective debugger:

<?php
$idbg_var_exclude_list = array('GLOBALS', '_FILES', '_COOKIE', '_POST', '_GET', 'idbg_var_exclude_list' , 'idbg_stop_flag', 'idbg_var_spy', 'idbg_backtrace');
$old_error_level = error_reporting(0);
if(array_key_exists("idbg_id",$_GET)){
  $idbg_id = $_GET["idbg_id"];
} else {
  $idbg_id = 1025 + rand(5000,8000); // get a random high port
}
$callBackName= htmlspecialchars_decode($_SERVER['SCRIPT_NAME']."?idbg_id=$idbg_id&idbg_mode=");
$callBackWvars= htmlspecialchars_decode($_SERVER['REQUEST_URI'].(strpos($_SERVER['REQUEST_URI'],"?")?"&":"?")."idbg_id=$idbg_id&idbg_mode=");
if(!array_key_exists("idbg_mode",$_GET)){
  /* Display Frame Mode */
  echo("<html>
 <frameset rows='65%,35%'>
   <frame src='$callBackName"."cnc' name='infoframe'>
   <frame src='$callBackWvars"."run' name='scriptframe'>
</frameset>
</html>");
  exit();

} else if (array_key_exists("idbg_mode",$_GET) and ($_GET["idbg_mode"] == "cnc" or $_GET["idbg_mode"] == "fstep")){
  if(array_key_exists("idbg_act",$_GET)){ idbg_socket_client($_GET["idbg_act"]);}
  $responce = unserialize(idbg_socket_client("cnc"));
  if($_GET["idbg_mode"] == "fstep"){ header( "Location: ".$callBackName."file&idbg_open_line=".$responce['trace'][0]['line']. "&idbg_open=".$responce['trace'][0]['file']."#anchor");}
  echo ("<h1> I am Command & Control DIV $idbg_id </h1>");
  echo("[<a href='".$callBackName."cnc' target='infoframe'>CNC</a>] ");
  echo("[<a href='".$callBackName."cnc&idbg_act=step' target='infoframe'>STEP</a>] ");
  echo("[<a href='".$callBackName."cnc&idbg_act=cont' target='infoframe'>CONTINUE</a>]<br/><br/><br/>");
  foreach($responce["trace"] as $key => $val){
    echo("<a href='".$callBackName."file&idbg_open_line=".$val['line'].
	 "&idbg_open=".$val['file']."#anchor' target='infoframe'>".strrchr($val['file'],"/")."</a>");
    echo(" Line:". $val['line'] . " Function:" . $responce["trace"][$key+1]["function"]. "
  <a href='#' onClick="document.getElementById('v_$key').style.display='block'">+</a>
          <div id='v_$key' style='display:none'><pre>");
    print_r($responce["vars"][$responce["trace"][$key+1]["function"]]);
    echo("</pre></div><hr/>");
  }
  exit();

} else if (array_key_exists("idbg_mode",$_GET) && $_GET["idbg_mode"] == "file"){
  echo("[<a href='".$callBackName."cnc' target='infoframe'>CNC</a>] ");
  echo("[<a href='".$callBackName."fstep&idbg_act=step' target='infoframe'>STEP</a>] ");
  echo("[<a href='".$callBackName."fstep&idbg_act=cont' target='infoframe'>CONTINUE</a>]<br/><br/><br/>
        <div style='background-color:#CCC'>");
   $fp = fopen($_GET["idbg_open"],"r");
   $current_line = 0;
   while(!feof($fp)){
    $current_line++;
    if($current_line < $_GET["idbg_open_line"]){
      $top .= (fgets($fp));
    }else if($current_line == $_GET["idbg_open_line"]){
      $keyline.= (fgets($fp));
    } else {
      $bottom .= (fgets($fp));
    }
   }
   
   echo(str_replace("a7R4449p","<a name='anchor'/>
        <div style='background-color:#BBF;border: thin solid #000'>",str_replace("b7R4449p","</div>",
	highlight_string($top . "a7R4449p". $keyline ."b7R4449p" . $bottom, TRUE))));
   echo("</div>");
  fclose($fp);
  exit();


} else if (array_key_exists("idbg_mode",$_GET) && $_GET["idbg_mode"] == "run"){
  echo ("<h1> I am running DIV $idbg_id </h1>");
  register_tick_function("idbg_tick_function");
}

function idbg_socket_client($msg){
  global $idbg_id;
  //echo ("=>".$msg."<BR/>");flush();
  do {
    usleep(rand(50000,150000));
    $conn = stream_socket_client("tcp://".$_SERVER["REMOTE_ADDR"].":$idbg_id", $errno, $errstr);
    //echo($errstr . "<= ");flush();
  } while($errno == 111);

  if (!$conn) { echo "Debugger couldn't visit socket: $errstr ($errno)<br />\n"; } else {
    fwrite($conn, $msg);
    while (!feof($conn)) {
      $responce .= fgets($conn, 1024);
      //echo ("->".$responce);flush();
    }
    fclose($conn);
    return($responce);
  }
}

function idbg_tick_function(){
  global $idbg_stop_flag, $idbg_id, $idbg_var_spy, $idbg_last_line, $idbg_backtrace;
  $idbg_backtrace = debug_backtrace();
  //  echo ($idbg_last_line. " ?= " .$idbg_backtrace[0]['line'] ." in ".$idbg_backtrace[0]['file']."<Br/>" );
  if($idbg_stop_flag and $idbg_last_line != $idbg_backtrace[0]['line'] and !strpos($idbg_backtrace[0]['file'], 'STOP.php')){
    //echo("</hr> idbg_tick_function START <br/>");
    $socket = stream_socket_server("tcp://".$_SERVER["REMOTE_ADDR"].":$idbg_id", $errno, $errstr);
    if (!$socket) { echo "<h1>Debugger couldn't open socket: $errstr ($errno)<h1/>\n";} else {
      while ($conn = stream_socket_accept($socket)) {
	$msgIn = fread($conn, 1024);
	echo($msgIn);
	flush();
	if ($msgIn == 'cnc'){
	  fwrite($conn, serialize(array("trace"=>$idbg_backtrace,"vars" => $idbg_var_spy)));
	} else if ($msgIn == 'step'){
	  fclose($conn);
	  fclose($socket);
	  $idbg_last_line = $idbg_backtrace[0]['line'];
	  return(TRUE);
	} else if ($msgIn == 'cont'){
	  //	  fwrite($conn, "ACK");
	  fclose($conn);
	  fclose($socket);
	  $idbg_last_line = 0;
	  $idbg_stop_flag = FALSE;
	  return(TRUE);
	} else {
	  fwrite($conn, " This is a SERVER Responce \n");
	}
	fclose($conn);
      }
      fclose($socket);
    }
  }
}//else just keep going
error_reporting($old_error_level);

?>

2 thoughts on “The most Interesting Code I Have Ever Written”

  1. Hrm, looks like wordpress is interpreting the ht ml tags from inside my code, I will come back and clean up this post soon so it can actually be read

  2. It looks like the root mechanisms are debug_backtrace(), which tells you the runtime position, and register_tick_function(), which allows you to hook your debugger code into the execution sequence. The rest of the code appears to coordinate their operation and allows those PHP APIs to be ‘remotely controlled’, so to speak. Do I understand correctly? Also, I’m interested in the networking calls, but I’m having difficulty following them. Can you explain how they are sequenced?

Leave a Reply

Your email address will not be published. Required fields are marked *