Looks Like I Require a Magic Wand

I’m in the middle of working on an auction script. I have come across a potential problem but have yet to come up with a solution. Let me lay it all out for you. :)

When a user bids on an item, an entry is added to to bid table (below):

Column Type Null Default Comments
bid_id int(11) No
auction_id int(11) No
item_id int(11) No
bid_amount decimal(10,0) No
bid_date int(11) No
user_id int(11) No

There will be some logic in the code that checks that the bid is valid (above the reserve threshold, correct increment, etc.). That part is fine.

What I’m worried about is if multiple bidders (or even the same bidder) submit bids for the same item at the same time. This could happen if for example, the server lags and all of them are processed at the exact same time. If there were a column I could assign the UNIQUE attribute to this would be a no-brainer. I don’t see a way to do that, though.

If the above scenario takes place, duplicate bids and/or an incorrect count on items remaining if it is a buy it now/quantity type item would suddenly plague my wonderful script. It would be quite problematic if there are only 5 items and 7 people end up getting a buy it now bid submitted. How would one decide who wins when the timestamp for all the bids ends up being the same? The better question is, how does one prevent the “bad” entries in the first place?

I get the feeling that this is where triggers and stored procedures come into play. Of course that just now occurred to me after bothering with writing this post. Still, any advice (and example code) is appreciated. Looks like I have a lot of documentation to read…

DJ Management Script

I present to you the script I wrote to take care of Live DJs in Sam. There are a number of different ways this could be done. If you wish to do it differently or port it to a language other than PHP, go for it (just be sure to share).

Before switching from Auto DJ to the specified Live DJ the script checks that the Live DJ is actually on the air. If the Live DJ is on the air, the Auto DJ fades to the Live DJ. If the Live DJ is not on the air when he is supposed to be, nothing happens. If the Live DJ drops the stream, the scripts switches back to the Auto DJ and rechecks every 2 seconds to see if the Live DJ has returned. If the Live DJ returns, we switch back to him.

Known issues:
* If schedule.php is inaccessible or doesn’t return the expected number of lines, Sam will crash.
* If current.txt or past.txt are inaccessible or don’t return the expected number of lines, Sam will crash.

dj.pal:

