July 29, 2012

For the Love of Coffee, Gadgets, and Python

Most geeks are familiar with the RasberryPi Project that set out to make a tiny, hackable, and amazingly capable PC for around $25.  I've been following it with great interest.

I have to say that I was really tickled when I came across the project blog for MoccaPi .  He's designing a controller to let him remotely start and stop his coffee maker via Telnet.  The coolest part for me is the use of Miniboa for the device's server.

Miniboa ... on a RasberryPi ... making coffee.  How awesome is that?

March 2, 2012

Desktop Linux

Linux has been my primary OS for about eight years. I am very fond of it and have often made the analogy that sitting down to a Windows box feels as clumsy as having your thumbs removed.

I used Redhat, then Fedora, then Ubuntu. It really annoyed me when they hid the kernel boot messages to be more noob friendly or stylish or whatever. My Linux boxes are workstations damn it; show me the bogomips.

Then Ubuntu gets stupid. Shuttleworth decides we need windows controls on the wrong side to prepare us for ... something. So I spend a year feeling like an American driving in Britain when using Linux and a Brit driving in the US when using Windows.

And that something turns out to be Unity.

And Unity sucks.

And my escape route is gone because my beloved Gnome had become Gnome 3 aka Gnome Shell aka Hunt the Wumpus but I give it a shot for a few weeks because it has the wonderful quality of not being Unity until it strikes me, this sucks too. So I spend an entire weekend trying different distros -- then going back to Ubuntu. Then spending the next weekend forcing XFCE into dressing up as Gnome 2. Which was close but what a weird the-opposite-of-forward step to make?

Pretty-please someone fork Gnome 2 and save the Linux desktop.

Remove the "close window?" prompt from Gnome-Terminal

$ gconftool-2 --type bool --set /apps/gnome-terminal/global/confirm_window_close "false"


February 26, 2012

The Web Client

Last weekend I got my WebSocket server for NetBoa working again (yay).

This weekend I've been laying out the HTML5 and CSS for the browser side. At the moment it looks like this;

It seems obvious now, but it felt like an epiphany when I realized that the project only required a single HTML page. Everything from the login screen forward will be elements dynamically create via Javascript (using the excellent JQuery lib) talking the server over a WebSocket. Chrome will happily maintain an open WebSocket for days with no activity (I tested it).

In John Gardner's book, Grendel, a dragon offers up the advice 'alternatives exclude'. I'm wrestling with some UI decisions -- screen dimensions vs. info glut. In the shot above, the left panel is somewhat like the main viewer from Star Trek;

When the right is like a console;
Originally, I had three columns where the far left one containing a kind of galactic IRC. But that was just too much.

I'm still trying to decide on a messaging protocol. JSON is great for interfacing with Javascript in the browser but that's precisely where I don't need speed. Given the short life of these message packets it seems rather wasteful to include an extra library just to generate Python objects to be cast into JSON strings a picosecond later. I'm 90% sure that I'll go with text commands and an option to send snippets of HTML.

February 20, 2012

Unpacking WebSocket Frames Cont.

Using WireShark, I captured some frames between my browser and WebSocket.org's Echo Server. This gave me some data to experiment with without needing a living server.

I mentioned that the protocol in version 13 was very different. Previously, you bookended your packets with \x00 and \xFF and shoved them down the wire. RFC 6455 adopted a more formal framing that includes op codes for the frame type (string vs binary && ping vs pong), a continuation flag, and three different data structures for describing payload size. Additionally, payloads from the Client to the Server are XOR'ed with a random 32 bit mask. This mask is included in the client frame. Frames from the Server to Client are sent in the clear. Plus some reserved fields.

Yes, it does seem a touch fiddly.

Since I'll own both ends of the wire, I should be fine with a server that only uses 'final fragment' frames (no need for messages to span data packets) using text frames. Most likely JSON. I don't plan to support the previous WS drafts since browser updates are darn near seamless today.

The output of the previous code is:

Final Frame: True
Masked: True
Opcode: 1
Payload Length: 28
Payload: Rock it with HTML5 WebSocket

