Sunday, November 15, 2009

Oracle's BETWEEN keyword

I came across a new Oracle keyword today, BETWEEN.

At first, I thought it was pretty cool. I would be able to simplify the majority of the range checks that I perform. Before I really started using it though, I decided to look at what it actually did. Ouch!

Google, my ever present documentation source, told me that between doesn't work the way I thought it would. It's inclusive of both ends of the range. Who would want that? You never want a range that is inclusive of both ends! Otherwise, elements in contiguous ranges have indeterminate ownership!

Let's try an example:

We want all rows with a date on the row that has a date of today.

  select id from test_table where my_date between 
    trunc(sysdate) and trunc(sysdate) + 1;

Great you would think, almost too easy!

You would be correct too, it was too easy. It doesn't work. Since it is inclusive of the end of range, you get all values that have a my_date of 12:00:00 tomorrow. What you really want is:

  select id from test_table where 
      (my_date >= trunc(sysdate)) and 
      (my_date < trunc(sysdate) + 1);

When using new keywords and abstractions, you should always know what they are doing.

Monday, November 02, 2009

std::auto_ptr and GDB.

I needed to gain access to the contents of an auto_ptr inside of GDB. However, GDB doesn't like the overloaded -> operator, so the simple foo->fnImInterestedIn() doesn't work. Here's the simple pattern:

class bar_t {
  public:
     int fnImInterestedIn();
};

std::auto_ptr<bar_t> foo;
(gdb) p ((struct bar_t *)foo._M_ptr)->fnImInterestedIn()

Hulu Proxy Apocalypse

It seems that the great Hulu apocalypse has hit more than just Witopia.net, Amazon's EC2 instances also seem to be blocked.

Of course, there are a tonne of other cloud providers out there, several of them even cheaper than Amazon. Personally, I'm still with Witopia. Like any good company, they had a new address range up immediately.

Hulu is stuck in the same game as Apple. They're playing whack-a-mole with the hackers. The only problem, every time they want to block an access method, it costs them money. However, it is free for us to invent a way around a block (it's a hobby), and there are a lot more of us than there are developers at Hulu.

This is yet another example of "Don't piss off the nerds".

Personally, here are the lessons that I would take from this.

  1. There is a market for International access. People are willing to _pay_ to get access. I am currently paying US$12/month to access Hulu, Pandora, and TV.com. I would pay that for unfettered access to Hulu.
  2. Hulu isn't going to win with black lists. They're going to have to implement a white list, which is a lot more expensive to maintain.
  3. Not a single person who was using Hulu simply stopped watching TV when Witopia and Amazon were turned off, they just went back to bittorrent.
  4. Don't piss off the nerds. They can out-spend you.

There are plenty of cloud providers out there. The same solution will probably work on other sites. Install Squid and give it a try!

Saturday, September 05, 2009

Using Amazon EC2 to access Hulu

As more and more content moves onto the Internet, it is frequently provided on a region-by-region basis. A lot of people want to have access to Hulu, Pandora, ABC, NBC, Netflix and the US Amazon and iTunes online stores.

I was one of them. S92A also provided an impetus to my research. If downloading US content was going to result in disconnection, I needed another way to get my North American TV fix. It would be even better if it was legal.

A little-known section of the NZ copyright law makes it legal to break DRM if the only purpose is to provide a region lock. To me, that indicates that if I can get around the geographic IP block on these web sites, I am no longer breaking NZ copyright law by watching the shows.

Perfect.

There are a couple of methods to do this. The ultimate method is using an OpenVPN server on EC2. I didn't start there. I started by using Squid.

First, you will need to learn how to construct an Amazon EC2 instance. This requires setting up an account, downloading the tools and starting an instance. Nothing too difficult, and all described by Robert Sosinski.

Since this will be a network proxy, we don't need a fast CPU, or a lot of memory. The smallest EC2 machine image is perfectly usable. I used a Fedora instance, since that was what I was familiar with at the time.

From the steps in Robert's instructions, I would leave out allowing access to port 80 (ec2-authorize default -p 80). We don't need it for this.

Now that you have a working image, we need to get Squid working. A funny aside, you can tell how mature the Internet is getting by the search results for open source project names. It used to be that if you Google'ed "Squid" you got the HTTP proxy. Now you get cephalopods.

I wanted a set of instructions that could be easily scripted so that I didn't have to leave the instance running, or store anything on S3, Amazon's storage system.

export EC2HOST=ec2-xx-xxx-xx-xx.compute-1.amazonaws.com

First we install and start squid.