{DJ Management Pal by Nathan Skelton
Updates available at http://hostify.net/blog}
PAL.Loop := True;
 
PAL.LockExecution;
{Set up our Variables}
Var Url : String = 'null';
Var Port : String = 'null';
Var DJ : String = 'null';
Var Main_status : String = 'null';
Var Main_artist : String = 'null';
Var Main_song : String = 'null';
Var DJ_status : String = 'null';
Var DJ_artist : String = 'null';
Var DJ_song : String = 'null';
Var Main_song_full : String = 'null';
Var DJ_song_full : String = 'null';
Var Past_URL : String = 'null';
Var Scheduled : TStringList; Scheduled := TStringList.Create;
Var Past : TStringList; Past := TStringList.Create;
Var rSong : TSongInfo; rSong := ActivePlayer.GetSongInfo;
 
{this is the working directory for the script
current.txt and past.txt must exist in this directory and be writable by Sam}
Var Dir : String = 'C:\Users\Administrator\Desktop\DJ\';
 
{grab the now playing and dj info from the server}
WebToFile(Dir + 'current.txt','http://localhost/DJ/schedule.php');
 
{if we grabbed the file successfully}
if FileExists(Dir + 'current.txt') then
begin
  Scheduled.LoadFromFile(Dir + 'current.txt');
 
  {load up the results from the last round}
  if FileExists(Dir + 'past.txt') then
  begin
    Past.LoadFromFile(Dir + 'past.txt');
    Past_URL := Past[0] + ':' + Past[1];
  end;
 
  {pull the variables from the file}
  Url := Scheduled[0];
  Port := Scheduled[1];
  DJ := Scheduled[2];
  Main_status := Scheduled[3];
  Main_artist := Scheduled[4];
  Main_song := Scheduled[5];
  Main_song_full := Main_artist + ' - ' + Main_song;
  DJ_status := Scheduled[6];
  DJ_artist := Scheduled[7];
  DJ_song := Scheduled[8] + ' ' + DJ;
  DJ_song_full := DJ_artist + ' - ' + DJ_song;
 
  {rename our current file so it will be fresh on our next loop}
  CopyFile(Dir + 'current.txt', Dir + 'past.txt', false);
end;
 
{If the DJ is null, there is no DJ scheduled for right now}
if (DJ <> 'null') then
begin
  WriteLn('The Current DJ is ' + DJ + ' On ' + Url + ':' + Port);
 
  {if the DJ is not currently loaded in the playing deck...}
  if (rSong['title'] <> Url + ':' + Port) then
  begin
    {if the DJ's server status is good, they should be put live...else, we do nothing}
    if (DJ_status='1') then
    begin
      Queue.AddURL(URL + ':' + Port,ipTop);
      ActivePlayer.FadeToNext;
      WriteLn('Switching to Live DJ');
 
      {var Song : TSongInfo;
      Song := TSongInfo.Create;
      Song['artist'] := DJ_song;
      Song['title'] := '';
      Encoders.SongChange(Song);
      Song.Free;
      WriteLn('Song Updated to ' + DJ_song);}
    end;
    if (DJ_status<>'1') then
    begin
      WriteLn('Live DJ not active');
    end;
  end;
 
  {if the DJ is currently loaded in the playing deck...}
  if (rSong['title'] = Url + ':' + Port) then
  begin
    {if the DJ is live}
    if (DJ_status='1') then
    begin
      {if the song on the streaming server doesn't match what is on the DJ server}
      if (Main_song_full <> DJ_song_full) then
      begin
        {we're assuming that the server doesn't care about a seperate artist and title}
        var Song : TSongInfo;
        Song := TSongInfo.Create;
        Song['artist'] := DJ_artist;
        Song['title'] := DJ_song;
        Encoders.SongChange(Song);
        Song.Free;
        WriteLn('Song Updated to ' + DJ_song_full);
      end;
    end;
 
    {if the DJ is currently loaded in the deck, but the DJ server is inactive}
    if (DJ_status<>'1') then
    begin
      ActivePlayer.FadeToNext;
      WriteLn('Live DJ not present. Switching to Auto DJ');
    end;
  end;
end;
 
{if there is no DJ scheduled}
if (DJ = 'null') then
begin
  {if the song title is still set to the past DJ, we need to fade to next}
  if (rSong['title'] = Past_URL) then
  begin
    ActivePlayer.FadeToNext;
    WriteLn('DJ no longer present. Switching to AutoDJ');
  end;
end;
 
rSong.Free;
Past.Free;
Scheduled.Free;
PAL.UnlockExecution;
PAL.WaitForTime('+00:00:02');

schedule.php:

/*
DJ Management Pal by Nathan Skelton
Updates available at http://hostify.net/blog
*/
$serv["name"][] = "AudioProbe.net - 192KB/s";     # short nickname of server.
$serv["host"][] = "listen.audioprobe.net";               # host address  # port IP address
$serv["port"][] = 80;                     # port number
$serv["passwd"][] = "pass";                # admin password

/** 
$time is in 24-hour/military format with leading zeros
 
$days are as follows:
	sunday=0
	monday=1
	tuesday=2
	wednesday=3
	thursday=4
	friday=5
	saturday=6
*/
$time=date("H:i", time());
$day=date("w", time());
 
//an example show
//i've given the DJ five minutes of padding on each end
//if you have back-to-back shows, you may not want to do this, however...it may work out okay since in theory there would be a seamless switch between the DJs
//if you wanted to get really creative, you'd put all of this in a database...
//I'm not feeling that creative at this point considering I only have one live show
 
if($day==0 && ($time>="13:55" && $time<="16:05"))
{
	$server='http://localhost';//the server the dj will be connecting to
	$port=8000;//the port of the server the dj will be connection to
	$password="pass";//the password to the admin interface of the server
	$dj='[Aural Pleasure]';//the name of the dj/show that will be appended to the title field
}
else
{
	//no djs scheduled
	$server='null';
	$port='null';
	$password='null';
	$dj='null';
}
 
//if we have a dj scheduled, let's generate some output!
if($dj!='null')
{
	//we will pull the stats from this server
	$count = 1;
 
	//begin pulling stats
	$mysession = curl_init();
	curl_setopt($mysession, CURLOPT_URL, "http://".$serv["host"][$count].":".$serv["port"][$count]."/admin.cgi?mode=viewxml");
	curl_setopt($mysession, CURLOPT_HEADER, false);
	curl_setopt($mysession, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($mysession, CURLOPT_POST, false);
	curl_setopt($mysession, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	curl_setopt($mysession, CURLOPT_USERPWD, "admin:".$serv["passwd"][$count]);
	curl_setopt($mysession, CURLOPT_FOLLOWLOCATION, true);
	curl_setopt($mysession, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
	curl_setopt($mysession, CURLOPT_CONNECTTIMEOUT, 2);
	$xml = curl_exec($mysession);
 
	//the stats from our main streaming server
	$result=xml2array(utf8_decode($xml));
	if(@is_array($result['SHOUTCASTSERVER']))
	{
		$song=split(' - ',$result['SHOUTCASTSERVER']['SONGHISTORY']['SONG'][0]['TITLE']);
		$streamstatus_1=$result['SHOUTCASTSERVER']['STREAMSTATUS'];
	}
	else
	{
		$song[0]='null';
		$song[1]='null';
		$streamstatus_1='null';
	}
 
	//the stats for our dj's server
	curl_setopt($mysession, CURLOPT_URL, $server.":".$port."/admin.cgi?mode=viewxml");
	curl_setopt($mysession, CURLOPT_USERPWD, "admin:".$password);
	$xml2 = curl_exec($mysession);
 
	curl_close($mysession);
 
 
	$result2=xml2array(utf8_decode($xml2));
	if(@is_array($result2['SHOUTCASTSERVER']))
	{
		$oldsong=split(' - ',$result2['SHOUTCASTSERVER']['SONGHISTORY']['SONG'][0]['TITLE']);
		$streamstatus_2=$result2['SHOUTCASTSERVER']['STREAMSTATUS'];
	}
	else
	{
		$oldsong[0]='null';
		$oldsong[1]='null';
		$streamstatus_2='null';
	}
}
else
{
	$song[0]='null';
	$song[1]='null';
	$oldsong[0]='null';
	$oldsong[1]='null';
	$streamstatus_1='null';
	$streamstatus_2='null';
}
 
if(!$song[0])
{
	$song[0]='null';
}
if(!$song[1])
{
	$song[1]='null';
}
if(!$oldsong[0])
{
	$oldsong[0]='null';
}
if(!$oldsong[1])
{
	$oldsong[1]='null';
}
if(!$streamstatus_1)
{
	$streamstatus_1='null';
}
if(!$streamstatus_2)
{
	$streamstatus_2='null';
}
 
echo $server."\n".$port."\n".$dj."\n".$streamstatus_1."\n".$song[0]."\n".$song[1]."\n".$streamstatus_2."\n".$oldsong[0]."\n".$oldsong[1];
 
/** 
 * xml2array() will convert the given XML text to an array in the XML structure. 
 * Link: http://www.bin-co.com/php/scripts/xml2array/ 
 * Arguments : $contents - The XML text 
 *                $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value.
 *                $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure. 
 * Examples: $array =  xml2array(file_get_contents('feed.xml')); 
 *              $array =  xml2array(file_get_contents('feed.xml', 1, 'attribute')); 
 */ 
function xml2array($contents, $get_attributes=1, $priority = 'tag') { 
    if(!$contents) return array(); 
 
    if(!function_exists('xml_parser_create')) { 
        //print "'xml_parser_create()' function not found!"; 
        return array(); 
    } 
 
    //Get the XML parser of PHP - PHP must have this module for the parser to work 
    $parser = xml_parser_create(''); 
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss 
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); 
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); 
    xml_parse_into_struct($parser, trim($contents), $xml_values); 
    xml_parser_free($parser); 
 
    if(!$xml_values) return;//Hmm... 
 
    //Initializations 
    $xml_array = array(); 
    $parents = array(); 
    $opened_tags = array(); 
    $arr = array(); 
 
    $current = &$xml_array; //Refference 
 
    //Go through the tags. 
    $repeated_tag_index = array();//Multiple tags with same name will be turned into an array 
    foreach($xml_values as $data) { 
        unset($attributes,$value);//Remove existing values, or there will be trouble 
 
        //This command will extract these variables into the foreach scope 
        // tag(string), type(string), level(int), attributes(array). 
        extract($data);//We could use the array by itself, but this cooler. 
 
        $result = array(); 
        $attributes_data = array(); 
 
        if(isset($value)) { 
            if($priority == 'tag') $result = $value; 
            else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode 
        } 
 
        //Set the attributes too. 
        if(isset($attributes) and $get_attributes) { 
            foreach($attributes as $attr => $val) { 
                if($priority == 'tag') $attributes_data[$attr] = $val; 
                else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr' 
            } 
        } 
 
        //See tag status and do the needed. 
        if($type == "open") {//The starting of the tag '<tag>' 
            $parent[$level-1] = &$current; 
            if(!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag 
 
 
                $current[$tag] = $result; 
                if($attributes_data) $current[$tag. '_attr'] = $attributes_data; 
                $repeated_tag_index[$tag.'_'.$level] = 1; 
 
                $current = &$current[$tag]; 
 
            } else { //There was another element with the same tag name 
 
                if(isset($current[$tag][0])) {//If there is a 0th element it is already an array 
                    $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result; 
                    $repeated_tag_index[$tag.'_'.$level]++; 
                } else {//This section will make the value an array if multiple tags with the same name appear together
                    $current[$tag] = array($current[$tag],$result);//This will combine the existing item and the new item together to make an array
                    $repeated_tag_index[$tag.'_'.$level] = 2; 
 
                    if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well 
                        $current[$tag]['0_attr'] = $current[$tag.'_attr']; 
                        unset($current[$tag.'_attr']); 
                    } 
 
                } 
                $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1; 
                $current = &$current[$tag][$last_item_index]; 
            } 
 
        } elseif($type == "complete") { //Tags that ends in 1 line '<tag />' 
            //See if the key is already taken. 
            if(!isset($current[$tag])) { //New Key 
                $current[$tag] = $result; 
                $repeated_tag_index[$tag.'_'.$level] = 1; 
                if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data; 
 
            } else { //If taken, put all things inside a list(array) 
                if(isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array... 
 
                    // ...push the new element into that array. 
                    $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result; 
 
                    if($priority == 'tag' and $get_attributes and $attributes_data) { 
                        $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data; 
                    } 
                    $repeated_tag_index[$tag.'_'.$level]++; 
 
                } else { //If it is not an array... 
                    $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
                    $repeated_tag_index[$tag.'_'.$level] = 1; 
                    if($priority == 'tag' and $get_attributes) { 
                        if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
 
                            $current[$tag]['0_attr'] = $current[$tag.'_attr']; 
                            unset($current[$tag.'_attr']); 
                        } 
 
                        if($attributes_data) { 
                            $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data; 
                        } 
                    } 
                    $repeated_tag_index[$tag.'_'.$level]++; //0 and 1 index is already taken 
                } 
            } 
 
        } elseif($type == 'close') { //End of tag '</tag>' 
            $current = &$parent[$level-1]; 
        } 
    } 
 
    return($xml_array); 
}

current.txt, past.txt:

http://localhost
8000
[Aural Pleasure]
1
The Crystal Method
Slipstream (feat. Jason Lytle) [Aural Pleasure]
1
The Crystal Method
Slipstream (feat. Jason Lytle)

Automatically kick and ban “bad” listeners from your Shoutcast server

I decided a few minutes ago that I’d like to make AudioProbe a bit less appetizing to stream rippers. Here’s the result:

First, create shoutcast-config.php
This file holds all of the configuration details for your shoutcast servers. I keep this in a separate file since I include this in other applications on the site. You can add as many servers as you want.

<?php
//server config...you can add as many servers as you want in following format...just simply copy and paste this code block to add a new server (update the info of course)
$serv["host"][] = "listen.audioprobe.net"; # host address  # port IP address
$serv["port"][] = 80; # port number
$serv["passwd"][] = "pass"; # admin password
?>

Create ban.php:

<?php
//import our list of server(s)
require_once('shoutcast-config.php');
 
//our banned useragents...feel free to add as many as you'd like
$banneduas=array("WinampMPEG/5.0", "WinampMPEG/5.50");
 
//if you would like to ban the IP in addition to kicking it, set this to TRUE
$ban=FALSE;
 
/***************************************************/
//Do NOT touch below this line
 
    /** 
     * xml2array() will convert the given XML text to an array in the XML structure. 
     * Link: http://www.bin-co.com/php/scripts/xml2array/ 
     * Arguments : $contents - The XML text 
     *                $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value.
     *                $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
     * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure. 
     * Examples: $array =  xml2array(file_get_contents('feed.xml')); 
     *              $array =  xml2array(file_get_contents('feed.xml', 1, 'attribute')); 
     */ 
    function xml2array($contents, $get_attributes=1, $priority = 'tag') { 
        if(!$contents) return array(); 
 
        if(!function_exists('xml_parser_create')) { 
            //print "'xml_parser_create()' function not found!"; 
            return array(); 
        } 
 
        //Get the XML parser of PHP - PHP must have this module for the parser to work 
        $parser = xml_parser_create(''); 
        xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss 
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); 
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); 
        xml_parse_into_struct($parser, trim($contents), $xml_values); 
        xml_parser_free($parser); 
 
        if(!$xml_values) return;//Hmm... 
 
        //Initializations 
        $xml_array = array(); 
        $parents = array(); 
        $opened_tags = array(); 
        $arr = array(); 
 
        $current = &$xml_array; //Refference 
 
        //Go through the tags. 
        $repeated_tag_index = array();//Multiple tags with same name will be turned into an array 
        foreach($xml_values as $data) { 
            unset($attributes,$value);//Remove existing values, or there will be trouble 
 
            //This command will extract these variables into the foreach scope 
            // tag(string), type(string), level(int), attributes(array). 
            extract($data);//We could use the array by itself, but this cooler. 
 
            $result = array(); 
            $attributes_data = array(); 
 
            if(isset($value)) { 
                if($priority == 'tag') $result = $value; 
                else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode 
            } 
 
            //Set the attributes too. 
            if(isset($attributes) and $get_attributes) { 
                foreach($attributes as $attr => $val) { 
                    if($priority == 'tag') $attributes_data[$attr] = $val; 
                    else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr' 
                } 
            } 
 
            //See tag status and do the needed. 
            if($type == "open") {//The starting of the tag '<tag>' 
                $parent[$level-1] = &$current; 
                if(!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag 
 
 
 
                    $current[$tag] = $result; 
                    if($attributes_data) $current[$tag. '_attr'] = $attributes_data; 
                    $repeated_tag_index[$tag.'_'.$level] = 1; 
 
                    $current = &$current[$tag]; 
 
                } else { //There was another element with the same tag name 
 
                    if(isset($current[$tag][0])) {//If there is a 0th element it is already an array 
                        $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result; 
                        $repeated_tag_index[$tag.'_'.$level]++; 
                    } else {//This section will make the value an array if multiple tags with the same name appear together
                        $current[$tag] = array($current[$tag],$result);//This will combine the existing item and the new item together to make an array
                        $repeated_tag_index[$tag.'_'.$level] = 2; 
 
                        if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well 
                            $current[$tag]['0_attr'] = $current[$tag.'_attr']; 
                            unset($current[$tag.'_attr']); 
                        } 
 
                    } 
                    $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1; 
                    $current = &$current[$tag][$last_item_index]; 
                } 
 
            } elseif($type == "complete") { //Tags that ends in 1 line '<tag />' 
                //See if the key is already taken. 
                if(!isset($current[$tag])) { //New Key 
                    $current[$tag] = $result; 
                    $repeated_tag_index[$tag.'_'.$level] = 1; 
                    if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data; 
 
                } else { //If taken, put all things inside a list(array) 
                    if(isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array... 
 
                        // ...push the new element into that array. 
                        $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result; 
 
                        if($priority == 'tag' and $get_attributes and $attributes_data) { 
                            $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data; 
                        } 
                        $repeated_tag_index[$tag.'_'.$level]++; 
 
                    } else { //If it is not an array... 
                        $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
                        $repeated_tag_index[$tag.'_'.$level] = 1; 
                        if($priority == 'tag' and $get_attributes) { 
                            if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
 
                                $current[$tag]['0_attr'] = $current[$tag.'_attr']; 
                                unset($current[$tag.'_attr']); 
                            } 
 
                            if($attributes_data) { 
                                $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data; 
                            } 
                        } 
                        $repeated_tag_index[$tag.'_'.$level]++; //0 and 1 index is already taken 
                    } 
                } 
 
            } elseif($type == 'close') { //End of tag '</tag>' 
                $current = &$parent[$level-1]; 
            } 
        } 
 
        return($xml_array); 
    }  
 
