hand page 2 - Dave's Blog

Search
My timeline on Mastodon

Subtleties of postMessage

2013 Jul 15, 1:00

In IE10 and other new browsers one may create MessageChannel objects that have two MessagePorts each connected (w3c spec calls it entangled) to one another such that postMessage on one port results in the message event firing on the other. You can pass an array of ports as the last parameter to postMessage and they show up in the ports property of the message event arg.

Origin

The postMessage here is like the worker postMessage and unlike the window and iframe postMessage in that it applies no origin checking:

  1. No origin postMessage in workers and MessagePorts: postMessage(messageData, ports)
  2. Origin postMessage in windows and iframes: postMessage(messageData, targetOrigin, ports)

Unfortunately the origin isn't an optional parameter at the end to make the two postMessages have the same signature.

On the event handler side, the event arg always has an origin property. But in the no origin case it is always the empty string.

Source

There is also a source property on the message event arg which if set is an object that has a postMessage property allowing you to post back to your caller. It is set for the origin case, however, in the no origin case this property is null. This is somewhat reasonable because in the case of MessagePort and Workers there are only two endpoints so you always know the source of a message implicitly. Unlike the origin case in which any iframe or window can be calling postMessage on any other iframe or window and the caller is unknown. So not unreasonable but it would be nice if the source property was always set for consistency.

MessageChannel start

When a MessageChannel is created it has two MessagePorts, but until those ports are started they will queue up any messages they receive. Once started they will dispatch all queued messages. Ports don't have to be started to send messages.