ssh -i ec2-keypair root@$EC2HOST  "yum -y install squid"
ssh -i ec2-keypair root@$EC2HOST  "/etc/init.d/squid start"

Finally, we setup a local tunnel from our local machine to the Squid proxy.

ssh -i ec2-keypair -N -L3128:localhost:3128 root@$EC2HOST 

To make use of the proxy, all we need to do is point Firefox (or your preferred browser) at localhost:3128. Voila we now have access to the US.

However, if we try to use Hulu, only some of the videos work. We don't get the "not available in your region" error message anymore, instead we get a "unable to play the video at this time". Something else is going on.

Hulu is using multiple layers of security. They are not only checking the source of the HTTP stream, the actual RTMPE stream is protected as well. Time to add more stealth.

First, we tell squid to not tell anyone downstream who they are proxying for:

ssh -i ec2-keypair root@$EC2HOST  "echo "forwarded_for off >> /etc/squid/squid.conf"
ssh -i ec2-keypair root@$EC2HOST  "/etc/init.d/squid restart"

However, that doesn't fix all of the problems. Reading up on the protocol that the flash player uses (RTMP), we see that while it will tunnel over HTTP, it will first try to make a direct connection. It is that direct connection which is causing us problems, so we will turn it off.

sudo ipfw add 2000 deny tcp from any to any 1935 out

Now, when we try to use Hulu, we see that all of the videos are working, the RTMP stream is properly using the HTTP proxy, and Hulu is no longer restricting our access.

However, this isn't perfect. Amazon EC2 seems to rate limit the instances. Even though you are paying per byte of transfer, EC2 doesn't let you have more than 1mbps per connection. That means that while we can watch Hulu, we can't get reliable access to the HD content.

So, how expensive is it?

Here's some math....
  • NZ Sky subscription, basic plan (no movies, no sports). $11.74/week
  • Hulu Video
    Amazon Cost:
      Instance: US$0.1*(NZ$1/USD$0.67) = NZ$0.15
      Traffic (based on 1 episode of Eureka)
      (304MB/43min)*(60min/hr)*(1GB/1024MB)*(USD$0.27/1GB)*(NZD$1/USD$0.67) = NZ$0.17
      Total   : NZ$0.32/hr
    NZ Bandwidth cost:
      (304MB/43min)*(60min/hr)*(1GB/1024MB)*(NZ$1.50/GB) = NZ$0.62/hr
    Total cost per hour: NZ$0.94/hr
    
  • Bittorrent cost per hour
      SeedRatio = 1.0
      (350MB/40min)*(60min/hr)*(2-(1-SeedRatio))*(1GB/1024MB)*(NZ$1.50/GB) = NZ$1.53/hr
    

Break even point of Squid Proxy:

  • vs Bittorrent - instant
  • vs Sky - 11.74/0.94 = 12 hours.

Therefore, to have any value, you need to be watching content on Sky TV which isn't available on FreeView for more than 12 hours a week in order to justify paying for Sky TV.

So, in this case, going legal is cheaper.

Sunday, March 22, 2009

The Future of Cable-TV

There's a bit of a discussion going on between Mark Cuban and Avner Ronen. It started with someone writing an article about boxee, the company that Avner heads.

Mark seemed to take exception to the article, and posted, "Why Do Internet People Think Content People Are Stupid?" Avner then followed up on his blog.

I've been thinking about Cable and Broadcast TV for a while. I find myself agreeing with Avner, that the Internet will allow customers to have a la carte access to shows and channels.

First off, why would this happen? We only need to look at PVRs to see where it is going. PVRs are changing the relationship between broadcast networks, content creators and viewers. Currently, a PVR changes how a viewer makes use of the TV network. They can watch any show they are interested in, regardless of when it was broadcast, or even if they know it is being broadcast. People with PVRs timeshift TV shows, frequently watching a show up to a week after broadcast. This change in viewing habits is showing up in the TV show's ratings, with some shows seeing a drop of up over 30% viewership as their viewers record it for later viewing.

What happens when the majority of your customers have PVRs? They no longer watch "whatever is on". They will watch the shows that they want to watch, when they want to watch them. The broadcast schedule becomes less important. In fact, it doesn't matter when the show is broadcast anymore. Your viewers will automatically follow the show through scheduling changes.

Some consultants say that people will still want to watch the show during the broadcast slot so that they can talk about it the next day at work. That is true, there is some pressure to watch a show as it comes out, but it doesn't need to be watched immediately. It can be watched just as easily +1,+2,+6 hours later. The person could even elect to watch the show the next morning over coffee or on the way to work on the train.

