Subscribe to RSS Feed

Open Source

Far from having a hardcore readership in Russia, I learned the hard way that running a custom WordPress installation invites hackers to manipulate its fallible security measures. It would seem that the variety of users signing-up with a .ru address have figured out how to inject php code into wordpress, and my 2.8.2 version was riddled with custom javascript, php code and lots of messages about those little blue pills that can do so much for your sex life. I have to hand-it to whoever it was, that they took the time at all to suss out the flaws and use wordpress for such a lofty goal. They even managed to get a PHP file uploaded to the application, which is both alarming and annoying.

In the end, I decided that caution was the best policy, and installed a completely fresh installation of WordPress. I’ve now disabled users (not really sure of the point of them anyway), and added HTTP authentication to my /wp-admin directory. Its now been a couple of quiet weeks, so I’m taking this to mean victory for now.

I suppose this is the main issue of using open-source software; if you find an exploit, you can cruise around the web, looking for older, vulnerable installations and attack them. The customised code of many of the websites I’ve seen are probably far more vulnerable, but their uniqueness brings a form of security of its own- its too much work for script kiddies to figure out the dynamics of every site on the web, and after all, who cares if you hack Dan Garland’s blog; better-off chasing after Disney and Microsoft, where all the geek kudos would be.
Clean-up
For anyone out there who has experienced a hacked wordpress installation and wants to clean it up, these are the steps I took:

  • Download the latest version of WordPress.
    You can find the latest verison at http://wordpress.org/latest.tar.gz.
  • Move / back-up your old installation and move it out of where apache is serving it.
    Don’t make the mistake of leaving your hacked wordpress somewhere on-line that these pricks can get at it.
  • Install your new wordpress with a new database
    You could point wordpress at your old installation, but you’re running the risk of leaving some code in a comment or post that will leave your installation vulnerable.
  • Comb through your old database to remove junk entries, spam and anything that has nasty stuff in it.
    Search particularly for long-entries, or any content not authored by yourself.
  • Use mysqldump to retrieve the bits of data you want to keep, and import them in.
    I decided to keep posts, comments, tags and categories. I used:
    mysqldump my_db -u user -p wp_links > links.sql
    mysqldump my_db -u user -p wp_posts > posts.sql
    mysqldump my_db -u user -p wp_comments > comments.sql
    mysqldump my_db -u user -p wp_links > links.sql
    mysqldump my_db -u user -p wp_term_relationships wp_terms_tp_term_taxonomy > tags.sql

    Barring the odd column here and there that may have changed between versions, this worked for me but gave me the chance to vet what content went back into the database.
    mysql my_db -u user -p < links.sql

  • Set a strong admin password
  • Set HTTP authentication on your wp-admin directory.
  • Continue Reading »
    No Comments
    Conic Bellophone in X3D, Part Two

    I reached the second milestone of my project to create a virtual reality model of the Conic Bellophone, an instrument comprised of 144 cone-shaped bells being developed for a PhD project. Moving on from the early prototype, which has six bells, I have managed to complete a version that has 144 bells, creating a ghostly harmonic when played.

    The first challenge was dealing with the size and complexity of the model. I was supplied VRML97 exported from CATIA, describing a much more complicated and detailed model. In this model, the author had gone to the detail of individual screws, brackets, stands and bells, and rather than defining the geometry as primitive shapes, the exporter program naively creates large numbers of IndexedFaceSets; defining each point on a plane individually. Consequently, the supplied VRML97 was about 15MB in size, some 40,000 lines of code. This instantly presented problems with the tools I was using; Netbeans would regularly crash and the load-up time was taking about 4-5 minutes, even on my MacBook. At any rate, to deliver such a file on the web would be useless. So my first task, before I could really begin, was to reduce the filesize of the model. To accomplish this, I had to first depart from the arcane VRML97 format and into X3D, an XML version of VMRL that I could work with.

    I noticed from inspecting the file that the exporter had introduced a large number of seemingly useless group nodes, such as:
    <Group>
    <Group>
    <Group>
    <Group USE=”somegroup”>

    </Group>
    </Group>
    </Group>
    </Group>
    I decided to remove them with a simple parser written in Java. I created an application that read in the XML file, performed a recursive operation to remove the nodes and write out the result.
    private void deleteUseless(Node n)
    {
         Node parent = n.getParentNode();

         NodeList children = n.getChildNodes();
         for(int p = 0; p < children.getLength(); p++)
         {
           Node child = children.item(p);

           if(!child.getNodeName().equals(“#text”))
           {
             deleteUseless(child);
           }
         }

         if(n.getNodeName().equals(“Group”)
                 && n.getAttributes().getNamedItem(“USE”) == null
                 && n.getAttributes().getNamedItem(“DEF”) == null)
         {
           for(int p = 0; p < children.getLength(); p++)
           {
             Node child = children.item(p);
             if(!child.getNodeName().equals(“#text”))
             {
                 parent.insertBefore(child, parent.getFirstChild());
             }
           }
           parent.removeChild(n);
           replacecount++;
         }
    }
    This method removed 2,500 unnecessary nodes. This still wasn’t enough to make the scene workable, so I began to simplify the scene by replacing IndexedFaceSets with primitive geometry.

    The most important element in the scene were the bells themselves. I created a new node to represent a bell, that would be scaled to the desired size and re-used multiple times. In X3D jargon, this new node is called a prototype. A prototype defines a new node, and has its own scope for ROUTEs and DEFs. A prototype can be parametrised by defining a number of fields, which permit re-use, towards a component-based method of building complex scenes.

    At this stage each bell had three requirements, other than rendering the bell in 3D. Firstly, the bell had to sound when clicked, as if the bell were stuck in real-life. Secondly, the bell had to change colour when clicked, to visualise what parts of the instrument were playing. Thirdly, the bell had to be able to play when the mouse was hovering over the bell, so that a run of bells could be played in a glissando effect. The behaviour between a single-bell sound and a glissando would be toggled by pressing the ‘G’ key on the keyboard.
    Single sound of AudioClip
    The first requirement is the most straightforward to implement. It is a text-book use of the TouchSensor node, along with a Sound and AudioClip node. Keeping all the nodes grouped together, it is important that the TouchSensor is a sibling of the grouping node of the geometry, for the TouchSensor acts upon the child nodes of its parent. Thus:
    <Group>
    <TouchSensor />
    <Sound>
    <AudioClip />
    </Sound>

    <!– Geometry –>
    <Shape>

    </Shape>
    </Group>
    The AudioClip defines the sound to play with its url parameter. X3D allows multiple URLs to be specified, to allow for local and remote access. ROUTEs are used to implement the sound behaviour:
    <ROUTE fromNode=”singleTouch” fromField=”touchTime” toNode=”chime” toField=”stopTime”/>
    <ROUTE fromNode=”singleTouch” fromField=”touchTime” toNode=”chime” toField=”startTime”/>
    N.B. I include both stopTime and startTime as I had desired the bell-sound to restart when clicked again, much like a bell would if hit successive times. According to the X3D specification, passing the same time event for the stop and the start should result in the audio clip restarting. However I found mixed results with this, and mostly I see start/stop behaviour instead.
    Colour Highlight with ColorInterpolator
    Like all complicated concepts, using interpolators in X3D is straightforward once you understand it. I wanted to choose a colour for the bell’s material, which would change like a roll-over in CSS. In X3D, its easier to consider the problem as charting the node’s material to pass through a series of colour values, which is precisely what ColorInterpolator does. In this sense its more akin to a robot walking between waypoints than a roll-over paradigm.

    An interpolator (or the similar sequencer nodes) have two main variables. The key, which defines the points in the series, and the keyValue, which define the corresponding values at those points. The key is always between 0 and 1, representing the start and end of the cycle, with any number of fractions in between, seperated by whitespace. For my roll-over I defined 0, 0.5 and 1, so that I can pass through three colours, finally returning to the original colour at the end of the cycle. For the corresponding values, in this case a colour, I would need three-pairs of RGB values to correspond to the colours at 0, 0.5 and 1.

    In order to cause succession between the points, in X3D a TimeSensor is used to generate time events, so that the browser moves through the series, like a sequencer. When used alongside the touchsensor, these nodes can now be routed to achieve the roll-over effect.
    <TimeSensor DEF=”colourTimer” />
    <ColorInterpolator DEF=”flash” key=”0 0.5 1″ keyValue=”0 1 0 1 1 1 0.8 0.8 0.8″/>
    <TouchSensor DEF=”glissTouch” enabled=”false”>

    <ROUTE fromField=’touchTime’ fromNode=’singleTouch’ toField=’set_startTime’ toNode=’colourTimer’/>
    <ROUTE fromField=’fraction_changed’ fromNode=’colourTimer’ toField=’set_fraction’ toNode=’flash’/>
    <ROUTE fromField=’value_changed’ fromNode=’flash’ toField=’set_diffuseColor’ toNode=’material’/>
    Glissando effect with AudioClip
    The best result of the model was the glissando, simultaneously playing several samples of micro-tonal bells, creating a haunting and harmonic sound when the mouse cursor passes over a bell. This effect was a slight change from the single-touch, using a different field to drive the behaviour. touchTime would be too late; for this is the time value when the touch sensor’s geometry was clicked. Instead, TouchSensor provides an isOver event, which is set to true when the mouse cursor intersects the geometry. As I required a time value rather than a boolean value, I needed another node to convert the values, called TimeTrigger. TimeTrigger is an invisible node that acts like a black-box; accepting a boolean input and returning a timestamp output, triggerTime. I used this to route between the TouchSensor and the AudioClip to obtain the glissando effect, and could even use this to drive the colour flash.
    <ROUTE fromNode=”glissTouch” fromField=”isOver” toNode=”gliss” toField=”set_boolean” />
    <ROUTE fromNode=”gliss” fromField=”triggerTime” toNode=”chime” toField=”set_startTime” />
    <ROUTE fromField=’triggerTime’ fromNode=’gliss’ toField=’set_startTime’ toNode=’colourTimer’/>
    Toggle play mode with keyboard button press
    Finally, I needed to switch between glissando and the single-click modes by pressing a keyboard key. To keep the behaviours seperate, I defined two seperate TouchSensors, each routed differently to achieve the different behaviours. I defined the TouchSensor associated with the glissando effect to be disabled, with the enabled=”false” attribute on the touch sensor. The process of toggling thus became an alternation of the enabled attribute of the TouchSensor. The current state of the toggle is stored using a BooleanToggle node.

    The browser picks up keyboard events when you define a KeySensor within your scene. The KeySensor can then be routed to a script node, for processing. Below I wrote a short script to detect whether the letter ‘G’ had been pressed, and routed the result to the touch sensor.
    <KeySensor DEF=”glissMode” />
    <BooleanToggle DEF=”playMode” />

    <Script DEF=”logic” directOutput=”true”>
    <field name=’keyInput’ type=’SFString’ accessType=’inputOnly’/>
    <field name=’toggleGliss’ type=’SFBool’ accessType=’outputOnly’/>
    <![CDATA[ecmascript:
     function keyInput (inputValue)
    {
    if(inputValue == 'g' || inputValue == 'G')
    {
    toggleGliss = true;
    }
    }
    ]]>
    </Script>

    <ROUTE fromNode=”logic” fromField=”toggleGliss” toNode=”playMode” toField=”set_boolean” />
    <ROUTE fromNode=’glissMode’ fromField=’keyPress’ toNode=’logic’ toField=’keyInput’/>
    <ROUTE fromNode=”playMode” fromField=”toggle_changed” toNode=”glissTouchSensor” toField=”enabled” />
    Putting it all together
    Now I could define a prototype and re-use the bell logic and geometry. I would embed each prototype inside a transform element, so that I could scale and translate each individually. The only alteration I needed to make was with the button toggle; for the state of the toggle had to be held within the main scene, not within each prototype, because each prototype has its own scope. I modified the prototype to accept the boolean value of the BooleanToggle as a field, as well as the URL for the sound to play.
    <ProtoDeclare name=’Bell’>
    <ProtoInterface>
      <field accessType=’initializeOnly’ name=’soundURL’ type=’MFString’ />
        <field accessType=’inputOnly’ name=’playMode’ type=’SFBool’/>
      </ProtoInterface>
      <ProtoBody>
      <Group DEF=”BellMain”>
          <TimeSensor DEF=”colourTimer” />
          <ColorInterpolator DEF=”flash” key=”0 0.5 1″ keyValue=”0 1 0 1 1 1 0.8 0.8 0.8″/>
          <TouchSensor DEF=”glissTouch” enabled=”false”>
          <IS>
              <connect nodeField=’enabled’ protoField=’playMode’/>
            </IS>
          </TouchSensor>
          <TouchSensor DEF=”singleTouch” />
          <TimeTrigger DEF=”gliss” />
          <Sound maxFront=”100000″ maxBack=”100000″>
            <AudioClip DEF=”chime”>
           <IS>
                <connect nodeField=’url’ protoField=’soundURL’/>
              </IS>
            </AudioClip>
          </Sound>

          <!– Bell Geometry –>

    <BooleanToggle DEF=”playMode”>
    <IS>
    <connect nodeField=’set_boolean’ protoField=’playMode’/>
    </IS>
    </BooleanToggle>

    <!– Single-touch sound –>
    <ROUTE fromNode=”singleTouch” fromField=”touchTime” toNode=”chime” toField=”stopTime”/>
    <ROUTE fromNode=”singleTouch” fromField=”touchTime” toNode=”chime” toField=”startTime”/>

    <!– Glissando –>
    <ROUTE fromNode=”glissTouch” fromField=”isOver” toNode=”gliss” toField=”set_boolean” />
    <ROUTE fromNode=”gliss” fromField=”triggerTime” toNode=”chime” toField=”set_startTime” />
    <ROUTE fromField=’triggerTime’ fromNode=’gliss’ toField=’set_startTime’ toNode=’colourTimer’/>

    <!– Colour flash –>
    <ROUTE fromField=’touchTime’ fromNode=’singleTouch’ toField=’set_startTime’ toNode=’colourTimer’/>
    <ROUTE fromField=’fraction_changed’ fromNode=’colourTimer’ toField=’set_fraction’ toNode=’flash’/>
    <ROUTE fromField=’value_changed’ fromNode=’flash’ toField=’set_diffuseColor’ toNode=’material1′/>
    </ProtoBody>
    </ProtoDeclare>
    Rather than rigging up 144 route statements to pass each prototype the playmode value, I picked up this neat trick from the X3D mailing list to dynamically add routes via the SAI. In order for the script to work, all of the prototypes were grouped together in a single group, so that they could be passed to the script.
    <Script DEF=”logic” directOutput=”true”>
    <field name=”touchs” type=”SFNode” accessType=”initializeOnly”>
    <Group USE=”Touchable”/>
    </field>
    <field name=”playMode” type=”SFNode” accessType=”initializeOnly”>
    <BooleanToggle USE=”playMode” />
    </field>

    <![CDATA[ecmascript:
    function initialize()
    {
    scene = Browser.currentScene;

    for (i = 0; i < 144; i++)
    {
    bell = touchs.children;
    scene.addRoute(playMode, 'toggle_changed', bell, 'playMode');
    }
    }
    ]]>
    </Script>
    Next steps
    I was left only to rig-up the geometry for the stands and the bases. Overall, the model is working well. After the optimisations, the file was reduced to 1,500 lines of code, and renders at an acceptable framerate. The next challenge will be to reduce the file-size of the audio-clips: currently 10 second .wav files, before it can be delivered onto the web proper.

    The remaining area of functionality for this project is to work with MIDI to read-in compositions and play them using the new instrument, in effect, writing a basic MIDI sequencer in X3D. I’m currently working on this now, so watch this space! You can listen to a sample of the sounds being played on my music blog.

    Thanks to all those in the X3D Mailing List whose comments have helped me progress with this project.

    Continue Reading »
    No Comments

    As if one blog could ever be enough. I decided to finally get my act together and create a web presence for my musical aspirations- http://www.dangarland.me.uk .

    The website is a beta version of a music-community website I’m developing for Vibey Subscriptions Ltd. (watch this space). The software has many features, including:

    • Track uploading – takes a PCM, uploads it to a web-server, encodes it on the fly, generates mp3, ogg and flac and creates a webpage for them to go on.
    • Music streaming – using flash or Java applets the software streams files down to clients so that they can instantly hear songs
    • Video uploading / stream – Same idea as above, but with videos!
    • User management – Users can login and edit the band’s their assigned to, but no more. Punters can sign-up and interact with less privileges than full-users.
    • Subscriptions- Full integration with SecureTrading’s XPay subscription module (although this is disabled for my blog, which is absolutely free!)
    • Blogging – OK maybe not as fully-featured as wordpress, but that makes it simpler to use!

    The full version is close to completion. I have some user interface improvements to make, but hopefully it will be ready within weeks. I’ll be picking out some of the features and writing about how they work over the next few days.

    In the meantime, take a look at my music blog and let me know what you think! Don’t forget to comment / rate!

    Continue Reading »
    1 Comment

    I had just resurrected some old music from my music collection; some good, some very, very bad; but I wanted to be honest and display the information on my music blog. After all, it would show I have good taste in music ;)

    I was streaming music using the excellent Icecast streaming server, and I wanted to display the currently playing track on my rails-based music blog as a link, which when clicked would feed the artist and track info into Google in a new window to help others find out about artists they might not have heard of. Fortunately, the current track information is provided by Icecast and is used by iTunes to display the current track information while I’m listening. The information is hosted on the admin section of the icecast server, /admin/stats.xml, so actually the simple solution would be to grab that XML file, parse it, and obtain the track information. The element I was interested in was called ‘Title’, under the source element, which contained the Artist – Track Title information, presumably from the mp3′s ID3 tag.

    The first step was to obtain the XML file and read in the value of the Title element. I created a method named currently_playing in the application_helper.rb file, which would enable the method to be available to any view in the application.
    Net::HTTP.start(‘hostname.co.uk’ , 8888) {|http|
          req = Net::HTTP::Get.new(‘/admin/stats.xml’)
          req.basic_auth ‘admin’, ICECAST_ADMIN_PASSWORD
          response = http.request(req)
          xml = REXML::Document.new response.body
          xml.elements.each(‘icestats/source/title’) { |title|
              return title.text
          }
        }
    Note that I used a constant value for the Icecast admin password, controlled via the constants.rb file in the config folder. This nice block of code HTTP gets the XML file, takes care of the basic HTTP authentication and turns the result into an XML DOM, using XPath to retrieve the value of the Title element.

    I decided that I wanted to display this information in the top-right of my header, so I found that component in rails and added a link:
    <% cl = currently_listening
    unless cl.empty? %>
    <div id=”currentlylistening”>
       Currently listening to : <%= link_to cl, { :controller => ‘referrals’, :action => ‘redirect_google’,
            :title => CGI.escape(cl)}, :target => ‘_blank’ %>
    </div>
    <% end %>
    Finally, I added a method in my referrals controller, called redirect_google. That way, I don’t lose page rank having a link to Google and instead redirect the user where I want them to go.
    def redirect_google
        redirect_to ‘http://www.google.co.uk/search?q=’ + params + ‘&ie=utf-8&oe=utf-8&aq=t’
    end
    Now, whenever the user visits a page, they can see what I’m actually listening to in iTunes. Time to delete my embarrassing Simply Red, Eternal and Cher tracks…

    Continue Reading »
    2 Comments

    I like to think that I stay ahead of the times. In 2000, I used to think that my Creative Nomad jukebox with 6GB of hard-disk space was the most incredible thing ever, and I took mine to University, proud of its ability to reduce a shelf-load of CDs into an object no larger than one or two discs. It was cool how you could take a bunch of music, let them all get strung together into a continuous stream, and have them played back in a random order, like your own personal radio station without the ‘personalities’. Back then, Creative had to market them as jukeboxes- they were still too bulky to be used like iPod shuffles are now. But that was nearly ten years ago, and times must move on.

    I have found that the biggest problem after moving to mp3s is keeping up with my collection. I stopped collecting after around 20GB and began to just have smaller collections here and there: some music on my PC laptop, some on my Mac, some on my PC, some on a mp3 player. Overall, it became difficult to keep it all in one place, and so whenever I’d buy a CD, download an album or mix one of my own tracks my collection would become increasingly fragmented. Its got to the stage now where I haven’t actually listened to parts of my collection for many months, so I decided to do something about it.

    I wanted to setup my own jukebox, streaming music over the web, so that I could access it wherever I was, from any platform, at any time. That way, all my music is in one place and I save heaps of disc space on my local computers.

    So I decided to setup Icecast, an open-source streaming server. It works by receiving an audio stream from somewhere, and converting it into itty-bitty-bytes that are downloaded to clients over the Internet, such as iTunes. The audio stream can be a live feed from a soundcard, or taken from a playlist running off your hard drive. I used the latter approach, because I have a large directory of mp3 files that I want to listen to. This involves using another piece of software called Ices, which is responsible for building the audio stream sent to Icecast. Its a handy piece of software; working from a playlist, it can randomly choose a track, re-sample it to a lower bitrate (to save your bandwidth costs and keep the music playing smoothly) and even cross-fade between tracks.

    While I was busy rsyncing my music collection to my server, I downloaded and installed icecast 2.3.2 and ices 0.4 from source. I chose the older version of ices, because it deals with mp3s, whereas the newer version can only read ogg Vorbis files, and my collection consists mainly of mp3 files. I needed to install a couple of dependencies thrown up by configure, specifically libxslt, which I did using apt-get. So far so good.

    The first configuration step was configuring Icecast. By default, icecast creates a configuration file in /usr/local/etc/ called icecast.xml which you can edit. The file is commented with examples, and can be tweaked as needed. Don’t forget as this is an XML file that it should be well-formed with matching opening and closing tags, as well as opening and closing comments (and no nesting comments!). I reduced the number of clients (it is a private stream for me!), set the hostname/port, log directory and the source, relay and admin passwords (they’re ‘hackme’ by default!). Following that, I was able to test the server was working by running icecast and checking the error.log file:
    icecast -c /usr/local/etc/icecast.xml
    tail /var/log/icecast/error.log
    I could also visit the admin pages at the hostname and port I had configured, which show a basic admin interface.

    The next step was to provide audio for Icecast by configuring Ices. Similarly, the default install created an example configuration file in /usr/local/etc/ called ices.conf.dist. I moved this to ices.conf and began to edit. I changed:

    • <File> – I set this to be the playlist file I wanted for the stream. The playlist file is simply a text file with a path to an mp3 file on each line, so I generated it automatically from the music files I kept in /music.
      find /music -name *.mp3 > /usr/local/etc/playlist.txt
    • <Randomize> – I set this to 1 so that Ices jumped around the list, creating a radio station style mix, rather than playing through sequentially.
    • <Crossfade> – I set this to 5 so that each song fades-in/fades-out over the course over five seconds, resulting in nice, continuous play.
    • <BaseDirectory> – I set this to be the same as the log directory of Icecast so that the logs were nearby each other.
    • <Hostname> – I set this to match the hostname I configured in Icecast.
    • <Port> – Ditto…
    • <Password> – Same…
    • <Name> – I set this to “Dan’s Jukebox”, which is what the stream is listed under in iTunes.
    • <Genre> – I set this to “Anything”.
    • <Description> – This also appears on the web interface and iTunes so I wrote something in there too.
    • <URL> – This URL is a page used to describe the stream, and appears on rotation in the iTunes interface so I used my website URL.
    • <Public> – I set this to 0 so that the stream isn’t listed publicly and I get subpoenaed by the RIAA…
    • <Bitrate> – Very important! This is the setting that Ices uses to determine what quality to send the audio in, and has implications on the amount of bandwidth you use; which in turn determines the financial cost and smoothness of your stream. If your stream is available to multiple users, you have to consider that this figure would be multiplied by the number of listeners, so be careful not to set it too high. 64kbps is about the quality you get listening to MySpace and is low-quality; but you won’t really notice if listening on a laptop speaker anyway. Bearing in mind that the mp3s were mostly encoded at 128kps originally, I decided to keep my bandwidth use down and started out with 64kbs. It sounds alright to me, maybe I’ll ramp it up to about 80-something later if I feel like it.

    Once configured, I tested Ices by running it without any options:
    ices
    By default, Icecast and Ices run in the foreground, which means that once you start running them they don’t return the console back to you and you have to open another to keep using Linux. I wanted them to run in the background as daemons so that when my server boots up / restarts, or I log-out, the music keeps going. I so put together two init.d scripts, starting from /etc/skeleton, to start/stop Icecast and Ices. Below is the icecast init.d script I’m using, and Ices is similar.
    #! /bin/sh
    # Author: Dan Garland dan@NOSPAMdangarland.co.uk>

    # Do NOT “set -e”

    # PATH should only include /usr/* if it runs after the mountnfs.sh script
    PATH=/sbin:/usr/sbin:/bin:/usr/bin
    DESC=”Icecast Server”
    NAME=icecast
    DAEMON=/usr/local/bin/$NAME
    DAEMON_ARGS=”-b -c /usr/local/etc/icecast.xml”
    ICES=/usr/local/bin/ices
    USER=$NAME
    GROUP=$NAME
    PIDFILE=/var/run/$NAME.pid
    ICES_PIDFILE=/var/run/ices.pid
    SCRIPTNAME=/etc/init.d/$NAME

    # Exit if the package is not installed
    || exit 0

    # Read configuration variable file if it is present
    && . /etc/default/$NAME

    # Load the VERBOSE setting and other rcS variables
    . /lib/init/vars.sh

    # Define LSB log_* functions.
    # Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
    . /lib/lsb/init-functions

    #
    # Function that starts the daemon/service
    #
    do_start()
    {
    # Return
    # 0 if daemon has been started
    # 1 if daemon was already running
    # 2 if daemon could not be started

    start-stop-daemon –start –quiet –chuid $USER:$GROUP –pidfile $PIDFILE –exec $DAEMON –test > /dev/null \
    || return 1

    start-stop-daemon –start –quiet –chuid $USER:$GROUP –pidfile $PIDFILE –exec $DAEMON — \
    $DAEMON_ARGS \
    || return 2
    # Add code here, if necessary, that waits for the process to be ready
    # to handle requests from services started subsequently which depend
    # on this one. As a last resort, sleep for some time.
    }

    #
    # Function that stops the daemon/service
    #
    do_stop()
    {
    # Return
    # 0 if daemon has been stopped
    # 1 if daemon was already stopped
    # 2 if daemon could not be stopped
    # other if a failure occurred
    start-stop-daemon –stop –quiet –retry=TERM/30/KILL/5 –pidfile $PIDFILE –name $NAME
    RETVAL=”$?”
    && return 2
    # Wait for children to finish too if this is a daemon that forks
    # and if the daemon is only ever run from this initscript.
    # If the above conditions are not satisfied then add some other code
    # that waits for the process to drop all resources that could be
    # needed by services started subsequently. A last resort is to
    # sleep for some time.
    start-stop-daemon –stop –quiet –oknodo –retry=0/30/KILL/5 –exec $DAEMON
    && return 2
    # Many daemons don’t delete their pidfiles when they exit.
    rm -f $PIDFILE
    return “$RETVAL”
    }

    #
    # Function that sends a SIGHUP to the daemon/service
    #
    do_reload() {
    #
    # If the daemon can reload its configuration without
    # restarting (for example, when it is sent a SIGHUP),
    # then implement that here.
    #
    start-stop-daemon –stop –signal 1 –quiet –pidfile $PIDFILE –name $NAME
    return 0
    }

    case “$1″ in
    start)
    && log_daemon_msg “Starting $DESC” “$NAME”
    do_start
    case “$?” in
    0|1) && log_end_msg 0 ;;
    2) && log_end_msg 1 ;;
    esac
    ;;
    stop)
    && log_daemon_msg “Stopping $DESC” “$NAME”
    do_stop
    case “$?” in
    0|1) && log_end_msg 0 ;;
    2) && log_end_msg 1 ;;
    esac
    ;;
    #reload|force-reload)
    #
    # If do_reload() is not implemented then leave this commented out
    # and leave ‘force-reload’ as an alias for ‘restart’.
    #
    #log_daemon_msg “Reloading $DESC” “$NAME”
    #do_reload
    #log_end_msg $?
    #;;
    restart|force-reload)
    #
    # If the “reload” option is implemented then remove the
    # ‘force-reload’ alias
    #
    log_daemon_msg “Restarting $DESC” “$NAME”
    do_stop
    case “$?” in
    0|1)
    do_start
    case “$?” in
    0) log_end_msg 0 ;;
    1) log_end_msg 1 ;; # Old process is still running
    *) log_end_msg 1 ;; # Failed to start
    esac
    ;;
    *)
    # Failed to stop
    log_end_msg 1
    ;;
    esac
    ;;
    *)
    #echo “Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}” >&2
    echo “Usage: $SCRIPTNAME {start|stop|restart|force-reload}” >&2
    exit 3
    ;;
    esac

    :
    Note the -b option to run in the background and the –chuid option to run the program as the icecast user and group (Icecast doesn’t run as root). If you don’t have a icecast user or group, create them as root with the adduser and addgroup commands:
    adduser icecast
    addgroup icecast
    I could then tell Debian to run these scripts at start-up using update-rc.d:
    update-rc.d icecast defaults
    update-rc.d ices defaults
    Once running, I could point iTunes to the stream by choosing Advanced -> Open Audio Stream, and typing in the full url to the mointpoint. Now I’m listening to some track I swear I haven’t heard since the mid 90′s, and I want to tell the world.

    Continue Reading »
    2 Comments