//retrieve xml stats from each server
for ($count = 0; $count < count($serv["host"]); $count++) {
    $mysession = curl_init();
    curl_setopt($mysession, CURLOPT_URL, "http://".$serv["host"][$count].":".$serv["port"][$count]."/admin.cgi?mode=viewxml");
    curl_setopt($mysession, CURLOPT_HEADER, false);
    curl_setopt($mysession, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($mysession, CURLOPT_POST, false);
    curl_setopt($mysession, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($mysession, CURLOPT_USERPWD, "admin:".$serv["passwd"][$count]);
    curl_setopt($mysession, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($mysession, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
    curl_setopt($mysession, CURLOPT_CONNECTTIMEOUT, 2);
    $xml = curl_exec($mysession);
 
    unset($result);
    $result=xml2array(utf8_decode($xml));
    if(is_array($result[SHOUTCASTSERVER][LISTENERS][LISTENER])) {
        foreach($result[SHOUTCASTSERVER][LISTENERS][LISTENER] as $l) {
            if(in_array($l[USERAGENT], $banneduas, FALSE)) {
                if($ban) {
                    //must ban first since user will stay connected unless he is susequently kicked
                    curl_setopt($mysession, CURLOPT_URL, "http://".$serv["host"][$count].":".$serv["port"][$count]."/admin.cgi?mode=bandst&bandst=".$l[POINTER]."&banmsk=255");
                    curl_exec($mysession);
                }
                //kick the user
                curl_setopt($mysession, CURLOPT_URL, "http://".$serv["host"][$count].":".$serv["port"][$count]."/admin.cgi?mode=kickdst&kickdst=".$l[POINTER]);
                curl_exec($mysession);
            }
        }
    }
    curl_close($mysession);
}
?>

You can set this to run periodically by using a Cron job. Your host should be able to assist you with setting it up. For example, on a cPanel server, the command would be this:

/usr/bin/curl -s http://YOURDOMAIN/ban.php >/dev/null 2>&1

Enjoy and please let me know if you find it useful! :)

Displaying Shoutcast Now Playing Information on Your Web Site

Want to pull listener stats and now playing and recently played from your shoutcast server(s)? This seems to be a common question, so here’s a small tutorial on how to accomplish this. This code is based on what I’ve done over at AudioProbe, so I’ve left in a lot of stuff as an example. If you have any questions, please do ask. :P

First, create shoutcast-config.php
This file holds all of the configuration details for your shoutcast servers. I keep this in a separate file since I include this in other applications on the site. You can add as many servers as you want, but it makes sense to ensure they are all playing the same program.

<?php
//server config...you can add as many servers as you want in following format...just simply copy and paste this code block to add a new server (update the info of course)
$serv["host"][] = "listen.audioprobe.net"; # host address  # port IP address
$serv["port"][] = 80; # port number
$serv["passwd"][] = "pass"; # admin password
?>

Next, create yql.php
This file is what takes care of retrieving the statistics from each server. The statistics are returned to pollstation.js (below) and placed on the page. The only part of this you will need to modify is at the bottom.

<?php
require_once('shoutcast-config.php');
for ($count = 0; $count < count($serv["host"]); $count++) {
    $mysession = curl_init();
    curl_setopt($mysession, CURLOPT_URL, "http://".$serv["host"][$count].":".$serv["port"][$count]."/admin.cgi?mode=viewxml");
    curl_setopt($mysession, CURLOPT_HEADER, false);
    curl_setopt($mysession, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($mysession, CURLOPT_POST, false);
    curl_setopt($mysession, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($mysession, CURLOPT_USERPWD, "admin:".$serv["passwd"][$count]);
    curl_setopt($mysession, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
    curl_setopt($mysession, CURLOPT_CONNECTTIMEOUT, 2);
    $xml = curl_exec($mysession);
    curl_close($mysession);
 
    $result[]=xml2array($xml);
}
 
/** 
 * xml2array() will convert the given XML text to an array in the XML structure. 
 * Link: http://www.bin-co.com/php/scripts/xml2array/ 
 * Arguments : $contents - The XML text 
 *                $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value.
 *                $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure. 
 * Examples: $array =  xml2array(file_get_contents('feed.xml')); 
 *              $array =  xml2array(file_get_contents('feed.xml', 1, 'attribute')); 
 */ 
function xml2array($contents, $get_attributes=1, $priority = 'tag') { 
    if(!$contents) return array(); 
 
    if(!function_exists('xml_parser_create')) { 
        //print "'xml_parser_create()' function not found!"; 
        return array(); 
    } 
 
    //Get the XML parser of PHP - PHP must have this module for the parser to work 
    $parser = xml_parser_create(''); 
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss 
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); 
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); 
    xml_parse_into_struct($parser, trim($contents), $xml_values); 
    xml_parser_free($parser); 
 
    if(!$xml_values) return;//Hmm... 
 
    //Initializations 
    $xml_array = array(); 
    $parents = array(); 
    $opened_tags = array(); 
    $arr = array(); 
 
    $current = &$xml_array; //Refference 
 
    //Go through the tags. 
    $repeated_tag_index = array();//Multiple tags with same name will be turned into an array 
    foreach($xml_values as $data) { 
        unset($attributes,$value);//Remove existing values, or there will be trouble 
 
        //This command will extract these variables into the foreach scope 
        // tag(string), type(string), level(int), attributes(array). 
        extract($data);//We could use the array by itself, but this cooler. 
 
        $result = array(); 
        $attributes_data = array(); 
 
        if(isset($value)) { 
            if($priority == 'tag') $result = $value; 
            else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode 
        } 
 
        //Set the attributes too. 
        if(isset($attributes) and $get_attributes) { 
            foreach($attributes as $attr => $val) { 
                if($priority == 'tag') $attributes_data[$attr] = $val; 
                else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr' 
            } 
        } 
 
        //See tag status and do the needed. 
        if($type == "open") {//The starting of the tag '<tag>' 
            $parent[$level-1] = &$current; 
            if(!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag 
 
 
                $current[$tag] = $result; 
                if($attributes_data) $current[$tag. '_attr'] = $attributes_data; 
                $repeated_tag_index[$tag.'_'.$level] = 1; 
 
                $current = &$current[$tag]; 
 
            } else { //There was another element with the same tag name 
 
                if(isset($current[$tag][0])) {//If there is a 0th element it is already an array 
                    $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result; 
                    $repeated_tag_index[$tag.'_'.$level]++; 
                } else {//This section will make the value an array if multiple tags with the same name appear together
                    $current[$tag] = array($current[$tag],$result);//This will combine the existing item and the new item together to make an array
                    $repeated_tag_index[$tag.'_'.$level] = 2; 
 
                    if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well 
                        $current[$tag]['0_attr'] = $current[$tag.'_attr']; 
                        unset($current[$tag.'_attr']); 
                    } 
 
                } 
                $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1; 
                $current = &$current[$tag][$last_item_index]; 
            } 
 
        } elseif($type == "complete") { //Tags that ends in 1 line '<tag />' 
            //See if the key is already taken. 
            if(!isset($current[$tag])) { //New Key 
                $current[$tag] = $result; 
                $repeated_tag_index[$tag.'_'.$level] = 1; 
                if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data; 
 
            } else { //If taken, put all things inside a list(array) 
                if(isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array... 
 
                    // ...push the new element into that array. 
                    $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result; 
 
                    if($priority == 'tag' and $get_attributes and $attributes_data) { 
                        $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data; 
                    } 
                    $repeated_tag_index[$tag.'_'.$level]++; 
 
                } else { //If it is not an array... 
                    $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
                    $repeated_tag_index[$tag.'_'.$level] = 1; 
                    if($priority == 'tag' and $get_attributes) { 
                        if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
 
                            $current[$tag]['0_attr'] = $current[$tag.'_attr']; 
                            unset($current[$tag.'_attr']); 
                        } 
 
                        if($attributes_data) { 
                            $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data; 
                        } 
                    } 
                    $repeated_tag_index[$tag.'_'.$level]++; //0 and 1 index is already taken 
                } 
            } 
 
        } elseif($type == 'close') { //End of tag '</tag>' 
            $current = &$parent[$level-1]; 
        } 
    } 
 
    return($xml_array); 
}  
    foreach($result as $r) {
        $listeners+=$r[SHOUTCASTSERVER][CURRENTLISTENERS];
    }
 
    $i=0;
    while($i!=10) {
        $songs.="<br/>".trim($r[SHOUTCASTSERVER][SONGHISTORY][SONG][$i][TITLE]);
        $i++;
    }
 
    $listenerstext="<a href="http://loudcity.com/stations/audioprobe-net/files/show/tunein.html" style="color: #ffffff" target="_blank">Join our other listeners now!</a> Listen live by clicking the above link.$listenerstext";
 
    if($listeners > 0) {
        $listenerstext.=" There are currently <a href="http://audioprobe.net/status.php" style="color: #ffffff;text-decoration:none;">$listeners</a> listeners tuned in.";
    }    
 
    $result = $listenerstext.$songs;
 
    echo htmlspecialchars($_GET[callback]).'([{"results": "'.addslashes(trim($result)).'"}])';
?>

pollstation.js
This is what handles placing the information on the page. I’ve left in my custom stuff at the bottom. You’ll most certainly want to customize it. Based on some feedback, I have provided a basic version as well as a version with some customization that is used on AudioProbe. The customization consists of linking to info pages for the songs, album art, etc. Note that this is for advanced users only since you will need to build the pages to serve the required stuff.

Change the “var yql” line to match the URL of your yql.php file. For example, if my domain were “domain.com” and I have placed yql.php in the root directory this would be the result: var yql = ‘http://domain.com/yql.php?callback=?’;

jQuery(document).ready(function() {
    pollstation();
    //refresh the data every 30 seconds
    setInterval(pollstation, 30000);
});
 
// Accepts a url and a callback function to run.  
function requestCrossDomain( callback ) {  
    // Take the provided url, and add it to a YQL query. Make sure you encode it!  
    var yql = 'http://audioprobe.net/yql.php?callback=?';
    // Request that YSQL string, and run a callback function.  
    // Pass a defined function to prevent cache-busting.  
    jQuery.getJSON( yql, cbFunc );
 
    function cbFunc(data) {  
    // If we have something to work with...  
    if ( data ) {  
        // Strip out all script tags, for security reasons. there shouldn't be any, however
        data = data[0].results.replace(/<script[^>]*>[sS]*?</script>/gi, '');
        data = data.replace(/<html[^>]*>/gi, '');
        data = data.replace(/</html>/gi, '');
        data = data.replace(/<body[^>]*>/gi, '');
        data = data.replace(/</body>/gi, '');
 
        // If the user passed a callback, and it  
        // is a function, call it, and send through the data var.  
        if ( typeof callback === 'function') {  
            callback(data);  
        }  
    }  
    // Else, Maybe we requested a site that doesn't exist, and nothing returned.  
    else throw new Error('Nothing returned from getJSON.');  
    }  
}  
 
function pollstation() {
    requestCrossDomain(function(stationdata) {
        //make our data into an array
        var lines = stationdata.split('<br/>');
 
        //update number of listeners
        jQuery('#listeners').html(lines[0]);
 
        //transform the song title into [artist] - [title] ([year])
        s_info=lines[1].split(" - ");
 
        //remove the artist from the title
        title=jQuery.trim(s_info[1]);
 
        //remove the year from the title
        cleantitle=jQuery.trim(s_info[1].replace(/ (d{4})/,''));
 
        //keep just the year
        new_year=title.replace(cleantitle, '');
 
        //get rid of parenthesis around the year
        new_year=new_year.replace(/ (/,'');
        new_year=new_year.replace(/)/,'');
 
 
        //update the current artist and song title
        jQuery('#currentsong').html(jQuery.trim(cleantitle) + '<br /><em>' + jQuery.trim(s_info[0]) + '</em><<br />' + jQuery.trim(new_year));
 
        //update the previously played songs
        for (var i = 1; i <= 10; i++) {            
            jQuery('#prevsong' + i).html(lines[i + 1]);
        }
    } );
}

//customized for album art and linking
jQuery(document).ready(function() {
    pollstation();
    //refresh the data every 30 seconds
    setInterval(pollstation, 30000);
});
 
// Accepts a url and a callback function to run.  
function requestCrossDomain( callback ) {  
    // Take the provided url, and add it to a YQL query. Make sure you encode it!  
    var yql = 'http://audioprobe.net/yql.php?callback=?';
    // Request that YSQL string, and run a callback function.  
    // Pass a defined function to prevent cache-busting.  
    jQuery.getJSON( yql, cbFunc );
 
    function cbFunc(data) {  
    // If we have something to work with...  
    if ( data ) {  
        // Strip out all script tags, for security reasons. there shouldn't be any, however
        data = data[0].results.replace(/<script[^>]*>[sS]*?</script>/gi, '');
        data = data.replace(/<html[^>]*>/gi, '');
        data = data.replace(/</html>/gi, '');
        data = data.replace(/<body[^>]*>/gi, '');
        data = data.replace(/</body>/gi, '');
 
        // If the user passed a callback, and it  
        // is a function, call it, and send through the data var.  
        if ( typeof callback === 'function') {  
            callback(data);  
        }  
    }  
    // Else, Maybe we requested a site that doesn't exist, and nothing returned.  
    else throw new Error('Nothing returned from getJSON.');  
    }  
}  
 
function pollstation() {
    requestCrossDomain(function(stationdata) {
        //make our data into an array
        var lines = stationdata.split('<br/>');
 
        //update number of listeners
        jQuery('#listeners').html(lines[0]);
 
        //update the album art
        jQuery('#songsearch').html('<img src="http://audioprobe.net/art.php?query=' + encodeURIComponent(jQuery.trim(lines[1])) + '" />');            
 
        //transform the song title into [artist] - [title] ([year])
        s_info=lines[1].split(" - ");
 
        //remove the artist from the title
        title=jQuery.trim(s_info[1]);
 
        //remove the year from the title
        cleantitle=jQuery.trim(s_info[1].replace(/ (d{4})/,''));
 
        //keep just the year
        new_year=title.replace(cleantitle, '');
 
        //get rid of parenthesis around the year
        new_year=new_year.replace(/ (/,'');
        new_year=new_year.replace(/)/,'');
 
        //if a special show, let's identify it and properly format it
        var index = cleantitle.indexOf("[Aural Pleasure]");
        if(index != -1) {
            //remove the show title from the title of the song
            cleantitle=cleantitle.replace(/ [Aural Pleasure]/,'');
 
            //replace the year with the song
            new_year='Aural Pleasure';
 
            //update the album art for the show
            jQuery('#songsearch').html('<img src="http://audioprobe.net/auralpleasure.jpg" alt="Aural Pleasure" />');
        }
 
        //update the current artist and song title
        jQuery('#currentsong').html('<a href="http://audioprobe.net/redirect.php?song=' + encodeURIComponent(jQuery.trim(lines[1])) + '" title="view song information"  style="text-decoration:none;" target="_blank"><span style="font-weight:bold;color:#993333;font-size: 14px;">' + jQuery.trim(cleantitle) + '</span><br /><span style="font-weight:bold;color:#333333;font-size: 12px;"><em>' + jQuery.trim(s_info[0]) + '</em></span><br /><div style="font-weight:bold;font-size: 14px;">' + jQuery.trim(new_year) + '</div></a>');
 
        //update the previously played songs
        for (var i = 1; i <= 10; i++) {            
            jQuery('#prevsong' + i).html('<a href="http://audioprobe.net/redirect.php?song=' + encodeURIComponent(jQuery.trim(lines[i+1])) + '" title="view song information"  style="text-decoration:none;font-weight:normal" target="_blank">' + lines[i + 1] + '</a>');
        }
    } );
}

Obtain jQuery and place it somewhere on your server or use a preferred CDN service.

index.html
This is an example of how the code could be displayed on your page.

<html>
<head>
<script src="/jquery.min.js" type="text/javascript"></script>
<script src="/pollstation.js" type="text/javascript"></script>
</head>
<body>
Currently Playing:
<div id="currentsong"></div>
<br /><br />
Listeners:
<span id="listeners"></span>
<br /><br />
Recently Played:
    <table>
    <tr><th>Recently Played Songs</th></tr>
    <tr><td><span id="prevsong1"></span></td></tr>
    <tr><td><span id="prevsong2"></span></td></tr>
    <tr><td><span id="prevsong3"></span></td></tr>
    <tr><td><span id="prevsong4"></span></td></tr>
    <tr><td><span id="prevsong5"></span></td></tr>
    <tr><td><span id="prevsong6"></span></td></tr>
    <tr><td><span id="prevsong7"></span></td></tr>
    <tr><td><span id="prevsong8"></span></td></tr>
    <tr><td><span id="prevsong9"></span></td></tr>
    <tr><td><span id="prevsong10"></span></td></tr>
    </table>
</body>
</html>

Good luck!

Update (March 13, 2012): I’ve made a few changes based on some feedback I’ve gotten. The sample pollstation.js with all the extra code was confusing so I added a “lite” version. It was also unclear that pollstation.js needed to be modified to reflect the location of yql.php. Also, please note that this script will work with Shoutcast DNAS version 2 with a few modifications. Instructions (untested) can be found in the comments.

Shoutcast Automatic Start Script for CentOS

I found this script and modified it a bit so it starts all three of my Shoutcast servers automatically when/if the server ever restarts. That part works great. However, there’s something I would like to change…I want to be able to manage each server individually. I’m not really sure what to do to accomplish this. At this point it’s not too big of a deal, so I’m not going to worry about it.

I want to be able to do “service shoutcast restart” and somehow be able to choose which one to restart (or restart all of them if no specific server is specified). Restarting them all isn’t acceptable when I’m only making configuration changes to one (kicking all users=bad). There is the method of hunting down the process id and killing it and then typing in the command to start it again, but that’s getting old rather fast.

I’d appreciate any suggestions.

#!/bin/sh
#
# chkconfig: 345 99 01
#
# description: shoutcast server startup script
#
# Init script for SHOUTcast
# by caraoge, modified to work correctly by Thomas R Bailey, modified further for
# use with three servers by Nathan Skelton
#
# Last edited Jan 13 2009
 
# Set config to config file location
# set daemon to sc_serv location
############################################################################
##  CHANGE THESE VALUES to match your setup
## CONFIG is the fully qualified location of your config file
## DAEMON is the fully qualified location of the sc_serv binary
## Note, the script will look for sc_serv and sc_serv.conf in /home/shoutcast
############################################################################
DAEMON="/home/shoutcast/sc_serv"
CONFIG="/home/shoutcast/sc_serv.conf"
CONFIG2="/home/shoutcast/sc_serv2.conf"
CONFIG3="/home/shoutcast/sc_serv3.conf"
 
############# Don't fiddle below this line ##############
# Check for SHOUTcast binary
test -f $DAEMON || exit 0
 
# The init commands
case "$1" in
        start)
                echo "Starting SHOUTcast server..."
                $DAEMON $CONFIG  > /dev/null 2>&1 &
                $DAEMON $CONFIG2  > /dev/null 2>&1 &
                $DAEMON $CONFIG3  > /dev/null 2>&1 &
                ;;
        stop)
                echo "Stopping SHOUTcast server..."
                kill -9 `ps -C sc_serv -o pid --no-headers`
                ;;
        restart)
                echo "Stopping SHOUTcast server..."
                kill -9 `ps -C sc_serv -o pid --no-headers`
                echo "Starting SHOUTcast server..."
                $DAEMON $CONFIG  > /dev/null 2>&1 &
                $DAEMON $CONFIG2  > /dev/null 2>&1 &
                $DAEMON $CONFIG3  > /dev/null 2>&1 &
                ;;
        *)
                echo "usage: /etc/init.d/shoutcast"
                echo "$0 {start | stop | restart}"
                exit 1
                ;;