So, if the timeslot doesn't matter, what does that do to a broadcast network? Frankly, it turns them into two things. First and foremost, they are aggregators. They decide what it is that you are going to watch. Second, they are a very efficient one to many data network. Because of their sunk costs in the form of spectrum and transmitters they are able to deliver content to homes across the world cheaply.

Now, remember, in the world of the PVR, it doesn't matter when a show is broadcast - it'll be found and recorded. This lowers the value represented by prime-time slots. Everyone is watching TV at that time, but it isn't needed to show them pre-recorded content. It also increases the value of the 2-6AM slots. The time when a broadcaster would usually send out a test-signal or infomercials are now perfectly positioned to show syndicated content.

Remember, it's all about feeding the PVR. You want to fill their viewing hours with _your_ content, not the other guy's.

So, we're not in a world where insanely popular shows are broadcast to people's PVRs at 2AM on a Monday morning. Just in case you think this is crazy, this is exactly how bittorrent works with background downloaders like TED (torrent episode downloader). TV shows show up on the pirate networks in the middle of the night, and are available for watching on your local PVR a couple of hours later.

So, now that they're feeding your PVR, what happens next? Aggregation. The networks provide aggregation and editing services. They are tastemakers. The only problem? They demonstrate this taste through their line-up and schedule. As I've already shown, the schedule is unimportant - people use PVRs. That leaves only the line-up. Those "up-next" teasers for the next show? Of little value - the viewer can't watch the next show! So, the line-up also becomes unimportant. There is no way to package shows to make viewers more "sticky". They will choose shows from networks a la carte. Again, we can already see this behaviour - both on PVRs, and bittorrent. There are also better "tastemakers" than networks. They're called bloggers. There are a lot more of them, they are the reviewers of the Internet age. Even better, they are perceived as more trustworthy, because they don't review things for a living. True "tastemaking".

In the world of the PVR, syndication is dead. In the world of 500 channels, how many versions of CBS do you need? How many times a day do you need to watch the same episode of "The Simpsons"? If your viewers have a PVR, the answer is you only need 1 instance. All those cable networks that are syndicating your shows to fill in their schedules? If you put those shows on your own network, with your own ads, you can have that revenue too.

So, the value of syndication has just collapsed. There's only room for one copy of each episode per week (perhaps even per year). All that revenue broadcasters get from cable companies for retransmitting their channels? Gone - the cable company only needs one, and they'll take the local one - they can frequently get that for free.

Let's recap. We've killed the schedule, aggregation and syndication. We have just turned a local TV broadcaster into a broadband pipe that specialises in delivery of video and audio content supported by local advertising.

Does that sound familiar? It should. It's an ISP running a rewriting HTTP proxy, that inserts advertisements into pages that its customers view.

At that point, the model shifts. Content producers sell their own advertisements and purchase time on the broadcast networks. This is how I see it proceeding:

  1. Content producers sell their own advertisements.
  2. They put their back catalog up on the Internet at VoD.
  3. They make the content available on a P2P network.
  4. In markets where they have significant penetration, they purchase time from the local broadcasters, and feed that information to their customers.

Now that would be an interesting synergy. You watch a show on Hulu through Boxee. When you are finished, up pops a dialog box "Would you like to schedule this show for recording in your area?". If you select yes, it instructs your local PVR to record that show the next time it comes around.

All of a sudden, there is a continuous flow between Internet VoD, P2P and OTA (or cable) broadcast. Each with their own strengths.

That'll be cool.

Monday, February 23, 2009

New Zealand S92A

Just to make sure that my stance isn't lost now that the blackout's been lifted.

I would like to see several changes to the TCF, including the right to see the evidence of your accusers.

Tuesday, February 10, 2009

Holy Cow

Wow, the price plans are changing. Even the prepaid plans are getting into the whole "flat rate" thing. I love the idea of a plan where if you don't use the phone, you aren't charged for the plan. The addition of unlimited on-net calling? Perfect.

Verizon prepaid pricing changes coming February 11th

(from Engadget Mobile)

Risk Management, are you getting your money's worth?

For the first time in the better part of a decade, I'm tech lead on a new project for my current employer. For the intervening years I've been working for other employers, other projects.... I wasn't slacking, honest!

Anyways, it gives me a perfect opportunity to compare and contrast the organization of 10 years ago with today.

Holy Cow! It takes them way to long to start up a project. They spend too long deciding what to do, and not enough time actually doing it. Of course, this is all in the name of "risk mitigation".

