The currency exchange of doom



  • Just recently one of our clients notified us that his site was either pretty unresponsive or it just died with a blank page depending on the page requested. I immediately decided to jump right into the code in question to see what the problem was. In the meantime our network administrator decided to double check that there was no communication problem.

    How surprised he was to discover that there is a continuous stream of connection attempts being made between one of the webservers and a remote banking site.

    By that time I was able to corner the problem to a set of files responsible of displaying proper prices when a new order was placed and the site was just about to redirect the user to the client's credit card operator site.

    The site's whole codebase was created by one of my past co-workers, let's call him Dave to protect the guilty. I've seen him perform all kinds of WTF tricks but the code I found was simply beyond my imagination:

    function getExchangeRate($code)
    {
        global $act_tag, $int, $positions, $is_position,$how_many_retries,$how_many_total_retries;
     
    $datep = date("Y-m-d");
     
    $how_many_retries_to_attempt = 16;
    $how_many_retries          = 0;
    $found_the_file    = 0;
     
    do {
     
        $dateT        = explode("-",$datep);
        $day_of_year   = date("z",mktime (0,0,0,$dateT[1],$dateT[2],$dateT[0]));
        $day_of_year   = floor($day_of_year-(($day_of_year/7)*2)+6);
         
        do {
            $table_no = str_pad($day_of_year,3,"0",STR_PAD_LEFT);
            $year          = substr($dateT[0],2);
            $file           = "http://somenbankingsite.com/exchange/xml/".$table_no."x".$year."x".$dateT[1]."x".$dateT[2].".xml";
            $day_of_year--;
            $how_many_retries++;
        } while (!@fopen($file,'r') && $how_many_retries<$how_many_retries_to_attempt && $table_no!="000"); // if true then repeats
        $how_many_total_retries = $how_many_total_retries+$how_many_retries;
        $how_many_retries=0;
     
            $fp = @fopen($file,'r');
            if ($data=@fread($fp,10000))
            {
                $found_the_file = 1;
                $d["date_of_exchange_rate"] = $datep;
            }
     
        // going back one day from $datep
        $dat       = explode("-",$datep);
        $timestamp = gmmktime(12,00,00,$dat[1],$dat[2],$dat[0])-(24*60*60);
        $today     = getdate($timestamp); 
        $datep     = $today['year']."-".$today['mon']."-".$today['mday'];
     
    }
    while ($found_the_file==0);
     
     
    $d["how_many_connection_attempts"] = $how_many_total_retries;
    $d["data_source"] = $file;
     
       $int = 0; 
       $positions = array(); 
       $is_position = 0;
     
       function tag_start($parser,$attr,$params)
       {
          global $act_tag, $int, $positions, $is_position;
            if ($attr=='POSITION')
                {
                    $is_position = 1;
                }
                $act_tag = $attr; 
       }
     
       function tag_text($parser, $text)
       {
          global $act_tag, $int, $positions, $is_position; 
                if ($is_position==1) 
                {
                    $positions[$int]["$act_tag"] .= trim($text);
                }
       }
     
       function tag_end($parser, $attr)
       {
          global $act_tag, $int, $is_position; 
          if($attr == 'POSITION')
          { $int++;
            $is_position = 0;
          } 
       }
     
     
    # -------- fetching data ---------------
       $parser = xml_parser_create(); 
     
       xml_set_element_handler($parser, 'tag_start', 'tag_end'); 
       xml_set_character_data_handler($parser, 'tag_text'); 
     
       if(!($fp = fopen($file,'r'))) die('Unable to open XML file!!!');  
     
       while($data = fread($fp, 4096)) 
        { 
          if(!xml_parse($parser, $data, feof($fp)))
             { 
                $d["error"]        = "Error parsing xml file";
                $d["error_status"] = 1;
             } 
        } 
       xml_parser_free($parser); 
    # -------------------------------------------
     
       for ($i=0;$i<sizeof($positions);$i++)
        {     
            if ($positions[$i]["CURRENCY_CODE"]==$code) 
                {
                    $d["sell_rate"] = eregi_replace(",",".",$positions[$i]["SELL_RATE"]);
                    $d["buy_rate"]     = eregi_replace(",",".",$positions[$i]["BUY_RATE"]);
                    $d["exchange_ratio"]    = $positions[$i]["EXCHANGE_RATIO"];
                    $d["country"]           = $positions[$i]["COUNTRY_NAME"];
                }
        }
    return $d;
    }

    I'm not really sure I can enumerate all the WTFs found in the above masterpiece. We can start with not providing any cache for the results (currency exchange rates are updated once a day). Then comes the guessing factor (why check how the file names are constructed in the first place when you can just blindly guess and eventually hit using trial-and-error). Then comes an infinite loop containing a limited one (just to be sure). Then comes the variable naming scheme (or lack of such). Then comes the file descriptor leak (depending on the success rate it would consume up to 100 in the inner loop before it decided the data is useless). Then comes the most WTFish way to calculate dates. Then comes the beautiful code quality and layout (no formatting rules at all).

    Just had to share it. 



  • my favorite part is that midway through the code "Dave" manages to use the dot equals(.=) operator....., but apparently he's not aware there's also a magical += op [$how_many_total_retries = $how_many_total_retries+$how_many_retries; ]

     

    Also, i don't see $how_many_total_retries initialized to 0 anywhere. 

     

    I don't get it, is he just choosing to type more for the fun of it?
     


Log in to reply