esac

And for those interested in this, here are the steps to set this up on CentOS (by memory, so please correct me if I’m wrong):

1. Navigate to the init.d directory

cd /etc/init.d

2. Create a new file named shoutcast by opening up the nano text editor

nano shoutcast

3. Paste in above code (right click if you’re using putty) and save by pressing CTRL + X and then Y.

4. Give the new file the correct permissions.

chmod 0755 /etc/init.d/shoutcast

5. Navigate to the rc.d directory

cd /etc/rc.d/rc5.d

6. Create a sym-link to the shoutcast file we created in init.d

ln -s ../init.d/shoutcast S99shoutcast

7. Register the script with the system.

chkconfig --add shoutcast

8. Enable the service to start automatically

chkconfig shoutcast on

9. Ensure that your servers start as planned.

/etc/init.d/shoutcast start

10. You may wish to reboot the system to ensure that they start up properly as well.

Of course you would remove “$DAEMON $CONFIG2 > /dev/null 2>&1 &,” “$DAEMON $CONFIG3 > /dev/null 2>&1 &,” etc, unless you are running more than one server (or add some with higher numbers if you have more servers). Setting $DAEMON and $CONFIG ($CONFIG, $CONFIG2, $CONFIG3 should each be unique) to wherever you placed Shoutcast is also necessary. I’m assuming you have enough Linux knowledge to accomplish this. If not, feel free to ask in the comments and I’ll try to help you the best I can. ;-)