I'm finding it both extremely frustrating and hilarious. It makes me want to throw things. The company is going to spend well over 30k to make sure that the 150k they spend on the project is a success. Even before writing the SRS. They are going to spend 30k writing a Product Concept Document, Project Definition Workshops, Project Initiation Gate Meeting, and a Product Scoping Document with estimates. I'm even willing to bet that I am underestimating how much they've spent on this.

The funny thing? All that work will be thrown out as soon as the SRS is written.

The next shock was the testing cost. For every day of development, there is a day of testing, more risk mitigation. Then there's another day added for "overhead". So, that small 100 day project? It's actually 300 days.

So, I looked at it from a math point of view. First the project budget:

  1. Pre-SRS work - 45k
  2. SRS - 45k
  3. Development effort - 100k
  4. Testing effort - 100k
  5. Management overhead - 100k
Total Project cost: 390k
Risk of complete failure: 10%

Even worse, the calendar time and effort are unrelated. The calendar time for steps 1+2, 3, 4 are all the same.

Now, let's have a look at a riskier way of doing it:

  1. Pre-SRS work - 15k
  2. SRS - 7k
  3. Development effort - 75k
  4. Testing effort - 50k
  5. Management overhead - 50k
Total Project cost: 197k
Risk of complete failure: 50%

We've gotten rid of all of the risk mitigation. Not only that, we've shrunk the time in steps 1+2 by 75%! That's a huge time to market win.

Let's see if the risk reward makes sense.

The cost of a failure is 50% (odds of failure) * the cost of the project:
  Risky Way: 197k * 0.5 = 95k
  Safe Way: 390k * 0.1 = 39k

Therefore, the amortized cost of a project using the:

  Risky Way: 197k + 95k = 292k
  Safe Way:  390k + 39k = 429k

What failure rate would be needed to justify the extra cost? 70%? 80%? 90%? To justify the extra money spent (assuming 0% the safe way), the failure rate would have to be:

390k - 197k
----------- = 97%
   197k

Failure is the cost of total failure, as in the project has to be thrown away and started over.

Add in the time to market benefits (on the order of 30% for these assumptions), and it starts to look pretty convincing.

Everyone wonders why so many businesses are CMM level 0/1. Have you considered that they might actually be right?

Thursday, January 15, 2009

Prepaid is Dead, redux.

I just saw this in the news today:

Boost sees $50 unlimited plan battling Leap, Metro

Unlimited calling and texting for US$50/month. It's a race to the bottom with all-you-can-eat plans.

If you're charging per minute, per sms, per byte, the question is "why?". Save yourself a lot of money and quit billing for the core service! That Intec Billing Engine you're thinking of buying? Get rid of it, or use it for something other than charging for calls.

Tuesday, November 25, 2008

Adding value?

Ask yourself, "Can I be replaced with a shell script?" Specifically:

 % yes 'No'

Then ask yourself, "What value am I adding?"

Tuesday, September 09, 2008

Google Chrome, a Contrarian View.

I read the comic about Google Chrome. I love the architecture! We downloaded it here in the office, and sure enough - it forks a new process for every page load. This is the browser architecture that I've been waiting years for, one where a script on one page won't kill performance in another window.

So, I went home and tried it on my single core Athlon at home. Ouch! The performance is terrible. The browser keeps locking up, it stops responding to mouse clicks, keypresses, anything and everything. It acts like alpha quality software, not the "beta" it is supposed to be.

I've got a 2 year old system (Athlon64 3800+), the only difference between it and new ones is that it is single core. It's still fast enough to play new games on, but it can't handle Google Chrome.

I can only assume that Google Chrome has a tendency to starve some of their child processes on single core machines.

In the meantime, I'll stick with Firefox 3. It leaves Google Chrome in the dust.

Wednesday, August 06, 2008

Duck Typing Sucks.

I'm working with some code that's written in Python, and makes extensive use of duck typing. In duck typing the premise is that if it quacks like a duck, it is a duck.

Of course, if you've got code that doesn't tell you what it expects to receive, you can't hope to figure out what the type should be.

For example, let's say you've got 3 code blocks:

class A:
    def funkyDuck():
        # random cool stuff

class B:
    def funkyDuck():
        # entirely different cool stuff

class C:
    def funkyDuck():
        # a third entirely cool thing

Now, imagine you're looking at code that goes:
some_random_object.funkyDuck()
Which one gets called? By the way, they're all in different files, so the only way to find them is with "grep". Added bonus, the undocumented hash!
    def addApplications(self, appDict):
        """ Add some application modules to the defaults.
            All binaries and libraries in any of the source dirs will be soft linked
            to a directory with the name of the product.
            @type  appDict: dict of string -> (list, string)
            @param appDict: The source dirs and OS user name for each product
        """