A port may be started in two ways, either by explicitly calling the start method on the port, or by setting the onmessage callback property on the port. However, adding an event listener via addEventListener("message", does not start the port. It works this way in IE and Chrome and the spec states this as well.

The justification is that since you can have only one callback via onmessage that once set you must implicitly be ready to receive messages and its fine to start the port. As opposed to the addEventListener in which case the user agent cannot start implicitly because it doesn't know how many event listeners will be added.  I found Hixie stating this justification in geoloc meeting notes.

Links

W3C Spec

Opera introduction

PermalinkCommentsDOM html javascript postMessage technical web-worker worker

Words with Hints Windows 8 App Development Notes

2013 Jul 4, 1:00

My second completed app for the Windows Store was Words with Hints a companion to Words with Friends or other Scrabble like games that gives you *ahem* hints. You provide your tiles and optionally letters placed in a line on the board and Words with Hints gives you word options.

I wrote this the first time by building a regular expression to check against my dictionary of words which made for a slow app on the Surface. In subsequent release of the app I now spawn four web workers (one for each of the Surface's cores) each with its own fourth of my dictionary. Each fourth of the dictionary is a trie which makes it easy for me to discard whole chunks of possible combinations of Scrabble letters as I walk the tree of possibilities.

The dictionaries are large and takes a noticeable amount of time to load on the Surface. The best performing mechanism I found to load them is as JavaScript source files that simply define their portion of the dictionary on the global object and synchronously (only on the worker so not blocking the UI thread). Putting them into .js files means they take advantage of bytecode caching making them load faster. However because the data is mostly strings and not code there is a dramatic size increase when the app is installed. The total size of the four dictionary .js files is about 44Mb. The bytecode cache for the dictionary files is about double that 88Mb meaning the dictionary plus the bytecode cache is 132Mb.

To handle the bother of postMessage communication and web workers this was the first app in which I used my promise MessagePort project which I'll discuss more in the future.

This is the first app in which I used the Microsoft Ad SDK. It was difficult to find the install for the SDK and difficult to use their website, but once setup, the Ad SDK was easy to import into VS and easy to use in my app.

PermalinkCommentsdevelopment technical windows windows-store words-with-hints

In Depth Review: New NSA Documents Expose How Americans Can Be Spied on Without A Warrant

2013 Jun 21, 10:43

What It All Means: All Your Communications are Belong to U.S. In sum, if you use encryption they’ll keep your data forever. If you use Tor, they’ll keep your data for at least five years. If an American talks with someone outside the US, they’ll keep your data for five years. If you’re talking to your attorney, you don’t have any sense of privacy. And the NSA can hand over you information to the FBI for evidence of any crime, not just terrorism. All without a warrant or even a specific FISA order.

Not sure if this is saying all Tor data is collected or saying if someone uses Tor then start collecting that someone’s communication.

PermalinkCommentstechnical legal tor nsa eff spying security privacy

laughingsquid: hi-Call, A Bluetooth Handset Glove

2012 Sep 26, 6:24


laughingsquid:

hi-Call, A Bluetooth Handset Glove

PermalinkCommentshumor phone cell-phone blue-tooth video

theatlantic: How the 8.5” x 11” Piece of Paper Got Its...

2012 Sep 19, 6:37


theatlantic:

How the 8.5” x 11” Piece of Paper Got Its Size

Why do we use a paper size that is so unfriendly for the basic task of reading? According to a very interesting post by Paul Stanley, the rough dimensions of office paper evolved to accommodate handwriting and typewriters with monospaced fonts, both of which rendered many fewer characters per line. “Typewriters,” he explains, “produced 10 or 12 characters per inch: so on (say) 8.5 inch wide paper, with 1 inch margins, you had 6.5 inches of type, giving … around 65 to 78 characters.” This, he says, is “pretty close to ideal.”

Read more. [Image: Picsfive/Shutterstock]

PermalinkCommentstechnical paper history

Stripe Web Security CTF Summary

2012 Aug 30, 5:00

I was the 546th person to complete Stripe's web security CTF and again had a ton of fun applying my theoretical knowledge of web security issues to the (semi-)real world. As I went through the levels I thought about what red flags jumped out at me (or should have) that I could apply to future code reviews:

Level Issue Code Review Red Flags
0 Simple SQL injection No encoding when constructing SQL command strings. Constructing SQL command strings instead of SQL API
1 extract($_GET); No input validation.
2 Arbitrary PHP execution No input validation. Allow file uploads. File permissions modification.
3 Advanced SQL injection Constructing SQL command strings instead of SQL API.
4 HTML injection, XSS and CSRF No encoding when constructing HTML. No CSRF counter measures. Passwords stored in plain text. Password displayed on site.
5 Pingback server doesn't need to opt-in n/a - By design protocol issue.
6 Script injection and XSS No encoding while constructing script. Deny list (of dangerous characters). Passwords stored in plain text. Password displayed on site.
7 Length extension attack Custom crypto code. Constructing SQL command string instead of SQL API.
8 Side channel attack Password handling code. Timing attack mitigation too clever.

More about each level in the future.

PermalinkCommentscode-review coding csrf html internet programming script security sql stripe technical web xss

Application Protocols in Windows 8

2012 Jun 12, 4:09
In Windows 8 you can still register a desktop application to handle a particular URI scheme, but now you can also register a Metro Win8 application to handle a particular URI scheme. No more manually modifying the registry - now there's pretty UI in VS to handle this.
PermalinkCommentsapplication-uri programming technical uri windows windows8

International - Max Fisher - Welcome to America, Please Be On Time: What Guide Books Tell Foreign Visitors to the U.S. - The Atlantic

2012 Jun 7, 9:15

Such tips as: “don’t hand out cash to dinner guests” reveal what foreign tourists findsurprising about coming to America.

PermalinkCommentshumor travel us

Web Worker Initialization Race

2012 Feb 24, 1:44

Elaborating on a previous brief post on the topic of Web Worker initialization race conditions, there's two important points to avoid a race condition when setting up a Worker:

  1. The parent starts the communication posting to the worker.
  2. The worker sets up its message handler in its first synchronous block of execution.

For example the following has no race becaues the spec guarentees that messages posted to a worker during its first synchronous block of execution will be queued and handled after that block. So the worker gets a chance to setup its onmessage handler. No race:

'parent.js':
var worker = new Worker();
worker.postMessage("initialize");

'worker.js':
onmessage = function(e) {
// ...
}

The following has a race because there's no guarentee that the parent's onmessage handler is setup before the worker executes postMessage. Race (violates 1):

'parent.js':
var worker = new Worker();
worker.onmessage = function(e) {
// ...
};

'worker.js':
postMessage("initialize");

The following has a race because the worker has no onmessage handler set in its first synchronous execution block and so the parent's postMessage may be sent before the worker sets its onmessage handler. Race (violates 2):

'parent.js':
var worker = new Worker();
worker.postMessage("initialize");

'worker.js':
setTimeout(
function() {
onmessage = function(e) {
// ...
}
},
0);
PermalinkCommentstechnical programming worker web-worker html script

Devs celebrate Double Fine's Kickstarter success

2012 Feb 10, 3:40

Some backhanded compliments towards the end =).  Exciting regardless.

PermalinkCommentsgame video-game double-fine kickstarter tim-schafer

Hacking Google for Fun and Profit (andrewcantino.com)

2011 Dec 28, 5:34

First hand account of security researcher reporting security issues to Google and details on the security issues.

PermalinkCommentstechnical google security csrf

(via Hand-stitched Kanye West tweets)

2011 Dec 9, 1:16


(via Hand-stitched Kanye West tweets)

PermalinkCommentshumor twitter kanye-west stitching

URI Empty Path Segments Matter

2011 Nov 23, 11:00

Shortly after joining the Internet Explorer team I got a bug from a PM on a popular Microsoft web server product that I'll leave unnamed (from now on UWS). The bug said that IE was handling empty path segments incorrectly by not removing them before resolving dotted path segments. For example UWS would do the following:

A.1. http://example.com/a/b//../
A.2. http://example.com/a/b/../
A.3. http://example.com/a/
In step 1 they are given a URI with dotted path segment and an empty path segment. In step 2 they remove the empty path segment, and in step 3 they resolve the dotted path segment. Whereas, given the same initial URI, IE would do the following:
B.1. http://example.com/a/b//../
B.2. http://example.com/a/b/
IE simply resolves the dotted path segment against the empty path segment and removes them both. So, how did I resolve this bug? As "By Design" of course!

The URI RFC allows path segments of zero length and does not assign them any special meaning. So generic user agents that intend to work on the web must not treat an empty path segment any different from a path segment with some text in it. In the case above IE is doing the correct thing.

That's the case for generic user agents, however servers may decide that a URI with an empty path segment returns the same resource as a the same URI without that empty path segment. Essentially they can decide to ignore empty path segments. Both IIS and Apache work this way and thus return the same resource for the following URIs:

http://exmaple.com/foo//bar///baz
http://example.com/foo/bar/baz
The issue for UWS is that it removes empty path segments before resolving dotted path segments. It must follow normal URI procedure before applying its own additional rules for empty path segments. Not doing that means they end up violating URI equivalency rules: URIs (A.1) and (B.2) are equivalent but UWS will not return the same resource for them.
PermalinkCommentsuser agent url ie uri technical web browser

[html5] Web Workers: Race-Condition setting onmessage handler?

2011 Sep 20, 7:17There's no race between posting to a web worker and the web worker setting up its message handler as long as the web worker sets its message handler in the first sync. block of code that runs in the web worker: "Basically, once the initial worker script returns, the worker's port is enabled and the normal message port event delivery mechanism kicks in (including dropping unhandled messages on the floor)."PermalinkCommentstechnical web-worker webbrowser programming postMessage

Command line for finding missing URLACTIONs

2011 May 28, 11:00

I wanted to ensure that my switch statement in my implementation of IInternetSecurityManager::ProcessURLAction had a case for every possible documented URLACTION. I wrote the following short command line sequence to see the list of all URLACTIONs in the SDK header file not found in my source file:

grep URLACTION urlmon.idl | sed 's/.*\(URLACTION[a-zA-Z0-9_]*\).*/\1/g;' | sort | uniq > allURLACTIONs.txt
grep URLACTION MySecurityManager.cpp | sed 's/.*\(URLACTION[a-zA-Z0-9_]*\).*/\1/g;' | sort | uniq > myURLACTIONs.txt
comm -23 allURLACTIONs.txt myURLACTIONs.txt
I'm not a sed expert so I had to read the sed documentation, and I heard about comm from Kris Kowal's blog which happilly was in the Win32 GNU tools pack I already run.

But in my effort to learn and use PowerShell I found the following similar command line:

diff 
(more urlmon.idl | %{ if ($_ -cmatch "URLACTION[a-zA-Z0-9_]*") { $matches[0] } } | sort -uniq)
(more MySecurityManager.cpp | %{ if ($_ -cmatch "URLACTION[a-zA-Z0-9_]*") { $matches[0] } } | sort -uniq)
In the PowerShell version I can skip the temporary files which is nice. 'diff' is mapped to 'compare-object' which seems similar to comm but with no parameters to filter out the different streams (although this could be done more verbosely with the ?{ } filter syntax). In PowerShell uniq functionality is built into sort. The builtin -cmatch operator (c is for case sensitive) to do regexp is nice plus the side effect of generating the $matches variable with the regexp results.
PermalinkCommentspowershell tool cli technical command line

Capturing HTTPS with FiddlerCore

2011 Apr 6, 10:00

I used FiddlerCore in GeolocMock to edit HTTPS responses and ran into two stumbling blocks that I'll document here. The first is that I didn't check if the Fiddler root cert existed or was installed, which of course is necessary to edit HTTPS traffic. The following is my code where I check for the certs.

    if (!Fiddler.CertMaker.rootCertExists())
{
if (!Fiddler.CertMaker.createRootCert())
{
throw new Exception("Unable to create cert for FiddlerCore.");
}
}

if (!Fiddler.CertMaker.rootCertIsTrusted())
{
if (!Fiddler.CertMaker.trustRootCert())
{
throw new Exception("Unable to install FiddlerCore's cert.");
}
}

The second problem I had (which would have been solved had I read all the sample code first) was that my changes weren't being applied. In my app I only need the BeforeResponse but in order to modify the response I must also sign up for the BeforeRequest event and mark the bBufferResponse flag on the session before the response comes back. For example:

    Fiddler.FiddlerApplication.BeforeRequest += new SessionStateHandler(FiddlerApplication_BeforeRequest);
Fiddler.FiddlerApplication.BeforeResponse += new SessionStateHandler(FiddlerApplication_BeforeResponse);
...
private void FiddlerApplication_BeforeRequest(Session oSession)
{
if (IsInterestingSession(oSession))
{
oSession.bBufferResponse = true;
}
}
PermalinkCommentshttp fiddler technical https geolocmock programming fiddlercore

Bluetooth Glove: Talk to the Hand!

2011 Mar 7, 9:13Instructions for a DIY bluetooth glove with mic in pinky and earpiece in thumb.
PermalinkCommentsbluetooth humor awesome phone diy

Make: Online : Hand lights — Cool Tools contest winner

2010 Sep 14, 2:24Good idea and solves some of the head lamp problems: "...Enter the Hand Lights, a pretty simple and cheap DIY project that puts adjustable lights on your forearms to light whatever is in your hands."PermalinkCommentslight diy hand head-lamp tool

I'm Married!

2010 Jun 12, 2:18

2010_05_Dave and Sarah Wedding_Sarah and Dave Married WalkDid I mention that I got married two weeks ago today on May 29th? Its true! Our wedding was a kind of planning singularity -- all of my planning efforts would get sucked into that day and I couldn't make any plans past that date. But the actual wedding itself was lovely and I didn't feel nearly as stressed out or nervous during the wedding as I did trying to plan for it. I've been gathering wedding photos on our wedding website photos page.

PermalinkCommentswedding photo personal marriage

Kevin Frei @ NWCPP: Exception Handling Cost

2010 May 10, 7:23"Kevin Frei - Exception Hanlding Cost September 2006 meeting of the Northwest C++ Users Group. Discussion of the assembly language cost of exception handling on the x86 Windows and x64 Windows platform"PermalinkCommentsC++ programming language exception microsoft windows performance technical video
Older EntriesNewer Entries Creative Commons License Some rights reserved.