XPS M1530 Audio Popping and Crackling Fix

Popping and crackling of audio on the Dell XPS M1530 has been an ongoing complaint of many users. The solution to this is rather simple, however. The problem seems to occur when the CPU throttles down. If you’re running Vista, you simply go into the advanced power options and set the minimum CPU frequency to 100% as shown in the attached images.

Posted in Uncategorized

Make Your Dell Wireless Card Work in Ubuntu

So I installed Ubuntu 9.04 onto my thumb drive last night. To my displeasure, I discovered that my Dell wireless adapter wasn’t recognized. With a little bit of research, I discovered this solution that worked wonders:

Mark Rijckenberg said on 2009-06-14:

Hi,

Please first connect your network card to the wireless router using an ethernet cable (also known as a LAN cable).

Then please follow this procedure:

Step 1: Open Terminal from “Applications->Accessories->
Terminal”

Step 2: Run the following commands (copy-paste the lines below into a Terminal, press enter after each line)

sudo aptitude update
sudo aptitude dist-upgrade
sudo aptitude install linux-backports-modules-jaunty

Step 3: Run the following command

gksudo gedit /etc/modprobe.d/blacklist.conf

# Add the following line to /etc/modprobe.d/blacklist.conf:

blacklist ssb

Step 4: Run the following command