Guess I'm supposed to guess what appDict actually looks like.

Hrm. Perhaps my problem isn't with duck typing itself, but it's use here.

Hint: When your test framework is just as complicated as the program under test, you're doing something very, very wrong.

Tuesday, July 22, 2008

One in a Million

I remember discussing multi-threaded programming with a senior engineer the better part of a decade ago. I was reacting rather strongly to his cavalier attitude towards multi-threaded code, deadlocks and race conditions.

"That is such a small hole, it's one in a million that it will happen."

At the time, we were a small company, and I was a young engineer. One in a million, that doesn't sound that big. Of course, one in a million happens more frequently than you would expect. It didn't take very long for our systems to be processing a million transactions a day, and then millions per hour. Every time the holes had to get smaller and smaller.

They still have a fault in there where the entire system crashes when the system goes completely idle for a couple of minutes. It doesn't happen all the time, it's a "one in about 20 million", but it only has to happen once. So, it crashed about once a week. That one took forever to track down. Still haven't been able to fix it entirely, but they know that it's there, and the hole is smaller, probably "1 in a couple billion" now, below the rate that it's restarted for maintenance. Fixed, for now.

It's interesting see that the DNS engineers are learning the same lesson. Compute power has now shifted in favour of the attackers. As we saw with Captcha, it doesn't matter that you only get through rarely - you only have to get through once in a while. Even just guessing a DNS TXID (2^16), you've got a 1 in a 65536 chance of guessing the right answer.

In pure mathematical terms, the likelihood of getting the TXID wrong 400,000 times in a row is 0.2%. In other words, pretty certain.

(1-(1/2^16)))^400000)

Let's look at the 50/50 point, where the likelihood of seeing X number of failures is 0.5.

That turns out to be somewhere around 45000 attempts, simple for loop range. Since I am spoofing packets, I don't care about a response, even better, filling up the pipe will expand the race situation, giving me a larger chance to get through.

Still, it sounds like the attacker has to also be requesting lookups to poison the server. Let's say they take 2ms each, and they're being nice by only doing them one at a time. Even using the large 400k count, it will take at most 15 minutes of concerted effort to poison the cache. The 50/50 point? One minute, 20 seconds.

Look out for those one in a million situations, they happen more often than you'd like.

Monday, July 21, 2008

Naming Documents

I thought we killed off Hungarian Notation because it doesn't work? Did I miss a memo somewhere? It seems that Hungarian Notation is making a comeback, this time in document names.

There's nothing like having your meta data encoded in the file name, with three letter acronyms for everything. It is impossible to decode, and becomes really fun when the team names change once a year!

"Say where's the SRS?" "Is it in SRS.doc?" "Nope" "How about esgEng_SIT_DR4_SRS.doc?" "Nope" "Oh, wait, Engineering was renamed last year for 6 months.... How about esg_PEN_SIT_DR3_SRS.doc?" "Ah, that's got it."

Encoding meta data in the filename is stupid. How about putting it in the file in the meta data portion where it belongs, and then using a search tool to search it? Or, maybe a directory structure that represents your tag tree.

esgEng/SIT/DR4/SRS.doc

Then, when you need to change the meta data, you rename the tree:

esg/PEN/SIT/DR3/SRS.doc

But Jason, I need to know who produced the document without opening it!

Use the checksum, and search/store that. Anything else can be mistakenly altered or lost. Use the file's checksum. It is a much more reliable descriptor of the file than the filename! I have learned from experience to, never, ever trust a filename, they lie.

Or better yet, you buy a document repository off the shelf for 100k, and shove the problem at them. Personally, I just use the Google Search Appliance. Now that they've got it looking at the correct bits of data, it's very useful. Much better than any of the searches built into the various corporate portals.

Friday, July 11, 2008

Getting Starcraft working on OSX

I've started playing Starcraft again after ages away, but I found that my brand spanking new MacBook Pro wouldn't work!