Final Frame: True
Masked: False
Opcode: 1
Payload Length: 28
Payload: Rock it with HTML5 WebSocket

Final Frame: True
Masked: True
Opcode: 1
Payload Length: 165
Payload: This is a very long message that is longer than 125 bytes so it will be offet with a 16 bit extended payload length and therefore payload len should be equal to 126.

Final Frame: True
Masked: False
Opcode: 1
Payload Length: 165
Payload: This is a very long message that is longer than 125 bytes so it will be offet with a 16 bit extended payload length and therefore payload len should be equal to 126.

Unpacking a WebSocket Frame

I'm going to put my comments in the next post because Blogger likes to mangle my code snippets if I try to edit something...
#!/usr/bin/env python

import struct
import array

## Frames with a 7 bit payload length



## Frames with a 16 bit payload length

CLIENT16 = (

SERVER16 = (

def unpack_frame(data):
frame = {}
byte1, byte2 = struct.unpack_from('!BB', data)
frame['fin'] = (byte1 >> 7) & 1
frame['opcode'] = byte1 & 0xf
masked = (byte2 >> 7) & 1
frame['masked'] = masked
mask_offset = 4 if masked else 0
payload_hint = byte2 & 0x7f
if payload_hint < 126:
payload_offset = 2
payload_length = payload_hint
elif payload_hint == 126:
payload_offset = 4
payload_length = struct.unpack_from('!H',data,2)[0]
elif payload_hint == 127:
payload_offset = 8
payload_length = struct.unpack_from('!Q',data,2)[0]
frame['length'] = payload_length
payload = array.array('B')
payload.fromstring(data[payload_offset + mask_offset:])
if masked:
mask_bytes = struct.unpack_from('!BBBB',data,payload_offset)
for i in range(len(payload)):
payload[i] ^= mask_bytes[i % 4]
frame['payload'] = payload.tostring()
return frame

if __name__ == '__main__':

frame = unpack_frame(CLIENT7)
print '\nFinal Frame:', bool(frame['fin'])
print 'Masked:', bool(frame['masked'])
print 'Opcode:', frame['opcode']
print 'Payload Length:', frame['length']
print 'Payload:', frame['payload']

frame = unpack_frame(SERVER7)
print '\nFinal Frame:', bool(frame['fin'])
print 'Masked:', bool(frame['masked'])
print 'Opcode:', frame['opcode']
print 'Payload Length:', frame['length']
print 'Payload:', frame['payload']

frame = unpack_frame(CLIENT16)
print '\nFinal Frame:', bool(frame['fin'])
print 'Masked:', bool(frame['masked'])
print 'Opcode:', frame['opcode']
print 'Payload Length:', frame['length']
print 'Payload:', frame['payload']

frame = unpack_frame(SERVER16)
print '\nFinal Frame:', bool(frame['fin'])
print 'Masked:', bool(frame['masked'])
print 'Opcode:', frame['opcode']
print 'Payload Length:', frame['length']
print 'Payload:', frame['payload']

February 19, 2012

WebSocket RFC 6455 Handshake

I think I got the request/response bit figured out (it was actually simpler than the draft 76 method). This is my test using headers from the RFC document:

from hashlib import sha1
from base64 import b64encode

WS13_GUID = b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'

b'GET /chat HTTP/1.1\r\n'
b'Host: server.example.com\r\n'
b'Upgrade: websocket\r\n'
b'Connection: Upgrade\r\n'
b'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n'
b'Origin: http://example.com\r\n'
b'Sec-WebSocket-Protocol: chat, superchat\r\n'
b'Sec-WebSocket-Version: 13\r\n'

b'HTTP/1.1 101 Switching Protocols\r\n'
b'Upgrade: websocket\r\n'
b'Connection: Upgrade\r\n'
b'Sec-WebSocket-Accept: {}\r\n'
b'Sec-WebSocket-Protocol: chat\r\n'


def parse_request(request):
req = {}
lines = request.split(b'\r\n')
line = lines.pop(0)
items = line.split(b'\x20',2)
if len(items) != 3:
raise BaseException('Malformed WebSocket Request Method.')
req[b'method'] = items[0]
req[b'request_uri'] = items[1]
req[b'http_version'] = items[2]
for line in lines:
if line:
parts = line.split(b':\x20', 1)
req[parts[0].lower()] = parts[1]
return req

if __name__ == '__main__':
req = parse_request(REQUEST)
salted_key = req[b'sec-websocket-key'] + WS13_GUID
sec_ws_accept = b64encode(sha1(salted_key).digest())
assert(sec_ws_accept == CORRECT_ACCEPT)
print RESPONSE.format(sec_ws_accept)

Step two is to get the VERY DIFFERENT message protocol working.


Naturally, the Overlords of the Internet have obsoleted my WebSocket code for the third time. Hopefully things will settle down now the current draft has been submitted as a proposed standard (one step away from an adopted standard).

Pointing my browser (Chromium) at http://websocketstest.com tells me that it's ready for RFC 6455, so I guess I need to get coding.

February 18, 2012


Known to use transmat beams to take brains directly from crewfolk skulls.

Failure is an Option

This is the icon for a dead player

February 17, 2012

Character Work

I have a notion of how I'd like the chat windows to flow using character portraits. Player and crew would appear left of chat boxes and encountered NPCs to the right. I suspect I'm channeling some Japanese RPG.
This is a Kthogin -- a Lovecraftian inspired hostile. I'm leaning towards giving each race a unique color for easy recognition.

February 12, 2012

Thoughts on Serialization

The problem domain is short and sweet;
  1. We need to write game data.
  2. We need to read game data.
The only real snag is, being single threaded, we need these operations to block as little as possible -- as in thousandths of a second. I've even toyed with the idea of reading everything at server start and only performing writes during execution. That would cut our blocking problem in half but removes our ability to modify data externally.

The model in my head calls for very little of the R in RDBMS. Heck, MUDs have managed very well for decades using flat files on systems with less processing power than your dishwasher.

Lastly, given that this hobby-coding, I have the luxury of asking, 'is the solution fun?' Let's set a couple goals;
  1. I don't want a crash to lose the overall state of the game -- which precludes saving writes for an extended period, or even worse, until server shutdown.
  2. Simple to install. Freely available software that does not require a DBA to manage.
  3. Simple to operate. No fretting dirty caches, scheduled housekeeping , etc.
  4. I would prefer back-ups and restores to be file copies. Tar'ing a directory or two is fine.
  5. Some external method to futz with the data while the game is running.
Flat files are certainly doable (and made crazy easy with Python's Pickle module). They meet goals #2, #3, and #4 but I cringe at the amount of runtime file-io needed to cover goal #1 and supporting goal #5 means we have to perform constant reads as well (plus some form of file-locking mechanism). Ick.

A lightweight dbms like SQLite would work except for goal #3. Wrapping Python CRUD in SQL statements is soul-destroying tedious. Yeah, I could tap a ORM like SQLAlchemy but let's look at that new sexy, NoSQL...

When I was a kid, one Christmas I got this electronics kit with 150 projects. It was awesome. You could build things like a crystal radio, lie detector, and light activated room alarm.

Python holds that same appeal for me. It's a big toy. Another one I've found is Redis -- a dead simple NoSQL data store. The distinguishing feature is all data is held in-memory which makes it wicked fast.

I'll admit, when I first read that it holds everything is RAM it struck me as rather pointless. I mean, wasn't I already doing that in my program? And who wants to hold everything in memory whether you need it or not?

Having played with it, the utility and genius starts to shine through. Redis has a clever system of serializing to a file based on the frequency of updates and you can copy this file at any moment without fear of corrupting it. The author also provides a really nice CLI tool with history and auto-complete similar to a Linux terminal.

We're pushing goal #2 a bit since it requires installing three packages, Redis, Hiredis, and Redis-py but they all loaded with minimal fuss. Hiredis needed the Python development libs you can get on Ubuntu using:

$ sudo apt-get install python-dev

...to be continued