gksudo gedit /etc/modules

# Add the following 2 lines to the /etc/modules file:

wl
wl0

Step 5: Save changes, reboot pc and retest wireless

http://ubuntuforums.org/showthread.php?t=1209055

Posted in Uncategorized

Unbricking Your Linksys WRT54G Router

The other day I realized that the dd-wrt custom firmware I was running on my Linksys WRT54G version 3 router was out of date and susceptible to a serious security vulnerability (see here: http://milw0rm.com/exploits/9209). So like a good system administrator, I immediately proceeded to upgrade to the latest version.

While this should have been a simple process, the router spit back a “firmware upgrade failed” message. Next thing I know, the web interface is gone and the lights are flashing on the front. One of the good signs was that it still recognized when I plugged something into one of the LAN ports and it was returning TTL=100 when pinged. This was a very good sign since it meant that the router was not completely bricked and was still recoverable. The TTL=100 means that the firmware loader is working, but it is waiting for firmware. Excellent!

So now it was time to attempt to recover it. I went to the Linksys site and downloaded the latest firmware for my router. I then loaded a program called TFTP. You can get a copy of that here. Next I changed my network adapter to assign itself a static IP address of 192.168.1.100 (if you don’t do this, you won’t be able to interact with the router). Open the TFTP program and set “server” to 192.168.1.1, leave password blank, select the Linksys firmware you just downloaded, and leave retries at 3. Now I was ready to feed the router some firmware.

Timing is everything with this. The easiest way I found is to watch the light on my network adapter card. In order to upload the firmware, you must unplug the power from your router (leave the network cable running from your computer to the router plugged in of course). Now, while keeping an eye on the light on your network adapter, plug in the router. As soon as the network adapter’s light comes on, hit the “Upgrade” button in the TFTP program. You should receive a “successfully installed firmware” message. If not, try again. Remember that you must send the router the firmware at a very specific time for it to work.

Now that you have the default Linksys firmware working (and you’ve waited for the power light on the front to stop flashing), you can leave it as is or attempt to upgrade to new firmware. After having the trouble with dd-wrt, I decided that it was time to switch to something different. I chose to switch to Tomato. I am very happy with Tomato! Everything runs faster and better with it. Not to mention it manages connections much more efficiently.

Posted in Uncategorized

RHEL5/CentOS 5 Firewire 1394 Support

Today I plugged in my external hard drive and expected it to “just work” like it had in Ubuntu. Instead of recognizing and mounting the hard drive, the OS automagically ignored it. The first thing that I checked was that I had enabled support for Firewire in the bios. It was enabled just like it should be, so I then checked the hard drive using my laptop. The hard drive worked perfectly on the laptop so I decided that CentOS was the problem.

I’ve found that the documentation for CentOS is VERY lacking. It’s hard to find answers for some of the basic questions new users typically have. That fine and dandy, but it also means that one will have the face some of the more advanced problems all alone. However, after a good bit of searching, I finally found the solution to enabling Firewire in CentOS 5 buried on someone’s blog. I’m going to keep a copy here just in case I need to use it again and in the hope it will make someone’s search much easier. This is a summarized version of Joe’s fix:

Step 1) Comment out the following line in /etc/modprobe.d/blacklist-firewire

blacklist firewire-ohci

Step 2) Create or update the file /etc/hal/fdi/policy/preferences.fdi with this code:

<?xml version="1.0" encoding="UTF-8"?> <!-- -*- SGML -*- -->
<deviceinfo version="0.2">
<device>
 <match key="@info.parent:@info.parent:@info.parent:info.linux.driver" string="firewire_ohci">
   <match key="info.category" string="storage">
     <match key="storage.drive_type" string="disk">
       <merge key="storage.hotpluggable" type="bool">true</merge>
     </match>
   </match>
 </match>
</device>
</deviceinfo>

After doing this, your Firewire device should be recognized and work relatively well. :)