The new versions of OSX have an updated video driver which does not support 256 colour modes. This means that Starcraft, Diablo II, or basically any older game will no longer work. Not good when the applications were still sold by Apple as OSX compatible games (they've since been removed).

I have now figured out a simple (albeit more expensive - US$79.99 + Windows license) way to solve the problem. I decided to run the game under VMWare Fusion.

However there were two problems with this. First, when running in full screen mode, the display doesn't stretch to fill the screen. So on my laptop, I end up with a postage stamp display right in the middle of the screen. Second, the mouse is not restricted to that little postage stamp, it moves freely all the way around the display. When attempting to scroll the display in the game, you move the mouse to the edge, since the mouse will leave the bounds, the game doesn't scroll very well.

The first was fixed with a quick google.

In the file "Preferences/VMWare Fusion/preferences" add

    pref.autoFitFullScreen = "fitHostToGuest"

This will stretch the display. If you have a widescreen display, you will still have black bars on the left and the right, but we're making progress.

Now to mouse capture. There doesn't appear to be an option to prevent the mouse from being taken back by the host OS, so I took a more drastic approach. I uninstalled VMWare Tools. This requires a reboot of the VM, but when you are done, you will no longer be able to move the mouse outside of the VM!

To get back to the host OS, press CTRL-CMD. To re-install VMWare Toole, select "Install VMWare Tools" under "Virtual Machine"

You should now be able to play Diablo II and Starcraft in all their 256 colour beauty.

Now, if I can only control my nerves enough to work my trackball....

Thursday, July 10, 2008

Keeping Efficiency Gains

Air Canada has implemented self check-in at Pearson Airport in Toronto. For all flights, you no longer go to an attendant to obtain you boarding pass, you enter all the required data into a computer, and then check your bags.

This was supposedly done for efficiency reasons. However, most of the efficiencies in the system have been lost. Amazingly, when you get to the front of the second line (to check in your bags), the check in clerk does exactly the same amount of work as before. The first thing they do is verify all of the details that you provided the computer!

Let's go over that again. After having provided my information to a computer, I have to provide it a second time to a human who verifies the first data. The time taken for verification was exactly the same as it would have taken for them to key it in in the first time. Instantly, you have a net loss of efficiency. Even worse, they only have a single set of scales for each pair of desks. That means that there is substantial dead time while you wait for the person at the desk next to you to finish weighing their bags. More lost efficiency.

I can see how it happened. Someone checked in to the wrong flight, or their bags went to the wrong place. Perhaps they got to US customs (you go through US customs in Canada when flying to the US), and didn't have the correct forms or all their data provided, and were sent back, maybe they even missed a flight.

So, the check-in clerks, who are also looking to protect their jobs, add in the task of checking customer provided data.

However, they don't check the data of people who don't have checked baggage, they go straight through to customs. This shows the stupidity of the additional check. Is Air Canada saying that people with checked luggage are more likely to enter incorrect data? I doubt it.

If you make efficiency gains in your organisation, make sure you protect them. Guard them jealously. If you don't, you will see them frittered away.

Thursday, June 12, 2008

The Truth about Vacations.

This invariably happens to me. I go on vacation, and then the server goes down. It doesn't go down during the year. It's had an uptime of over a year! However, it's down and stayed down. So, if you've been trying to email me, I apologize, it won't get through. The same goes if you're wondering where blog.jason.pollock.ca went to, or why I'm not on jabber anymore. I'm trying to get it going again, but email will probably be down until I get back home. The eBook Repositories will definitely not be updating, so the Baen Books will slowly rot.

Saturday, June 07, 2008

Installer.app and chmod/chown

How is it that I would go about chmodding the directories created by CopyPath?

It seems that if the .zip contains the permissions already, they are maintained when used by CopyPath.

In other words, if you have:

foo/bar

in your .zip, and do a CopyPath("foo", "~/foo") in the XML document, the permissions are set up correctly. At least I haven't had any problems if my installer looks like that.

However, if you create implicitly create directories by using CopyPath on the individual files, they are created without permissions, and a chmod/chown is needed. For example, CopyPath("foo/bar", "nuts/baz/bar") will create "nuts/baz", with no permissions.

I have to do this with the Gutenberg SciFi and Baen Books libraries, since I don't host the .zips themselves.

To manage the chmod/chown problem, the packages ensure that the BSD subsystem is installed (or Cydia), and then runs them as part of the install steps.

Here is an example:

      <key>preflight</key>
      <array>
        <array>
          <string>IfNot</string>
          <array>
              <array>
                <string>InstalledPackage</string>
                <string>com.natetrue.iphone.iphone_binkit</string>
              </array>
          </array>
          <array>
              <array>
                <string>AbortOperation</string>
                <string>You must install the "BSD Subsystem" package from Installer first!  It's in the System Category.</string>
              </array>
          </array>
        </array>
      </array>

Which checks for the BSD subsystem as part of the pre-install. If the BSD subsystem is not installed, the user gets a pop-up error message and the package will not install.

And then the install

      <key>install</key>
      <array>
        <array>
          <string>CopyPath</string>
          <string>1013.txt</string>
          <string>~/Media/EBooks/The_First_Men_in_the_Moon/1013.txt</string>
        </array>
        <array>
          <string>If</string>
          <array>
              <array>
                <string>FirmwareVersionIs</string>
                <array>
                  <string>1.1.3</string>
                  <string>1.1.4</string>
                </array>
              </array>
          </array>
          <array>
              <array>
                <string>SetStatus</string>
                <string>Changing Permissions</string>
              </array>                              
              <array>
                <string>Exec</string>
                <string>/bin/chmod -R 755 /var/mobile/Media/EBooks</string>
              </array>
              <array>
                <string>Exec</string>
                <string>/usr/bin/chown -R mobile /var/mobile/Media/EBooks/.</string>
              </array>
              <array>                 
                <string>SetStatus</string>
                <string>Running GutenMark</string>
              </array>
              <array>
                <string>Exec</string>
                <string>/usr/bin/GutenMark --profile=en --no-toc --config=/etc/GutenMark.cfg /var/mobile/Media/EBooks/The_First_Men_in_the_Moon/1013.txt /var/mobile/Media/EBooks/The_First_Men_in_the_Moon/1013-h.htm</string>
              </array>
              <array>
                <string>SetStatus</string>
                <string>Running GutenSplit</string>
              </array>
              <array>
                <string>Exec</string>
                <string>/usr/bin/GutenSplit --no-toc /var/mobile/Media/EBooks/The_First_Men_in_the_Moon/1013-h.htm /var/mobile/Media/EBooks/The_First_Men_in_the_Moon/Chapter_</string>
              </array>
          </array>
        </array>

That's not the full install segment, but it should give you an idea. I have to separate 1.1.3/4 from earlier firmwares because they use different users and store files differently.

To help, I've created a little perl library that allows me to write packages without having to mess with the nasty XML. It's part of the iphoneebookrepo project over at google code. Specifically PlistMaker.pm.

In terms of the perl library, it ends up looking like this:

my $gutenberg_html_install =
 p_if(IsFirmwareVersion("1.1.3", "1.1.4"),
      SetStatus("Changing Permissions").
      Exec("/bin/chmod -R 755 /var/mobile/Media/EBooks").
      Exec("/usr/bin/chown -R mobile /var/mobile/Media/EBooks/.").
      SetStatus("Running GutenSplit").
      Exec("/usr/bin/GutenSplit -1 -2 -3 -4 --no-toc --no-skip /var/mobile/Media/EBooks/$BookDir/${BookNumber}-h.htm /var/mobile/Media/EBooks/$BookDir/Chapter_")
 ).
 p_if(IsFirmwareVersion("1.0.0", "1.0.1", "1.0.2", "1.1.1", "1.1.2" ),
      SetStatus("Changing Permissions").
      Exec("/bin/chmod -R 755 /var/root/Media/EBooks") .
      SetStatus("Running GutenSplit").
      Exec("/usr/bin/GutenSplit -1 -2 -3 -4 --no-toc --no-skip /var/root/Media/EBooks/$BookDir/${BookNumber}-h.htm /var/root/Media/EBooks/$BookDir/Chapter_")
 );

my %BookDescriptor = (
 bundleIdentifier => "ca.pollock.gutenberg.$BookNumber",
 name => $BookTitle,
 version => "1.0",
 location => $BookURL,
 category => "Gutenberg SciFi (" .$BookLang . ")",
 size => $BookSize,
 hash => $BookMD5,
 url => "http://jason-pollock.blogspot.com/",
 maintainer => "Jason Pollock",
 contact => 'jason@pollock.ca',
 description => "by $BookAuthor",
 install => $Book_install,
 preflight => $Book_preflight,
 postflight => "" ,
 uninstall => $Book_uninstall,
 update => ""
 );

my $BookPLIST = CreatePackage(%BookDescriptor);

One "Gotcha" to be aware of... The Exec command is actually performing it's own parameter splitting prior to calling "Exec". It does not do any sort of "~" expansion, nor does it understand spaces. So, if you are doing a chmod on a directory with spaces in the name, it won't work, regardless of escapes or quotes.

Sunday, May 11, 2008

The iPhone Gutenberg Science Fiction eBook Repository!

Yes, I managed to finish it. I've managed to convince Project Gutenberg books to install onto the iPhone.

To make use of the repository:

  1. Obtain an iPhone.
  2. Jailbreak the iPhone, I recommend ziphone for this task.
  3. Install Books, the iPhone ebook reader using the Installer application (1.4+ only!)
  4. Add the repository to Installer:
    1. Start Installer
    2. Click "Sources"
    3. Click "Edit"
    4. Click "Add"
    5. Enter "http://library.pollock.ca/gutenberg_scifi"
    6. Click "OK"
    7. Click "Done"
    8. Click "Refresh"
  5. Select "Install" at the bottom of the screen. You will see "Gutenberg SciFi" is now available as an application category!
  6. Before you can install a book, you will need to install GutenMark, it is under Utilities. I am using it to format the files on your phone to save me bandwidth.

There are currently 163 books in the library, in English and French. The list of books I used is from Gutenberg's SciFi CD collection. Since I can convert any Gutenberg book at this point, if there is a favourite you are looking for, please let me know.

The installation software has a preference for the HTML version of the book if it exists, however it will use the TXT version and pass it through GutenMark if it doesn't. Both versions will be split into chapters using the very handy GutenSplit.

Friday, May 02, 2008

VoIP and 911

I see that another infant has died because a VoIP call wasn't properly routed to a 911 operator. Situations like this caused some very extreme results for US VoIP carriers - Vonage wasn't allowed to accept new customers for a couple of months until they sorted it out!

Every time I see one of these stories, I try to come up with a solution. Here's what I would do for this problem.

There are a couple of problems in the current solution that need to be solved. First, the call was routed based on the customer's billing data. That isn't accurate in the VoIP world. It's not even accurate in the fixed line world! Many people have phones that are billed to PO boxes or businesses that are not the physical location of the line. Second, E911 has the ability to locate an individual caller. Without that, if the call is disconnected, or the caller cannot speak, the 911 operator has no way of determining where the person needing help is.

First, the easy one. Routing based on billing data. This is pretty easy, DON'T DO IT!

We need to find some reasonably accurate geolocation data in a VoIP call. Thankfully, it's right there. The source IP address. Home VoIP will be at the end of either a cable or DSL modem. Either is a physical port. With a static IP address, it's well defined where they are. Even with a dynamic address, the address range is still geographically limited. Definitely accurate enough to select a 911 call center.

We can make use of commercial IP address geolocation databases to route to the nearest 911 operator. There are existing commercial databases that provide just this information. However, the data may be inaccurate. So, you add the data to the call. You now have a call with location data of the call and the billing data. If they disagree, you route based on the IP address and inform the call center to verify the region information.

Perhaps it's too simple a solution. VoIP telephony people (and most Internet people) view the Internet as a cloud, they don't trust IP addresses to identify locations (Telephony people have the opposite problem, they put too much trust in the phone number.)

However, society has started using IP addresses as not only identification of location, but of a specific user too. For an example, have a look at the RIAA lawsuits in the US. The IP address is sufficient to sue an individual for copyright infringement. It is used to identify not only the location the connection is made from, but to make a reasonable assertion to the identity of the individual!

So, current commercial IP address geolocation products have the information we need to properly route 911 calls to the local call center.

How do we get E911 levels of location accuracy? To do that, we need the help of the ISPs.

Remember, everyone is connecting through DSL or cable, or some other fixed-line connection. We will deal with mobile later. That means that the ISP has a mapping between the IP address and the physical port (at least for DSL, cable too probably). However, gaining access to this data will require government regulation and probably some money changing hands (carriers bill for 911 services).

If this database is also made available to the 911 operator, then we have a complete system, a database that maps an IP address to a call center, and then on from the IP address to the physical location. There is probably even a standard that we can use, since E911 services for mobile phones have the same problems.

So, what about mobile? Well, in the mobile world, we still have the IP address to location mapping, and the carrier still has the IP address to physical location mapping. However, it is a little more indirect. There is a mapping from IP address to phone number, and then the carrier can use their existing E911 services to locate the actual device.

Is any of this even expensive code? No, it isn't. That's the interesting bit. It's all information that is added on to the existing 911 call. Even without a correct geolocation of the IP address, the call center operator can still correct the problem by asking "Where are you?". This system will be there to provide additional information to the 911 operator, not replace them. Since the 911 operator themselves are a key component of this solution, additional training will undoubtedly be needed, including a change in some of the scripts they read from. Adding the city to the address for confirmation would solve many problems.

Where does this break down?

  1. VPN - If the phone is in a branch office, that routes IP traffic through a VPN to a different POP, it won't work. However, they've already got this exact same problem with corporate PBXs anyways, this isn't new.
  2. Calls from outside of the jurisdiction. If someone takes the device overseas to use it for cheap (free) long distance.
  3. Carriers making frequent changes to their routing rules. If a subnet moves from one region to another, 911 calls may have the wrong location until the database is updated.