<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>hatsuseno&#039;s blog</title>
	<atom:link href="http://blog.hatsuseno.org/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.hatsuseno.org</link>
	<description>rantings on tech</description>
	<lastBuildDate>Tue, 12 Jul 2011 09:26:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Seventeen or Bust; a gentoo daemon script</title>
		<link>http://blog.hatsuseno.org/index.php/seventeen-or-bust-a-gentoo-daemon-script/</link>
		<comments>http://blog.hatsuseno.org/index.php/seventeen-or-bust-a-gentoo-daemon-script/#comments</comments>
		<pubDate>Tue, 12 Jul 2011 08:56:22 +0000</pubDate>
		<dc:creator>hatsuseno</dc:creator>
				<category><![CDATA[gentoo]]></category>
		<category><![CDATA[Tips and Tricks]]></category>

		<guid isPermaLink="false">http://blog.hatsuseno.org/?p=256</guid>
		<description><![CDATA[Seventeen or Bust It&#8217;s been a while since I&#8217;ve just my available CPU cycles for vanity, but I&#8217;m a sucker for stats. Normally, you&#8217;d just start the binary mprime in some terminal and let it be, I didn&#8217;t like that for my servers (basically, I&#8217;d have to run SoB under some user, in some screen, [...]]]></description>
			<content:encoded><![CDATA[<h2><a href="http://www.seventeenorbust.com/">Seventeen or Bust</a></h2>
<p>It&#8217;s been a while since I&#8217;ve just my available CPU cycles for vanity, but I&#8217;m a sucker for stats. Normally, you&#8217;d just start the binary mprime in some terminal and let it be, I didn&#8217;t like that for my servers (basically, I&#8217;d have to run SoB under some user, in some screen, and whenever something happens I&#8217;d have to manually interfere to kill it or restart it). So I wrote a very simple rc script to handle it for me.</p>
<h2>The script</h2>
<h3>/etc/init.d/seventeenorbust</h3>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/sbin/runscript</span>
&nbsp;
depend<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span>
        use net
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
start<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span>
        <span style="color: #007800;">PWHOME</span>=<span style="color: #ff0000;">&quot;<span style="color: #007800;">$(getent passwd $USER | awk -F: '{ print $6 }')</span>&quot;</span>
&nbsp;
        ebegin <span style="color: #ff0000;">&quot;Starting SeventeenOrBust&quot;</span>
        <span style="color: #c20cb9; font-weight: bold;">env</span> <span style="color: #007800;">TERM</span>=<span style="color: #ff0000;">&quot;xterm&quot;</span> \
                start-stop-daemon \
                        <span style="color: #660033;">--start</span> \
                        <span style="color: #660033;">--user</span> <span style="color: #007800;">$USER</span> \
                        <span style="color: #660033;">--env</span> <span style="color: #007800;">HOME</span>=<span style="color: #ff0000;">&quot;<span style="color: #007800;">${PWHOME:-/home/$USER}</span>&quot;</span> \
                        <span style="color: #660033;">--name</span> sob \
                        <span style="color: #660033;">--exec</span> <span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>bin<span style="color: #000000; font-weight: bold;">/</span><span style="color: #c20cb9; font-weight: bold;">screen</span> <span style="color: #660033;">--</span> <span style="color: #660033;">-dmS</span> sob <span style="color: #000000; font-weight: bold;">/</span>home<span style="color: #000000; font-weight: bold;">/</span>sob<span style="color: #000000; font-weight: bold;">/</span>mprime <span style="color: #660033;">-d</span>
        eend <span style="color: #007800;">$?</span>
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
stop<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span>
        ebegin <span style="color: #ff0000;">&quot;Stopping SeventeenOrBust&quot;</span>
        start-stop-daemon <span style="color: #660033;">--stop</span> <span style="color: #660033;">--signal</span> <span style="color: #000000;">2</span> <span style="color: #660033;">--name</span> sob
        eend <span style="color: #007800;">$?</span>
<span style="color: #7a0874; font-weight: bold;">&#125;</span></pre></div></div>

<h3>/etc/conf.d/seventeenorbust</h3>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #007800;">USER</span>=<span style="color: #ff0000;">&quot;sob&quot;</span></pre></div></div>

<h2>Setup</h2>
<ol>
<li>Copy the above files to your filesystem</li>
<li><code>$ useradd -m -p "sob" sob</code></li>
<li>Add a <code>DenyUsers</code> entry in your <code>sshd_config</code> for the <code>sob</code> account, don&#8217;t want people getting access to your box with a default user</li>
<li>Login as the sob user, download and install the SoB binaries in your homedir and configure SoB accordingly (usually, this is just setting up your username in <code>prime.txt</code></li>
<li>(Optional); <code>$ rc-update add seventeenorbust default</code></li>
</ol>
<h2>Like to view progress?</h2>
<p>If you like to keep tabs on your instance, completion percentage and such, you can log in as the <code>sob</code>-user and run <code>$ screen -dr sob</code> to attach to te daemon&#8217;s screen session.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hatsuseno.org/index.php/seventeen-or-bust-a-gentoo-daemon-script/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android 2.2 USB Tethering on a Gentoo box</title>
		<link>http://blog.hatsuseno.org/index.php/android-2-2-usb-tethering-on-a-gentoo-box/</link>
		<comments>http://blog.hatsuseno.org/index.php/android-2-2-usb-tethering-on-a-gentoo-box/#comments</comments>
		<pubDate>Tue, 03 Aug 2010 12:57:58 +0000</pubDate>
		<dc:creator>hatsuseno</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[gentoo]]></category>
		<category><![CDATA[froyo]]></category>
		<category><![CDATA[networking]]></category>

		<guid isPermaLink="false">http://blog.hatsuseno.org/?p=224</guid>
		<description><![CDATA[Why not use the WiFi Hotspot Recently HTC rolled out the Android 2.2 upgrade for my Desire, finally enabling USB Tethering out of the box. Often enough I used the WiFi hotspot feature on my previous phone to enable my laptop to have internet on the go. Android&#8217;s got this feature as well nowadays, but [...]]]></description>
			<content:encoded><![CDATA[<h2>Why not use the WiFi Hotspot</h2>
<p>Recently HTC rolled out the Android 2.2 upgrade for my Desire, finally enabling USB Tethering out of the box. Often enough I used the WiFi hotspot feature on my previous phone to enable my laptop to have internet on the go. Android&#8217;s got this feature as well nowadays, but I don&#8217;t really like it because it really, and I mean *really*, puts the drain on your phone&#8217;s battery. USB Tethering seems like a much better solution.</p>
<h2>Setup for Android</h2>
<p>This is by far the easiest part, just hook up your phone, drag down the status bar and instead of charge only, or whatever mode it is in at that time, set it to USB Tethering.</p>
<h2>Setup for Gentoo</h2>
<p>This part is a bit trickier, especially when you roll your own kernel. Open up <code>menuconfig</code> for your kernel and enable these options</p>

<div class="wp_syntax"><div class="code"><pre class="none" style="font-family:monospace;">Device Drivers ---&gt;
  [*] Network device support ---&gt;
    USB Network Adapters ---&gt;
      [*] Multi-purpose USB Networking Framework
        &lt;*&gt; CDC Ethernet support
        &lt;*&gt; CDC EEM support
        &lt;*&gt; Simple USB Network Links (CDC Ethernet subset)
          [*] Embedded ARM Linux links
  [*] USB Support ---&gt;
    &lt;*&gt; USB Modem (CDC ACM) support
    &lt;*&gt; USB Wireless Device Management support</pre></div></div>

</p>
<p>Now build your kernel as usual and reboot. When you now plug in your Android phone when it&#8217;s in USB Tethering mode, if all is well, you should be able to see a new network interface, <code>usbX</code>, X usually being 0. The link might be down, so check it with the command</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #c20cb9; font-weight: bold;">ifconfig</span> <span style="color: #660033;">-a</span></pre></div></div>

<p>Which will output something like this</p>

<div class="wp_syntax"><div class="code"><pre class="none" style="font-family:monospace;">usb0      Link encap:Ethernet  HWaddr 26:10:72:ab:38:0e  
            BROADCAST MULTICAST  MTU:1500  Metric:1
            RX packets:0 errors:0 dropped:0 overruns:0 frame:0
            TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
            collisions:0 txqueuelen:1000 
            RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)</pre></div></div>

<p>Which means it all worked. Now all you have to do is run a DHCP request on that interface, and Android will handle the rest. You can set up a init.d script for this interface much the same way you would for a normal interface. Just make a symlink from <code>/etc/init.d/net.lo</code> to <code>/etc/init.d/net.usb0</code> and run that script whenever you want. </p>
<h2>Beautifying the whole thing</h2>
<p>Running around on the console starting bootscripts like that doesn&#8217;t suit everyone, including me when I&#8217;m just on the road and stuff needs to work. I recommend using something like <a href='http://wicd.sourceforge.net/'>wicd</a> or <a href='http://projects.gnome.org/NetworkManager/'>NetworkManager</a> to handle it for you. Using wicd it&#8217;s pretty easy to make it automagically use the <code>usb0</code> interface when it appears, so you&#8217;ll only have to plug it on for it to work.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hatsuseno.org/index.php/android-2-2-usb-tethering-on-a-gentoo-box/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Porting Windows behaviour to Linux :)</title>
		<link>http://blog.hatsuseno.org/index.php/porting-windows-behaviour-to-linux/</link>
		<comments>http://blog.hatsuseno.org/index.php/porting-windows-behaviour-to-linux/#comments</comments>
		<pubDate>Wed, 07 Jul 2010 17:33:54 +0000</pubDate>
		<dc:creator>hatsuseno</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[awesome]]></category>
		<category><![CDATA[custom-scripts]]></category>
		<category><![CDATA[gui]]></category>
		<category><![CDATA[scripts]]></category>

		<guid isPermaLink="false">http://blog.hatsuseno.org/?p=214</guid>
		<description><![CDATA[In the olden days when I still used Windows, I loved having the ALT+PrintScreen keycombo around, it makes a screen capture of only the currently active window, nicely cropped and everything. This saves you the hassle of aligning it pixel-perfect in Paint. On Linux, at least using awesome, I haven&#8217;t been able to do this, [...]]]></description>
			<content:encoded><![CDATA[<p>In the olden days when I still used Windows, I loved having the ALT+PrintScreen keycombo around, it makes a screen capture of only the currently active window, nicely cropped and everything. This saves you the hassle of aligning it pixel-perfect in Paint. On Linux, at least using awesome, I haven&#8217;t been able to do this, so I wrote a quick script that allows me to do that and a bit more.</p>
<p><strong>grabw</strong> is a bash script that allows you to</p>
<ol>
<li>Take a screenshot of a window by X window ID</li>
<li>Take a screenshot of a window the user first has to click, using xwininfo</li>
<li>The above two with or without asking for a filename using Zenity&#8217;s file selection dialogue window</li>
</ol>
<p>Combine this with awesome&#8217;s ability to spawn processes on the fly and pass parameters (such as window IDs, *hint hint*) this is one feature I&#8217;m glad to have back</p>
<p><strong>grabw 0.2</strong> has been released into public domain, you can find it on my <a href="http://projects.hatsuseno.org">projects</a> page.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hatsuseno.org/index.php/porting-windows-behaviour-to-linux/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Secure and safe computing on the go</title>
		<link>http://blog.hatsuseno.org/index.php/secure-and-safe-computing-on-the-go/</link>
		<comments>http://blog.hatsuseno.org/index.php/secure-and-safe-computing-on-the-go/#comments</comments>
		<pubDate>Tue, 11 May 2010 21:46:26 +0000</pubDate>
		<dc:creator>hatsuseno</dc:creator>
				<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[cryptsetup]]></category>
		<category><![CDATA[dmcrypt]]></category>
		<category><![CDATA[encryption]]></category>
		<category><![CDATA[initramfs]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[luks]]></category>
		<category><![CDATA[lvm]]></category>
		<category><![CDATA[lvm2]]></category>

		<guid isPermaLink="false">http://blog.hatsuseno.org/?p=151</guid>
		<description><![CDATA[I&#8217;m a bit paranoid when it comes to the &#8220;evil corporations and governments trying to spy on us all&#8221;, as such I like doing encryption tests on old an esoteric storage devices, like JAZ-drives and LS120 &#8216;SuperDisk&#8217; technology. Recently though, especially because of all the news of laptops being checked on airports and such, I [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m a bit paranoid when it comes to the &#8220;evil corporations and governments trying to spy on us all&#8221;, as such I like doing encryption tests on old an esoteric storage devices, like JAZ-drives and LS120 &#8216;SuperDisk&#8217; technology. Recently though, especially because of all the news of laptops being checked on airports and such, I figured it was about time I got serious and see how (semi-) full-disk encryption works for GNU/Linux, specifically Gentoo.</p>
<p><em>This walkthrough assumes you are setting up a new Gentoo system and are not trying to migrate an existing system to a encrypted setup.</em></p>
<p>There are a couple of options mostly noted on blogs and in manuals;</p>
<dl>
<dt><strong>Home-partition encryption</strong></dt>
<dd>Perhaps the easiest to set up, this just encrypts the partition where all user data ought to go. In gentoo this is pretty easy, if I recall correctly there are init.d scripts in place that take care of mounting this for you and prompting for a passphrase at an appropriate time.</dd>
<dt><strong>Full disk encryption</strong></dt>
<dd>Also relatively easy, but this requires you to have another volume (usb key, cd-rom, floppy?) with you at all times to boot the system and decrypt the drive in order for the system to start.</dd>
<dt><strong>Unencrypted boot partition</strong></dt>
<dd>This devides the partitions on your drive between one small boot partition and a encrypted blob that is further broken up into smaller pieces using <abbr title='Logical Volume Management'>LVM</abbr> or some similar volume management software.</dd>
</dl>
<p>To each his own, and I personally like the unencrypted boot, because it encrypts more than just my home folder, and when in place is easy to extend upon or change. The rest of this blog post is dedicated to the setup of this method of encryption, although the other two options could easily be derived from the steps taken.</p>
<p>First up, the partition layout. As noted in the description, the unencrypted boot-partition take on data encryption divides the drive up into two chunks, in my case like this:</p>
<table border='1' rules='all' cellpadding='2px'>
<tr>
<td>Blockdevice</td>
<td>Size</td>
</tr>
<tr>
<td>sda1</td>
<td>64 MiB</td>
</tr>
<tr>
<td>sda2</td>
<td>the rest</td>
</tr>
</table>
<p><cpde>sda2</code> will first be encrypted and the encrypted contents will contain a LVM2 <abbr title='Volume Group'>VG</abbr>. This means that all <abbr title='Logical Volume'>LV</abbr>s created from this VG will be fully encrypted under a shared passphrase. Adding and removing LVs (analogous with partitions) becomes very easy under LVM, and also adds some extra features like online resizing of the LV (if the underlying filesystem supports online resizing as well).</p>
<h3>Phase 1 - Preparations</h3>
<p>First things first, create the partitions as described above with your favourite partitioning tool (mine's <code>cfdisk</code>, but anything that partitions will do fine). When you've done this it's time to completely overwrite the volume-to-be-encrypted with random data, making it very difficult to estimate the amount of data hidden in the encrypted volume.</p>
<p>You can use a tool like <code>shred</code> for this task, but by default it overwrites the volume at thrice with pseudo-random data. This satisfies some paranoid people who believe magnetic drives retain some part of their previous polarization, perhaps making it possible to read data already overwritten. I don't have any proof in favor or against this theory, and if you have the time it can't hurt to have the driver fully overwritten three times. For those who want to get this done with as quickly as possible a simple <code>dd</code> will suffice. </p>
<p>
<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;"># A simple direct copy, use cat or pv for enhanced throughput</span>
$ <span style="color: #c20cb9; font-weight: bold;">dd</span> <span style="color: #007800;"><span style="color: #000000; font-weight: bold;">if</span></span>=<span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>urandom <span style="color: #007800;">of</span>=<span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>sda2</pre></div></div>

<p><em>-or-</em></p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;"># use -v for increased verbosity, i.e. a progress bar</span>
$ <span style="color: #c20cb9; font-weight: bold;">shred</span> <span style="color: #660033;">-v</span> <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>sda2</pre></div></div>

</p>
<h3>Phase 2 - Encryption and LVM</h3>
<p>This is where the magic happens, but it turns out to be really easy to do. First we encrypt <code>sda2</code> using <code>cryptsetup</code>, next we create the VG and LVs so we can start using our new volumes.</p>
<p>
<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;"># encrypt using the Rijndael cipher, use 256 bit key size</span>
$ cryptsetup luksFormat <span style="color: #660033;">-c</span> aes <span style="color: #660033;">-s</span> <span style="color: #000000;">256</span> <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>sda2
&nbsp;
<span style="color: #666666; font-style: italic;"># open the newly created volume</span>
$ cryptsetup luksOpen <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>sda2 crypt</pre></div></div>

</p>
<p>
Alrighty, if all went as it should you should now have a decrypted volume located at <code>/dev/mapper/crypt</code>. Next up, LVM.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;"># I name my volume group after the computer's hostname</span>
$ vgcreate cluebrick <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>mapper<span style="color: #000000; font-weight: bold;">/</span>crypt
&nbsp;
<span style="color: #666666; font-style: italic;"># create rootfs lv, 20 GiB big in the vg cluebrick</span>
$ lvcreate <span style="color: #660033;">-L</span> 20G <span style="color: #660033;">-n</span> root cluebrick
&nbsp;
<span style="color: #666666; font-style: italic;"># create swap lv, 2 GiB in the vg cluebrick</span>
$ lvcreate <span style="color: #660033;">-L</span> 2G <span style="color: #660033;">-n</span> swap cluebrick
&nbsp;
<span style="color: #666666; font-style: italic;"># create the home volume... etc</span>
$ lvcreate <span style="color: #660033;">-L</span> 32G <span style="color: #660033;">-n</span> home cluebrick</pre></div></div>

</p>
<p>So far so good, these LVs should be accessible through <code>/dev/cluebrick/{root,swap,home}</code>. If that's not the case, try this set of commands, outdated systems might pick up on the LVs after these.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;"># if at first you don't succeed...</span>
$ vgchange <span style="color: #660033;">-a</span> n
$ vgexport <span style="color: #660033;">-a</span> 
$ vgimport <span style="color: #660033;">-a</span>
$ vgchange <span style="color: #660033;">-a</span> y</pre></div></div>

</p>
<h3>Phase 3 - System installation</h3>
<p>I'm going to leave this one up to you, if you are a Gentoo buff you should be able to pick up from here, starting with formatting your newly created volumes. There are <a href='http://www.gentoo.org/doc/en/handbook/handbook-x86.xml?full=1#filesystems'>plenty</a> tutorials out there that do a better job then I would at covering the installation. If you're going to migrate an existing system, this would be the time to start copying files back and forth.</p>
<h3>Phase 4 - Kernel configuration</h3>
<p>Rolling your own kernel isn't very difficult, nor is it a required part of the process, but for completeness' sake I'll note some things you need to take care of in order for this system to work. I do not recommend doing this if you don't have prior experience with compiling kernels, there's a lot more settings, flipswitches and knobby thingies that can royally bite you in the ass.
<p>In the kernel menuconfig, be sure to check the following settings and adjust if necessary</p>

<div class="wp_syntax"><div class="code"><pre class="none" style="font-family:monospace;">General setup  ---&gt;
  [*] Initial RAM filesystem and RAM disk (initramfs/initrd) support
&nbsp;
Device Drivers  ---&gt;
  [*] Block devices  ---&gt;
    &lt;*&gt;   RAM block device support</pre></div></div>

<p>If you like, you can let the kernel take care of the creation of a initramfs by setting the following variable:</p>

<div class="wp_syntax"><div class="code"><pre class="none" style="font-family:monospace;">General setup  ---&gt;
  [*] Initial RAM filesystem and RAM disk (initramfs/initrd) support
    (/usr/src/initramfs)    Initramfs source file(s)</pre></div></div>

</p>
<p>Depending on whether you chose to let the kernel roll your initramfs instead of you doing it yourself, a few steps will be different, I'll highlight the differences as they come. Personally I let the kernel roll the initramfs for me, that way I don't have to fiddle with my bootloader settings.</p>
<h3>Phase 5 - Building the initramfs</h3>
<p>In order for the system to boot you'll need what's called a early rootfs. Basically this is a small filesystem contained in your boot partition or inside the kernel image itself which as the tools and scripts on board to deal with the decryption of your rootfs and setting it up so Linux can continue booting as usual. It's important to note that this is a very small, purpose built rootfs, it won't contain a lot of tools you're used to when working on the command line. A short list of items that do go into this image, and the reason why. Also, because we have to be lean on functionality all programs included will have to be statically compiled, or you have to be willing to manually copy the required libraries, something that's hard to maintain and very cumbersome to debug when it hits the fan.</p>
<dl>
<dt><strong>busybox</strong></dt>
<dd>busybox contains most of the system tools you'll need in bootstrapping your system. Things like mount, sleep and a simple shell are all provided by one big binary which installs symlinks for the tools it provides when instructed to do so. Gentoo provides the USE-flag "static" in combination with it's package for this program, which causes busybox to also be built as a static binary that we can use.</p>
<dt><strong>LVM</strong></dt>
<dd>This one is a no-brainer, we need LVM to access our root filesystem. Gentoo's Portage also provides the "static" USE-flag for this package, making it easy for us to use it for this purpose.</dd>
<dt><strong>cryptsetup</strong></dt>
<dd>Also a no-brainer. Here the USE-flag however is not "static", but "dynamic", and it needs to be explicitly negated. (So, add "-dynamic" the USE variable in <code>make.conf</code>)</dd>
</dl>
<p>Alright, let's get crackin'.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;"># make the fs structure</span>
$ <span style="color: #c20cb9; font-weight: bold;">mkdir</span> <span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>src<span style="color: #000000; font-weight: bold;">/</span>initramfs
$ <span style="color: #7a0874; font-weight: bold;">cd</span> <span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>src<span style="color: #000000; font-weight: bold;">/</span>initramfs
$ <span style="color: #c20cb9; font-weight: bold;">mkdir</span> <span style="color: #660033;">-p</span> bin dev etc sbin usr var root mnt<span style="color: #000000; font-weight: bold;">/</span>root proc sys tmp
&nbsp;
<span style="color: #666666; font-style: italic;"># copy essential binaries</span>
$ <span style="color: #c20cb9; font-weight: bold;">cp</span> <span style="color: #000000; font-weight: bold;">`</span><span style="color: #c20cb9; font-weight: bold;">which</span> busybox.static<span style="color: #000000; font-weight: bold;">`</span> bin<span style="color: #000000; font-weight: bold;">/</span>bb
$ <span style="color: #c20cb9; font-weight: bold;">cp</span> <span style="color: #000000; font-weight: bold;">`</span><span style="color: #c20cb9; font-weight: bold;">which</span> cryptsetup<span style="color: #000000; font-weight: bold;">`</span> sbin
$ <span style="color: #c20cb9; font-weight: bold;">cp</span> <span style="color: #000000; font-weight: bold;">`</span><span style="color: #c20cb9; font-weight: bold;">which</span> lvm.static<span style="color: #000000; font-weight: bold;">`</span> sbin<span style="color: #000000; font-weight: bold;">/</span>lvm
&nbsp;
<span style="color: #666666; font-style: italic;"># housekeeping</span>
$ <span style="color: #c20cb9; font-weight: bold;">touch</span> init
$ <span style="color: #c20cb9; font-weight: bold;">chmod</span> +x init
$ <span style="color: #7a0874; font-weight: bold;">cd</span> bin
$ <span style="color: #c20cb9; font-weight: bold;">ln</span> <span style="color: #660033;">-s</span> bb busybox
$ <span style="color: #7a0874; font-weight: bold;">cd</span> ..<span style="color: #000000; font-weight: bold;">/</span>sbin
&nbsp;
<span style="color: #666666; font-style: italic;"># create symlinks for all LVM supported operations.</span>
$ .<span style="color: #000000; font-weight: bold;">/</span>lvm <span style="color: #7a0874; font-weight: bold;">help</span> <span style="color: #000000;">2</span><span style="color: #000000; font-weight: bold;">&gt;&amp;</span><span style="color: #000000;">1</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">grep</span> <span style="color: #660033;">-e</span> <span style="color: #ff0000;">'^ *[plv][vg]'</span> <span style="color: #000000; font-weight: bold;">|</span> \
  <span style="color: #c20cb9; font-weight: bold;">awk</span> <span style="color: #ff0000;">'{print $1}'</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">xargs</span> <span style="color: #660033;">-n1</span> <span style="color: #c20cb9; font-weight: bold;">ln</span> <span style="color: #660033;">-s</span> lvm
&nbsp;
<span style="color: #666666; font-style: italic;"># on to /dev</span>
$ <span style="color: #7a0874; font-weight: bold;">cd</span> ..<span style="color: #000000; font-weight: bold;">/</span>dev
$ <span style="color: #c20cb9; font-weight: bold;">cp</span> <span style="color: #660033;">-a</span> <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>console <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>tty <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>zero <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>null .</pre></div></div>

</p>
<p>Next up, the init script. We're using busybox's shell, so don't expect anything too fancy scripting wise, we just need to get our system up, and that's it. The more you code, the more you can break. Copy the following listing into your script and customize where necessary.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/busybox sh</span>
&nbsp;
busybox <span style="color: #660033;">--install</span> <span style="color: #660033;">-s</span>
&nbsp;
<span style="color: #c20cb9; font-weight: bold;">mount</span> <span style="color: #660033;">-t</span> proc none <span style="color: #000000; font-weight: bold;">/</span>proc
<span style="color: #c20cb9; font-weight: bold;">mount</span> <span style="color: #660033;">-t</span> sysfs none <span style="color: #000000; font-weight: bold;">/</span>sys
&nbsp;
<span style="color: #666666; font-style: italic;"># populate /dev</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;/sbin/mdev&quot;</span> <span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #000000; font-weight: bold;">/</span>proc<span style="color: #000000; font-weight: bold;">/</span>sys<span style="color: #000000; font-weight: bold;">/</span>kernel<span style="color: #000000; font-weight: bold;">/</span>hotplug
mdev <span style="color: #660033;">-s</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># sleep 1 second so we don't get overrun by kprintf's</span>
<span style="color: #c20cb9; font-weight: bold;">sleep</span> <span style="color: #000000;">1</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># safeguard against failed unlocking</span>
cryptsetup luksOpen <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>sda3 crypt <span style="color: #000000; font-weight: bold;">||</span> <span style="color: #7a0874; font-weight: bold;">exec</span> <span style="color: #000000; font-weight: bold;">/</span>bin<span style="color: #000000; font-weight: bold;">/</span><span style="color: #c20cb9; font-weight: bold;">sh</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># try and find all LVM volumes</span>
vgscan
vgchange <span style="color: #660033;">-a</span> y
&nbsp;
<span style="color: #666666; font-style: italic;"># safeguard against failed mount</span>
<span style="color: #c20cb9; font-weight: bold;">mount</span> <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>cluebrick<span style="color: #000000; font-weight: bold;">/</span>root <span style="color: #000000; font-weight: bold;">/</span>mnt<span style="color: #000000; font-weight: bold;">/</span>root <span style="color: #000000; font-weight: bold;">||</span> <span style="color: #7a0874; font-weight: bold;">exec</span> <span style="color: #000000; font-weight: bold;">/</span>bin<span style="color: #000000; font-weight: bold;">/</span><span style="color: #c20cb9; font-weight: bold;">sh</span>
&nbsp;
<span style="color: #c20cb9; font-weight: bold;">umount</span> <span style="color: #000000; font-weight: bold;">/</span>proc
<span style="color: #c20cb9; font-weight: bold;">umount</span> <span style="color: #000000; font-weight: bold;">/</span>sys
&nbsp;
<span style="color: #7a0874; font-weight: bold;">exec</span> switch_root <span style="color: #000000; font-weight: bold;">/</span>mnt<span style="color: #000000; font-weight: bold;">/</span>root <span style="color: #000000; font-weight: bold;">/</span>sbin<span style="color: #000000; font-weight: bold;">/</span>init</pre></div></div>

</p>
<p>Of course, this is a very crude init script, it'll get the job done, and even provide you with a rescue shell should the two major operations fail (unlocking the encrypted volume and mounting your decrypted root filesystem), but a lot of stuff could (and probably should) be added to make it more robust. There's plenty to read on the internet about init scripts in general, and expanding on this script should be fairly easy. One thing that you should consider is that when <code>mdev</code> populates <code>/dev</code> and <code>switch_root</code> does it's job, the created files will exists even in the new root filesystem, and might cause problems with device nodes not being where they should. If your rootfs' init process starts complaining about devices not being available, try manually populating <code>/dev</code> with the devices you need, and leave mdev out of it.</p>
<h3>Phase 6 - Wrapping it up</h3>
<p>For those who chose to let the kernel build the actual initramfs image from the structure in <code>/usr/src/initramfs</code>, you only have to do the usual bootloader antics to get it deployed, the image is contained in bzImage, as such, you should be set to give your setup a whirl. For the other group, we still have to build the image and make the bootloader pass it to the kernel. Here goes.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #7a0874; font-weight: bold;">cd</span> <span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>src<span style="color: #000000; font-weight: bold;">/</span>initramfs
$ <span style="color: #c20cb9; font-weight: bold;">find</span> . <span style="color: #660033;">-print0</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">cpio</span> <span style="color: #660033;">-ov</span> <span style="color: #660033;">-0</span> <span style="color: #660033;">--format</span>=newc <span style="color: #000000; font-weight: bold;">|</span> \
  <span style="color: #c20cb9; font-weight: bold;">gzip</span> <span style="color: #660033;">-9</span> <span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #000000; font-weight: bold;">/</span>boot<span style="color: #000000; font-weight: bold;">/</span>initramfs.cpio.gz</pre></div></div>

</p>
<p>This creates the initramfs image right in <code>/boot</code>, so make sure it's mounted before you do this. Next up is the bootloader. Most tutorials on the web use <code>grub</code> for this purpose, so I'll do it with lilo. Edit lilo.conf to suit your needs, making it look something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="lilo" style="font-family:monospace;">image = /boot/bzImage
        label = gentoo
        root = /dev/cluebrick/root
        initrd = /boot/initramfs.cpio.gz
        read-only</pre></div></div>

</p>
<h3>Conclusion</h3>
<p>If everything went as it should've, you now have a fully working, secure machine. There's a lot of stuff you could still add to the init script to make it more robust, like a telnet server when something fails, or some fancy echos that give a more verbose and colorful output when booting, but the core should be easy enough to extend upon. Any comments or criticism is welcome, but save me the grammar crud <img src='http://blog.hatsuseno.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hatsuseno.org/index.php/secure-and-safe-computing-on-the-go/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tips and Tricks for console cowboys</title>
		<link>http://blog.hatsuseno.org/index.php/tips-and-tricks-for-console-cowboys/</link>
		<comments>http://blog.hatsuseno.org/index.php/tips-and-tricks-for-console-cowboys/#comments</comments>
		<pubDate>Tue, 11 May 2010 20:38:08 +0000</pubDate>
		<dc:creator>hatsuseno</dc:creator>
				<category><![CDATA[Tips and Tricks]]></category>

		<guid isPermaLink="false">http://blog.hatsuseno.org/?p=182</guid>
		<description><![CDATA[Howdy! Okay, enough horsing around. UNIX command line paradigms are powerful ideas and methods of accomplishing things in a short time. This is my, far from complete, list of tricks I&#8217;ve picked up over the years using Linux &#038; friends. Speeding up tarball download/extract $ wget -O- http://example.org/tarball.tar.gz &#124; tar -xvzf- This little one liner [...]]]></description>
			<content:encoded><![CDATA[<p>Howdy!</p>
<p>Okay, enough horsing around. UNIX command line paradigms are powerful ideas and methods of accomplishing things in a short time. This is my, far from complete, list of tricks I&#8217;ve picked up over the years using Linux &#038; friends.</p>
<h3>Speeding up tarball download/extract</h3>
<p>
<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #c20cb9; font-weight: bold;">wget</span> <span style="color: #660033;">-O-</span> http:<span style="color: #000000; font-weight: bold;">//</span>example.org<span style="color: #000000; font-weight: bold;">/</span>tarball.tar.gz <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">tar</span> <span style="color: #660033;">-xvzf-</span></pre></div></div>

<p>This little one liner has saved time and disk space, basically it forces wget to dump the file you want to download into tar which directly starts extracting it as it comes in. This has the advantage of being one command you can easily type, not having the need to temporarily store the tarball while you download it and then extract the contents (making the extract a in-place operation) and speeding up the total time wasted, either your internet bandwidth or harddrive writing speed will be the bottleneck (most often the latter), but at least you won&#8217;t have to wait for one to finish to start on the other.</p>
<h3>Bulk copy progress indicator</h3>
<p>
<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #c20cb9; font-weight: bold;">tar</span> <span style="color: #660033;">-cf-</span> <span style="color: #000000; font-weight: bold;">/</span>path<span style="color: #000000; font-weight: bold;">/</span>to<span style="color: #000000; font-weight: bold;">/</span><span style="color: #c20cb9; font-weight: bold;">dir</span> <span style="color: #000000; font-weight: bold;">|</span> pv <span style="color: #000000; font-weight: bold;">|</span> \
  <span style="color: #c20cb9; font-weight: bold;">ssh</span> user<span style="color: #000000; font-weight: bold;">@</span>box <span style="color: #ff0000;">'cat &gt; /path/to/archive.tar'</span></pre></div></div>

<p>This on-liner makes a tarball from a source directory, pipes that through the <code>pv</code> (pipe view) utility, which shows throughput speed, progress and ETA if it can determine it, and finally pumps it over the network to a remote box which writes it to a file. Instead of waiting around and wondering when the job will be done, you now at least have some idea how long it&#8217;s going to take.</p>
<p>
<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #c20cb9; font-weight: bold;">tar</span> <span style="color: #660033;">-cf-</span> <span style="color: #000000; font-weight: bold;">/</span>path<span style="color: #000000; font-weight: bold;">/</span>to<span style="color: #000000; font-weight: bold;">/</span><span style="color: #c20cb9; font-weight: bold;">dir</span> <span style="color: #000000; font-weight: bold;">|</span> pv <span style="color: #660033;">-c</span> <span style="color: #660033;">-N</span> <span style="color: #c20cb9; font-weight: bold;">tar</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">gzip</span> <span style="color: #660033;">-c</span> <span style="color: #000000; font-weight: bold;">|</span> \
  pv <span style="color: #660033;">-c</span> <span style="color: #660033;">-N</span> <span style="color: #c20cb9; font-weight: bold;">gzip</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">ssh</span> user<span style="color: #000000; font-weight: bold;">@</span>box <span style="color: #ff0000;">'cat &gt; /path/to/archive.tar.gz'</span></pre></div></div>

<p>This one is even nicer, compressing the output as it goes. <code>pv</code> has a very nice feature, activated by the switch <code>-c</code> which uses cursor positioning escape characters to draw the progress indicator. When you have several <code>pv</code> processes doing this in a pipe-chain (such as the above command) all output is written neatly on screen, without interfering with each others&#8217; updates. Using <code>-N name</code> will cause <code>pv</code> to write that name out before the progress indicator. This is a good thing, because when using the <code>-c</code> switch, there is no telling which <code>pv</code> process will end up on top of the other when drawing the progress bars.
</p>
<h3>netcat, swish army knife of TCP/IP</h3>
<p>
<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">user<span style="color: #000000; font-weight: bold;">@</span>box1 $ pv <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>sda <span style="color: #000000; font-weight: bold;">|</span> lzop <span style="color: #660033;">-c</span> <span style="color: #000000; font-weight: bold;">|</span> nc <span style="color: #660033;">-l</span> <span style="color: #000000;">9876</span>
user<span style="color: #000000; font-weight: bold;">@</span>box2 $ nc box1 <span style="color: #000000;">9876</span> <span style="color: #000000; font-weight: bold;">&gt;</span> box1-sda.lzo</pre></div></div>

<p>This simple set of commands has saved my ass quite a couple of times. It works across networked computers, on one box it let&#8217;s <code>pv</code> take in all the data on a partition (like <code>dd</code> or <code>cat</code> would), prints a progress indicator, compress the who thing with a minimal CPU overhead using <code>lzop</code> and then pipe it to netcat, which is listening for incoming TCP connections on port 9876. After that&#8217;s set up netcat will block until something connects to port 9876. On the second box we do just this and write that to a file. A remote backup which, although not pretty, does the job. Fast. There&#8217;s almost no overhead when using netcat for file transfers like this.</p>
<p>
<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">user<span style="color: #000000; font-weight: bold;">@</span>box1 $ nc <span style="color: #660033;">-e</span> <span style="color: #ff0000;">'/bin/bash'</span> <span style="color: #660033;">-l</span> <span style="color: #660033;">-p</span> <span style="color: #000000;">9876</span>
user<span style="color: #000000; font-weight: bold;">@</span>box2 $ nc box1 <span style="color: #000000;">9876</span></pre></div></div>

<p>Perhaps the nastiest way to get a remote shell on a machine. box1 has netcat listening on port 9876, and when something connects to it netcat simply connects stdin and stdout of whatever process it starts (in this case bash) to the in- and output streams of the connection. On box2, you&#8217;ll be greeted not by your usual command prompt though, a lot of basic stuff gets left behind, but if you ever need a remote shell very very badly, this is one way to do it.</p>
<h3>SSH reverse tunneling</h3>
<p>
<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">user<span style="color: #000000; font-weight: bold;">@</span>firewalledbox $ <span style="color: #c20cb9; font-weight: bold;">ssh</span> <span style="color: #660033;">-R</span> <span style="color: #000000;">1337</span>:localhost:<span style="color: #000000;">22</span> user<span style="color: #000000; font-weight: bold;">@</span>remotebox
user<span style="color: #000000; font-weight: bold;">@</span>remotebox $ <span style="color: #c20cb9; font-weight: bold;">ssh</span> localhost <span style="color: #660033;">-p</span> <span style="color: #000000;">1337</span></pre></div></div>

<p>This one can be a bit tricky to grasp, it certainly took me some time before I got the hang of it. Basically this trick allows you to connect to a firewalled machine without fancy-pants hole-punching or other invasive tactics. The machine behind a firewall logs into a remote PC, and sets up a reverse tunnel back to itself. It binds to <code>remotebox:1337</code>, which in turn can connect to itself on that port to log into the firewalled machine. You can change the string <code>1337:localhost:22</code> to anything you want, as long as you get that the first port number is the one which SSH binds to on the remote box, and the <code>hostname:port</code> combo is the machine you want to connect to, this doesn&#8217;t have to be localhost, it can be any machine accessible to the firewalled box (like a server on the local network that&#8217;s not available from the internet).</p>
<p>I guess that&#8217;s it for now, I&#8217;ll probably come back later for another round with new tricks.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hatsuseno.org/index.php/tips-and-tricks-for-console-cowboys/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom order sorting in PHP</title>
		<link>http://blog.hatsuseno.org/index.php/custom-order-sorting-in-php/</link>
		<comments>http://blog.hatsuseno.org/index.php/custom-order-sorting-in-php/#comments</comments>
		<pubDate>Sun, 02 May 2010 14:46:56 +0000</pubDate>
		<dc:creator>hatsuseno</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[quicksort]]></category>

		<guid isPermaLink="false">http://blog.hatsuseno.org/?p=139</guid>
		<description><![CDATA[Every once in a while you find your self in need of a generic sorting function that orders in a very specific, and non-machine understandable way. Like sorting items from &#8216;one&#8217; to &#8216;four&#8217;. Instead of building a small subset of those kind of sort operations into the language PHP has usort family (short for user-defined [...]]]></description>
			<content:encoded><![CDATA[<p>Every once in a while you find your self in need of a generic sorting function that orders in a very specific, and non-machine understandable way. Like sorting items from &#8216;one&#8217; to &#8216;four&#8217;. Instead of building a small subset of those kind of sort operations into the language PHP has usort family (short for user-defined sort). In the background this sort still works as a <a href="http://en.wikipedia.org/wiki/Quicksort">quicksort</a>, but the developer is tasked with making a function that does the comparison between different elements of the array. It&#8217;s up to him to define whether a value is smaller, equal or bigger than another.</p>
<p>So, keeping the &#8216;one&#8217; to &#8216;four&#8217; example, I present you with a very simple custom sort function.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> customCompare<span style="color: #009900;">&#40;</span><span style="color: #000088;">$a</span><span style="color: #339933;">,</span> <span style="color: #000088;">$b</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">// We flip the array to get the positional indices </span>
  <span style="color: #000088;">$order</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array_flip</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'one'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'two'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'three'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'four'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">// Sanity check, $a and $b must exist in the order array</span>
  <span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$a</span><span style="color: #339933;">,</span> <span style="color: #000088;">$b</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$arg</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">array_key_exists</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$arg</span><span style="color: #339933;">,</span> <span style="color: #000088;">$order</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
      <span style="color: #990000;">trigger_error</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;`<span style="color: #006699; font-weight: bold;">$arg</span>' is not a sortable key&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">// The positions in the order array dictate if $a is bigger</span>
  <span style="color: #666666; font-style: italic;">// than $b, as such we can simply subtract the integers</span>
  <span style="color: #666666; font-style: italic;">// from the flipper order array to get an integer value</span>
  <span style="color: #666666; font-style: italic;">// which is smaller, equal or bigger than 0 depending on</span>
  <span style="color: #666666; font-style: italic;">// $a and $b's relative position in the array.</span>
  <span style="color: #b1b100;">return</span> <span style="color: #000088;">$order</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$a</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">-</span> <span style="color: #000088;">$order</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$b</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// An example array to be sorted</span>
<span style="color: #000088;">$example</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
  <span style="color: #0000ff;">'four'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #cc66cc;">4</span><span style="color: #339933;">,</span>
  <span style="color: #0000ff;">'one'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">,</span>
  <span style="color: #0000ff;">'three'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #cc66cc;">3</span><span style="color: #339933;">,</span>
  <span style="color: #0000ff;">'two'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Do the actual sort</span>
<span style="color: #990000;">uksort</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$example</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'customCompare'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Dump results</span>
<span style="color: #990000;">print_r</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$example</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The dumped array will look like this</p>
<pre>
Array
(
    [one] => 1
    [two] => 2
    [three] => 3
    [four] => 4
)
</pre>
<p>If you, like me, like closures and are running PHP 5.3, we can make the compare function a lot nicer and easier to maintain.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> createSorter<span style="color: #009900;">&#40;</span><span style="color: #000088;">$order</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000088;">$order</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array_flip</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$order</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #b1b100;">return</span> <span style="color: #000000; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$a</span><span style="color: #339933;">,</span> <span style="color: #000088;">$b</span><span style="color: #009900;">&#41;</span> use <span style="color: #009900;">&#40;</span><span style="color: #000088;">$order</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// Sanity check, again</span>
    <span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$a</span><span style="color: #339933;">,</span> <span style="color: #000088;">$b</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$arg</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">array_key_exists</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$arg</span><span style="color: #339933;">,</span> <span style="color: #000088;">$order</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #990000;">trigger_error</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;`<span style="color: #006699; font-weight: bold;">$arg</span>' is not a sortable key&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #000088;">$order</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$a</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">-</span> <span style="color: #000088;">$order</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$b</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Sort array $array in the 'one' to 'four' order.</span>
<span style="color: #990000;">uksort</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$array</span><span style="color: #339933;">,</span> createSorter<span style="color: #009900;">&#40;</span>
  <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'one'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'two'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'three'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'four'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://blog.hatsuseno.org/index.php/custom-order-sorting-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Gentoo, awesome and themes</title>
		<link>http://blog.hatsuseno.org/index.php/gentoo-awesome-and-themes/</link>
		<comments>http://blog.hatsuseno.org/index.php/gentoo-awesome-and-themes/#comments</comments>
		<pubDate>Thu, 25 Feb 2010 03:53:23 +0000</pubDate>
		<dc:creator>hatsuseno</dc:creator>
				<category><![CDATA[Gentoo errors]]></category>
		<category><![CDATA[awesome]]></category>
		<category><![CDATA[custom-scripts]]></category>
		<category><![CDATA[gentoo]]></category>
		<category><![CDATA[themes]]></category>
		<category><![CDATA[wallpaper]]></category>

		<guid isPermaLink="false">http://blog.hatsuseno.org/?p=126</guid>
		<description><![CDATA[I&#8217;ve been a Gentoo user since forever, and for some time I&#8217;ve been using awesome for a window manager instead of the desktop environments Gnome or KDE. One thing I never got around to change was the wallpaper. My terminals are pseudo-transparent, and I never disliked the default &#8216;awesome&#8217; wallpaper. @ZackLeonhart&#8216;s bitching and moaning changed [...]]]></description>
			<content:encoded><![CDATA[<p><img alt="" src="http://hammerfest.hatsuseno.org/~crashmatrix/awesome_logo.png" title="Awesome logo" class="alignleft" width="64" height="64" />
<p>I&#8217;ve been a Gentoo user since forever, and for some time I&#8217;ve been using awesome for a window manager instead of the desktop environments Gnome or KDE. One thing I never got around to change was the wallpaper. My terminals are pseudo-transparent, and I never disliked the default &#8216;awesome&#8217; wallpaper. <a href='http://twitter.com/ZackLeonhart'>@ZackLeonhart</a>&#8216;s bitching and moaning changed that.</p>
<p>Turns out that aside from editing the system-wide theme script, by default located in <code>/usr/share/awesome/themes/*</code> (which I consider to be a BadThink&#8482;), there is no straight forward way of doing it nicely in the Gentoo provided default setup. So here&#8217;s what you do.</p>
<p><ol>
<li>Create yourself a lua.rc in <code>${HOME}/.config/awesome</code><br /><code>$ cp /etc/xdg/awesome/rc.lua ~/.config/awesome</code></li>
<li>Recursively copy all themes from the system-wide dirs to your local configdir.<br /><code>$ cp -rvf /usr/share/awesome/themes ~/.config/awesome</code></li>
<li>In your copy of lua.rc you will find a variable called <code>theme_path</code>, change it to <code>theme_path = os.getenv("HOME") .. "/.config/awesome/themes/path/to/theme.lua"</code></li>
<li>Edit the variable <code>theme.wallpaper_cmd</code> to contain the string <code>"eval `cat ~/.fehbg`"</code></li>
<li>Choose a wallpaper you like, execute <code>$ feh --bg-scale /path/to/wallpaper.jpg</code></li>
</ol>
<p>And you&#8217;re done! If you want to change your wallpaper, simply use <code>feh</code> again with a random other file, and make sure the file is readable when awesome is starting up, and it&#8217;ll set it up automagically. Basically, awesome&#8217;s &#8216;beautiful&#8217; library takes your typed out command and executes that in order to set the wallpaper, feh has a convenient way of storing the default wallpaper by simply dumping the command that was used to set it up in the first place in a configuration file in your home directory, hence the <code>eval `cat whatever`</code> trick.
</p>
<div class="wp-caption alignnone" style="width: 450px"><a href='http://hammerfest.hatsuseno.org/~crashmatrix/screencap_250210.jpg'><img alt="Screenshot of my new wallpaper in Awesome" src="http://hammerfest.hatsuseno.org/~crashmatrix/screencap_250210.jpg" title="Screenshot" width="440" /></a><p class="wp-caption-text">Screenshot of my new wallpaper in Awesome</p></div>
<p>P.S.: Don&#8217;t think you can leave out the call to os.getenv() in step 3, awesome doesn&#8217;t expand the tilde (&#8216;~&#8217;), so the path it&#8217;ll try to access will be invalid.</p>
<p>P.P.S.: This is more of a note for me, in case I ever lose my epic new wallpaper. It can be found <a href='http://upload.wikimedia.org/wikipedia/commons/e/ec/LodalenPano.jpg'>here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hatsuseno.org/index.php/gentoo-awesome-and-themes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>building a programming language, part 2</title>
		<link>http://blog.hatsuseno.org/index.php/building-a-programming-language-part-2/</link>
		<comments>http://blog.hatsuseno.org/index.php/building-a-programming-language-part-2/#comments</comments>
		<pubDate>Fri, 04 Sep 2009 13:02:30 +0000</pubDate>
		<dc:creator>hatsuseno</dc:creator>
				<category><![CDATA['cwx' project]]></category>
		<category><![CDATA[cwx]]></category>
		<category><![CDATA[programming languages]]></category>
		<category><![CDATA[syntax]]></category>

		<guid isPermaLink="false">http://blog.hatsuseno.org/?p=90</guid>
		<description><![CDATA[Following up on my original post, this time, version 1.0 &#8220;final&#8221; for the basic structure and syntax of the language, still unnamed, although someone suggested I should integrate &#8216;two&#8217; and &#8216;hash&#8217; in there. Oh well. The spirit remains, but there have been a few changes in the language as a whole. The entire codeblock-as-type feature [...]]]></description>
			<content:encoded><![CDATA[<p>Following up on my original post, this time, version 1.0 &#8220;final&#8221; for the basic structure and syntax of the language, still unnamed, although someone suggested I should integrate &#8216;two&#8217; and &#8216;hash&#8217; in there. Oh well.</p>
<p>The spirit remains, but there have been a few changes in the language as a whole. The entire codeblock-as-type feature has been dropped until it can be further perfected syntactically, and I&#8217;ve taken a more pragmatic approach in general, things need to get done after all.</p>
<p><h2>Built-in types</h2>
<dl>
<dt><code>boolean</code></dt>
<dd>A boolean type, true or false.</dd>
<p></p>
<dt><code>integer</code></dt>
<dd>Pretty obvious, integer numbers, 64bit signed.</dd>
<p></p>
<dt><code>float</code></dt>
<dd>Less obvious, implemented as a C-style double.</dd>
<p></p>
<dt><code>string</code></dt>
<dd>A string type, most types can be cast to this.</dd>
<p></p>
<dt><code>list</code></dt>
<dd>Simple, LISP-style, linked-list.</dd>
<p></p>
<dt><code>array</code></dt>
<dd>Variable-length, numerically indexed arrays.</dd>
<p></p>
<dt><code>hash</code></dt>
<dd>Variable-length hashmap, /[[:alnum:]_]+?/ keys.</dd>
<p></p>
<dt><code>function</code></dt>
<dd>Standard first-class citizen functions.</dd>
<p></p>
<dt><code>class</code></dt>
<dd>First-class citizen classes.</dd>
<p></p>
<dt><code>dynamic</code></dt>
<dd>Special untyped variable, can contain *any* type value at any time, default type</dd>
<p>
</ul>
<h3>Examples of primitive types</h3>

<div class="wp_syntax"><div class="code"><pre class="cwx" style="font-family:monospace;">boolean b = true;
integer x = 5;
float j = 5.4E-4;
string s = 'test string';
list l = list(1, 2, 3, 4, 5);
array m = array('a', 'b', 'c', 'd', 'e');
hash z = hash(a: 1, b: 2, c: 3, d: 4, test_key: 666);
&nbsp;
function f = function(a, b, c, d) uses (m) {
  sum(a, b, c, d, m[1]);
};
&nbsp;
class c = class(
  private integer attr_name: 5,
  public function constructor myConstructor: function() {
    this.attr_name *= 10;
  }
);
dynamic y = 20;
p = 20;</pre></div></div>

<p>A few sidenotes;</p>
<ul>
<li>Keys in hash-maps are unquoted, because they are properly constrained.</li>
<li>Functions are <i>always</i> closures, but require explicit declaration of the enclosed variables.</li>
<li>Classes syntactically resemble hash-maps, but have modifier keywords, like private, protected, constructor and destructor.</li>
<li>The variables y and p are for all intents and purposes identical in content and type, untyped variables *are* dynamic variables.</li>
<li>All composite types (like lists, arrays and classes) have a constructor-function, which is an actual function that can be called with eval()-esque intent.</li>
</ul>
<p><h2>In-depth look into the composite types</h2>
<h3>Lists</h3>
<p>Lists are singly-linked lists, and the functions <code>list()</code>, <code>first()</code> and <code>rest()</code> are the primitive operators on lists.</p>

<div class="wp_syntax"><div class="code"><pre class="cwx" style="font-family:monospace;">x = list(1, 2, 3, 4, 5);
first(x);
  =&gt; 1
rest(x);
  =&gt; list(3, 4, 5)</pre></div></div>

<p><code>first()</code> and <code>rest()</code> are modifying functions, they pop from the list whatever they return, so the list <code>x</code> is now a list with the value <code>(2)</code>. Trying to pop from an empty array results in a &#8216;null&#8217; value being returned. While-loops can be constructed around this, but lists are iteratable, so the built-in <code>foreach()</code> will do just fine.</p>

<div class="wp_syntax"><div class="code"><pre class="cwx" style="font-family:monospace;">foreach(list(1, 2, 3, 4, 5) as li) { ... }</pre></div></div>

<h3>Arrays</h3>
<p>Arrays are numerically indexed, sparse datastructures. So you can have a value at index 1 and at 5, nothing stops you from breaking sequence. By default an array can contain values of any type (so it&#8217;s implicitly an array of dynamic values) but this behaviour can be changed easily.</p>

<div class="wp_syntax"><div class="code"><pre class="cwx" style="font-family:monospace;">integer array a = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
a[9] = 10;
a[1] = null;
a;
  =&gt; array(1, 3, 4, 5, 6, 7, 8, 9, 10);
&nbsp;
a[1];
  =&gt; null;</pre></div></div>

<p>Array <code>a</code> is explicitly an array of integer values, and so cannot be assigned anything else. Doing so will result in a run-time error. (Type-checking is always done in run-time).<br />
Unsetting array indecis is done by setting the value to <code>null</code>, as you can see when evaluating the array, index 1 does not exist. Evaluating a non-existant index of an array produces <code>null</code> as well. There is no difference between non-existing indecis and values set to <code>null</code>.</p>
<h3>Hash-maps</h3>
<p>Similar to arrays in syntax to arrays, maps are variable in length, and implicitly of type &#8216;dynamic&#8217;. This can be changed in the same way it can for arrays.</p>

<div class="wp_syntax"><div class="code"><pre class="cwx" style="font-family:monospace;">integer hash m = hash(a: 1, b: 2, c: 3, d: 4);
x = map(function (val, key) { ... }, m);</pre></div></div>

<p>Introducing the function <code>map</code>, although it could be easily constructed using lower-level operations, a high-order function provided by the language runtime.</p>
<h3>Functions</h3>
<p>Being first-class citizens, functions get assigned to variables, and nothing else. All functions are closures, but require a list of variables to enclose. This is to keep GC simpler and it requires the developer think about what he or she wants to enclose.</p>

<div class="wp_syntax"><div class="code"><pre class="cwx" style="font-family:monospace;">square = function(x) { return x^2; } // f(x) = x^2;
&nbsp;
deriv = function(f, dx) {
  return function(x) uses (f, dx) {
    return (f(x + dx) - f(x)) / dx
  };
};
&nbsp;
d_square = deriv(square, 0.001); // Approximates f'(x) = 2x;</pre></div></div>

<p>Provided is an example demonstrating the use of this language in creating a function that produces a function approximating the derivative of another function.</p>
<h3>Classes</h3>
<p>Classes are a bit different from the usual OOP approach, and are halfway between normal OOP classes and prototype-based languages. Classes are first-class citizens, and can be modified in run-time. Immediately the usual implied trust that a class will remain the same during it&#8217;s entire lifetime no longer exists, although there are methods of regaining that trust.</p>

<div class="wp_syntax"><div class="code"><pre class="cwx" style="font-family:monospace;">p = class(
  private integer x,
  private integer y,
&nbsp;
  public constructor function myConstructor: function() {
    this.x = 5; this.y = 5;
  },
&nbsp;
  public function toString() {
    return &quot;x: &quot; ~ x ~ &quot;, y: &quot; ~ y;
  }
);
&nbsp;
object = new p;
p.toString();
  =&gt; string &quot;x: 5, y: 5&quot;</pre></div></div>

<p>Looks reasonable enough, create a class, make an object, execute method, the usual. Inheritance is also mostly the same as PHP and Java classes.</p>

<div class="wp_syntax"><div class="code"><pre class="cwx" style="font-family:monospace;">k = class() extends p; // Empty class extending class p.
&nbsp;
z = interface(public function toList);
t = class(
  public function toList: function() {
    return list(this.x, this.y);
  }
) extends p implements z;</pre></div></div>

<p><code>t</code> is a class implementing interface <code>z</code> and extending class <code>p</code>. It&#8217;s a bit ugly with the modifiers at the bottom, but it works fine. But because classes are also first-class citizens, and not the global structures we know from Java and C++ for example, you can hide classes in context, effectively using the code-scope mechanism to implement a system similar to namespaces in that it provides some classes can be directly accessed from the entire project, and some are internal to a function, a class or any other scope-seperating block.</p>
<p>The role/mixin/trait feature described in the first post about this programming language has been dropped until I get my head around it well enough to see the implications of adding it.
</p>
<p>
That about sums it up for the built-in types for version 1.0 of the language specification, though I&#8217;m sure there are flaws in here that need resolving before it can be implemented properly. Critisism, as always, is appreciated, save for spelling errors and such, I am already aware my English skill needs upgrading <img src='http://blog.hatsuseno.org/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  For now, I can start working on the grammar/syntacical parser of the interpreter. After that comes a symbol table and after that I&#8217;ll be sure to post an update here.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hatsuseno.org/index.php/building-a-programming-language-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>building a programming language, part 1</title>
		<link>http://blog.hatsuseno.org/index.php/building-a-programming-language-part-1/</link>
		<comments>http://blog.hatsuseno.org/index.php/building-a-programming-language-part-1/#comments</comments>
		<pubDate>Mon, 29 Jun 2009 11:27:32 +0000</pubDate>
		<dc:creator>hatsuseno</dc:creator>
				<category><![CDATA['cwx' project]]></category>
		<category><![CDATA[cwx]]></category>
		<category><![CDATA[programming languages]]></category>
		<category><![CDATA[syntax]]></category>

		<guid isPermaLink="false">http://blog.hatsuseno.org/?p=48</guid>
		<description><![CDATA[As a follow-up from a school assignment (where I had to build a full parser for a very simple language) I decided to construct a language of my own, just for fun. Orignally, I was a C programmer, my part-time job entails PHP, and I have a fondness for languages like Scheme, Lua and Javascript. [...]]]></description>
			<content:encoded><![CDATA[<p>As a follow-up from a school assignment (where I had to build a full parser for a very simple language) I decided to construct a language of my own, just for fun.</p>
<p>Orignally, I was a C programmer, my part-time job entails PHP, and I have a fondness for languages like Scheme, Lua and Javascript. Drawing inspiration from all these language, I have (for now) decided on a syntax like this;</p>
<p><h2>Variables</h2>

<div class="wp_syntax"><div class="code"><pre class="cwx" style="font-family:monospace;">int x = 42;
dynamic j = 'x';
y = 'x';</pre></div></div>

<p><code>j</code> and <code>y</code> are both of the same type, &#8216;<code>dynamic</code>&#8216;, in the case of <code>y</code>, this is implied. Dynamic variables can contain any type of content, others are type strict.
</p>
<p><h2>Built-in types</h2>

<div class="wp_syntax"><div class="code"><pre class="cwx" style="font-family:monospace;">int x = 42;
float j = 4.5;
string s = &quot;hello world&quot;;
array l = (1, 2, 3, 4, 'a', 'b', 'c', 'd');
map m = [a: 1, b: 2, c: 3, d: 4];
code c = { a = 5; a++; doSomething(a); };
function f = function() {};
class c = class [];</pre></div></div>

<p>Statements are first class citizens of the language, albeit not for the right reasons yet.
</p>
<p><h2>Functions</h2>

<div class="wp_syntax"><div class="code"><pre class="cwx" style="font-family:monospace;">string s = &quot;Amount &quot;;
&nbsp;
f = function(int x, function y, z) uses (s) {
  x += y(z);
  return s ~ x;
}</pre></div></div>

<p>This here example shows literal strings as a language construct, and first class citizenship of functions. All functions are closures, but require (<a href="http://wiki.php.net/rfc/closures">like</a> in PHP) the desired variables in the closure to be explicitly summed up. String concatenation is done through the &#8216;<code>~</code>&#8216; operator.
</p>
<p><h2>Classes</h2>

<div class="wp_syntax"><div class="code"><pre class="cwx" style="font-family:monospace;">surface = class [
  private x : 0,
  private int y,
&nbsp;
  public constructor makeNew : function {
    this-&gt;x = 5;
    this-&gt;y = 7;
  },
]</pre></div></div>

<p>Classes, in my opinion, are more like hash-tables than functions, as such, the syntax reflects this. &#8216;<code>constructor</code>&#8216; is a special keyword that indicates that the method defined is the constructor of said object. As shown, the name of this method can be anything. I haven&#8217;t quite decided on overloading and it&#8217;s implications, so I&#8217;ve left it at that. As with functions, classes are first class citizens of the language. That means they can be assigned to variables, copied and have operations performed on them. An example:</p>

<div class="wp_syntax"><div class="code"><pre class="cwx" style="font-family:monospace;">// Class with two attributes, implied public, of undefined type
a = class [ x, y ];
&nbsp;
// 'b' is an empty class that extends 'a'
b = class [] extends a; 
&nbsp;
c = interface [ public int x, public function getName ];
d = class []; // 'd' is an empty class
d implements c; // which now implements 'c'</pre></div></div>

<p>Operators like &#8216;<code>extends</code>&#8216; and &#8216;<code>implements</code>&#8216; can be applied to a class during it&#8217;s entire lifetime. Instances of those classes made before the operations do not change with them.</p>

<div class="wp_syntax"><div class="code"><pre class="cwx" style="font-family:monospace;">/* Classes can be extended with anonymous classes,
 * same for interfaces.
 * Not really useful, but syntactically it's valid
 * sidenote: newlines are regarded as whitespace */
a = class [ x, y ] extends class [ 
     function getName() { return 'name'; }, int c ]
     implements interface [ function getType ];
&nbsp;
x = class [ function getThing(a, b) { return a + b; } ];
&nbsp;
a has x;     // 'a' now has a method 'getThing'
b extends a; // but 'b' does not.</pre></div></div>

<p>A trick I picked up from Perl 6, class-traits. I believe this will be very beneficial in bridging traditional classes and prototype-based languages by allowing class extending without adding to the inheritance chain.
</p>
<p><h2>Operators</h2>

<div class="wp_syntax"><div class="code"><pre class="cwx" style="font-family:monospace;">/* All common symbolic operators (+, -, &amp;&amp;, extends) have
 * function-like counterparts. Internally, the symbolic ops
 * are just syntactic sugar for the function-like ops */
print(2 + 2);
print(add(2, 2));
&nbsp;
print(true &amp;&amp; false);
print(and(true, false));
&nbsp;
// Variable amount of parameters when it makes sense
print(and(true, true, true, true, true, true, false));
print(subtract(40, 3, 4, 6, 2, 13));</pre></div></div>

<p>But also</p>

<div class="wp_syntax"><div class="code"><pre class="cwx" style="font-family:monospace;">/* Symbol quoting stolen from Lisp,
 * symbols a, b and c are not evaluated */
function a = _function(('a, 'b, 'c), (x, y, z), {
  return add(a, b, c) * subtract(x, y, z); });</pre></div></div>

<p>Which, as you can see is exceedingly ugly. Neither concise nor elegant, the syntax has grown to represent what I want to avoid in general. This either means I will need to get a clue as to resolving this syntactically, or I will have to remove the operators-as-functions feature from the language, but I haven&#8217;t decided. The entire concept of code as a first class citizen of the language (like in Smalltalk) was created out of necessity to make this work.
</p>
<p><h2>Conclusion (for now, anyway)</h2>
<p>Although I have started with a parser for the basic language, stuff like the operators-as-functions and first class citizenship of codeblocks need to be resolved to add to the whole of the language instead of looking like I just clobbered it all together. Also, I still need to name it&#8230; &#8216;project cwx&#8217; sounds increasingly cheezy.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hatsuseno.org/index.php/building-a-programming-language-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP and XML manipulation</title>
		<link>http://blog.hatsuseno.org/index.php/php-and-xml-manipulation/</link>
		<comments>http://blog.hatsuseno.org/index.php/php-and-xml-manipulation/#comments</comments>
		<pubDate>Thu, 28 May 2009 23:19:30 +0000</pubDate>
		<dc:creator>hatsuseno</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[SimpleXML]]></category>

		<guid isPermaLink="false">http://blog.hatsuseno.org/?p=32</guid>
		<description><![CDATA[Recently I&#8217;ve been fiddeling around with an old project of mine, and decided to extend it into a full-blown framework, just for kicks. Born from GDO, a ORM layer for PHP, it&#8217;s supposed to serve no real purpose but personal gratification. Anyway, parallel with the framework I am building a website to showcase it. I [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I&#8217;ve been fiddeling around with an old project of mine, and decided to extend it into a full-blown framework, just for kicks. Born from <acronym title='Generic Database Object'>GDO</acronym>, a <acronym title='Object-relational mapping'>ORM</acronym> layer for PHP, it&#8217;s supposed to serve no real purpose but personal gratification.</p>
<p>Anyway, parallel with the framework I am building a website to showcase it. I also decided that in this specific case all the HTML documents should be built from either PHPs DOM or SimpleXML libraries, I personally dislike having HTML strewn across the project, so I&#8217;ve seperated structures like forms and tables into classes and the idea is that I can simply append them to the current page at a specific node and it&#8217;ll render the HTML when everything is added. </p>
<h3>The problem</h3>
<p>Here in lies the problem, PHPs XML libraries (at least the ones that I tried) require you to drag the top node to which you want to append whatever around in all helper classes and such, allow me to demonstrate.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000088;">$document</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> DOMDocument<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$table</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> DOMElement<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'table'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$row</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> DOMElement<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'tr'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$row</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">appendChild</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> DOMElement<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'td'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'test element'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$table</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">appendChild</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$row</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$document</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">appendChild</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$table</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>One would expect this all to work out fine and produce the following XML document;</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">'1.0'</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">'utf-8'</span> <span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;table<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;tr<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;td<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>test element<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/td<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;/tr<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;/table<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>In fact, it won&#8217;t. It won&#8217;t even run. PHP bails out during run time with the error &#8220;<code>DOMException: No Modification Allowed Error</code>&#8220;. This is because every <code>DOMElement</code> object not created with <a href='http://php.net/manual/en/domdocument.createelement.php'><code>DOMDocument::createElement()</code></a> is by default <i>read-only</i>, as you can read in the description of <a href='http://php.net/manual/en/domelement.construct.php'><code>DOMDocument::__construct()</code></a>.</p>
<p>Besides begging the PHP developers to make every <code>DOMElement</code> not read-only on construction, the obvious solution would be to add the <code>DOMElement</code> in question to the <code>DOMDocument</code> and continue building from there, but that&#8217;s the problem. It seems counter-intuitive to pass the <code>DOMElement</code> or <code>DOMDocument</code> that you want to append your seperate structure to to every constructor of every XML producing class (or via normal methods of course).</p>
<p>I&#8217;ve taken the literal example of PHPs DOM classes, but I&#8217;ve tested SimpleXML as well, which provides even less flexibilty regarding node reuse and other fancy stuff one could want to do with XML documents.</p>
<h3>Workarounds</h3>
<p>There are several solutions to this problem, to name a few:</p>
<ul>
<li>Create a singleton class that holds one instance of <code>DOMDocument</code>, and use a wrapper method somewhere to either get a valid <code>DOMElement</code></li>
<li>Have all classes that produce XML nodes use a fake <code>DOMDocument</code>, and then use <a href='http://php.net/manual/en/domdocument.importnode.php'><code>DOMDocument::importNode()</code></a> at the return-point to import the nodes (very inefficient, especially when using a deep-copy).</li>
<li>Have the classes that produce XML nodes return nested arrays containing all name -> content relations of the nodes and run through them when it&#8217;s sensible to do so.</li>
</ul>
<p>I&#8217;ll leave it as an exercise to the reader to pick out the best method. I haven&#8217;t found a solution yet, but I hope to contact the DOM XML module maintainer and discuss this with him/her.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hatsuseno.org/index.php/php-and-xml-manipulation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

