Tag Archives: flash

flash policy service daemon

Sorry it took me so long to post this, but WordPress 2.5 doesn’t seem to like me trying to upload gz/zip files, so I had to upload the source manually.

Well, it’s been months since I promised to post some usable socket policy service code, so I will.

The script here is meant to serve as a good starting point for people whose servers need to allow flash clients to make socket connections. I have not actually used this exact code in a production environment, but I have been using code that is 99% identical for a while now. I am confident that any blatant flaws are the result of simple copy-paste errors as I compiled the package. Please let me know if you find any.

I have however, stress tested the heck out of this service. One instance successfully served up over 16000 policy file requests fed into it as rapidly as I could send them. The same networking code has also handled requests from at least 100 different hosts at roughly the same time.

Everything has been combined into a single cli php script that requires no special installation. Just plop it down on the server and run it as root. It will take care of the rest. The config defaults should be safe, but you probably want to specify them more clearly – just to be safe.

The daemon is made of three classes:

  • Logger – A rudimentary log file management class that I copy from project to project in one form or another. The included version is stripped down from some of the other versions I’ve written, and I’m planning on releasing a more feature-rich version in the future.
  • Daemon – A simple class for daemonizing a process. Adapted and re-adapted countless times from an original php4 class I found on the net a few years ago by some guy named Seth (whose email domain no longer exists).
  • FlashPolicyService – The meat and potatoes, a child of Daemon. Mostly, this is just the requisite networking code and glue to make everything work together.

As with any of my other code, this is licensed under CC Attribution 3.0.


Source code after the jump.
Continue reading flash policy service daemon

flash socket policies update

I’ve been getting a lot of positive feedback recently on the post I made last December on this topic, so it’s probably time to post an update.

Last week, Adobe finally released some help for people who need to provide socket policy services. They’ve got python and perl versions of the socket policy daemon that look like they can run either standalone or through xinetd. They don’t claim that the code is production quality yet… but it’s at least something.

Of course, I released sample PHP code 5 months ago… shrug.

My confederates and I have spent the intervening months sniffing packets, yelling at flash, rewriting daemons, etc… until settling upon a version of the service that appears to function reliably now. I am currently running it on 6 different servers and have seen it successfully handle requests from >100 simultaneous users during stress tests.

The biggest problem with my previous versions of the code was how I handled closing of connections. Previously, I had simply accepted connections and fired off the policy xml without waiting for a request from the client.

This worked 95% of the time over a good net connection, and more like 80% of the time over a poor connection.

The reason it didn’t work consistently was because of weird tcp ordering issues. Connections would be closed out of order, the response would be received before the request was dispatched, etc..

My new version is much more robust and actually waits for flash to submit the request before sending the XML. I consider it release candidate beta quality code and hope to be able to release it later today.


Version 0.9.b is available now.

new flash security policies

So… I am not happy with Adobe right now. With the push of Flash Player 9,0,115,0 “moviestar”, which included such awesome features as H.264 and AAC codec support and improvements to fullscreen mode, they kind of ambushed me with some sweeping changes to their security policy.

I’d been running pre-release nightly builds of the player since 9,0,60,x… and had noticed some strange warnings. Mysterious “Socket Security Error #2048” exceptions that were being thrown at random – even though I was serving an appropriate (for the time) crossdomain.xml file, unexplained timeouts attempting to talk to an xml socket server when I was very clearly not attempting to do any such thing, etc… My regularly repeated attempts to find documentation on what the warnings actually meant proved fruitless. I believe that is because the appropriate document was not actually released to the public until 9,0,115,0 was released.

Now, the bit where they improved the format for crossdomain.xml files doesn’t really affect me one way or the other. I approve of the improvements but could really care less in this case. They don’t really affect anything I’m doing.

The part that really chaps my hide is the fact that they’ve completely redone the way that socket security policies are handled. The important parts:

  • A SWF file may no longer make a socket connection to its own domain without a socket policy file. Prior to version 9,0,115,0, a SWF file was permitted to make socket connections to ports 1024 or greater in its own domain without a policy file.
  • HTTP policy files may no longer be used to authorize socket connections. Prior to version 9,0,115,0, an HTTP policy file, served from the master location of /crossdomain.xml on port 80, could be used to authorize a socket connection to any port 1024 or greater on the same host.

That’s right. Your socket policy data can’t live in the sitewide crossdomain.xml file that Apache serves any more.

Flash Player 9,0,115,0 introduces a concept of socket master policy files, which are served from the fixed TCP port number 843.

Socket policy files may be obtained from the same port as a main connection (the socket connection being made by ActionScript, which is authorized by a socket policy file), or from a different port, separate from the main connection. If you opt to serve a socket policy file from the same port as a main connection, the server listening on that port must understand socket policy file requests (which are indicated by a transmission of from Flash Player), and must respond differently for policy file requests and main connection requests.

  • When a SWF file attempts to make a socket connection, even to its own domain, Flash Player will first attempt to contact port 843 to see if the host is serving a socket master policy file.

So… regardless of whether you’re even using a custom port 843 client, the Flash Player is going to try to hit it. What if your firewall doesn’t allow/route traffic to sub-1024 ports w/o special configuration? What if you don’t have the access to bind to a sub-1024 port and can’t rewrite your other server process to serve the policy data on its port?

  • Socket meta-policies can only be declared in a socket master policy file. The syntax is the same as for declaring a meta-policy in an URL master policy file, using the <site-control> tag. Socket meta-policies cannot be declared in HTTP response headers, as HTTP is not involved.

This implies that you can’t even tell apache to listen to port 843 and serve up the data. You HAVE to either maintain a separate server process specifically for the purpose of serving this policy data, or you have to edit the process that SWF’s are connecting to and make them serve the data..

As of the time of this writing (10 days after moviestar’s release), they have yet to release promised help on how to deploy a solution to these new changes. Granted, the one article they did release explains what needs to be done in high level terms. It was sufficient to help me out. I wrote a server that simply listens on port 843 and spews the required xml. But… I’d have really appreciated specific examples, and I suspect plenty of people would appreciate drop-in solutions to the issue.

A 5-minute skeleton implementation (not recommended for production use by any means) written as a PHP cli script might look something like this:

// make sure everything launches correctly
if( posix_getuid() != 0 )
die( “You must run this script as root.\\\n” );

$sock = @socket_create( AF_INET, SOCK_STREAM, SOL_TCP );
if( !$sock )
die( “Unable to create socket.\\\n” );

$succ = @socket_bind( $sock, “”, 843 );
if( !$succ )
die( “Unable to bind to port 843.\\\n” );

$succ = @socket_listen( $sock );
if( !$succ )
die( “Unable to start listening.\\\n” );

// start serving policies
while( true ) {
$r = $w = $e = array( $sock );
if( @socket_select( $r, $w, $e, null ) !== false ) {
$conn = @socket_accept( $sock );
if( $conn !== false ) {
// somebody connected, just dump the xml and close
socket_write( $conn, $policy_file );
socket_close( $conn );
} else {
echo “socket_accept() failed?\\\n”;
} else {
echo “socket_select() failed?\\\n”;
}// end: listen forever

// clean up
socket_close( $sock );
I’ll try to make my production version of this a bit more suitable for public consumption and release it as soon as I can.

The random #2048 security errors continue, despite having deployed my port 843 policy xml server. Granted, they happen less than before… but they still happen. And even when my policy server isn’t running, the errors aren’t thrown 100% of the time. This just baffles me. If they were consistent, that would be one thing. But when you get a security error 1 time in 20… that’s not security, that’s not even a lame deterrent. It’s just incentive to hammer the same port over and over again until something finally gives.

Now, I admit that I could be wrong here… but I’ve re-re-read the documentation on these policies a few times now, and cannot find any reason for the behaviors I’m seeing.


On April 22nd, 2008, I released a much better, much more reliable version of this daemon. Head over there for more details and source code.

udp in flash

This is a memo to myself more than anything else… but there has got to be a way to use UDP from a SWF running through your web browser.

Pieces of the puzzle:

  • Flash 9 has binary TCP socket support, but no UDP.
  • Standalone projectors like MDM Zinc can add UDP capabilities to the mix.
  • A projector and a SWF in the browser can communicate together very happily via the LocalConnection interface.

But web browsers are understandably reluctant to download and run a 3rd party UDP proxy application for you ๐Ÿ˜‰ It’s also not terribly platform independent to require something running in userspace outside of the VM.

Java has UDP support. You could write a UDP proxy in Java that uses a standard local TCP socket to talk to the SWF – both the SWF and the applet would have to load from the same page. Don’t know whether Java’s and Flash’s security policies would allow this sort of behavior… probably not. I know applets have difficulties connecting to anything but the originating server – so they probably can’t listen for traffic on the local host either. And if they can, there’s probably some big security certificate you have to sign in blood and offer to the Sun gods or something…

Of course, the dumb option would be to have a remote TCP->UDP proxy… but that eliminates any sort of performance gain that might have been achieved by using UDP in the first place, so that’s only valid in the weird case where you honestly need to talk to a UDP server for whatever reason and don’t care about the lag.

No, the proxy must run locally, somehow.

as1 swf loader

So I find myself writing a whole bunch of AS1 recently (upgrading another old game). In this case, the project was originally done in a single ginormous FLA file. No separate assets file, no external .as files. We’ve broken lots of timeline code out into source files, but have yet to break any of the assets out. That’s my current project.

I’m actually splitting assets up into several small files and then loading them up into an invisible container clip.

When I started writing the loading code, I forgot that AS1 doesn’t have the MovieClipLoader class. That’s a Flash 7 invention. So, I got to do things the really old fashioned way, by listening to bytes loaded and all that. I figured since it is potentially a common problem (for those who wind up having to go back into the stone ages, that is), I may as well share the code with folks.

Please note that this code is a skeleton. It does not do a whole lot as it is. It just gives you a starting framework to edit to your individual application.

FakeMCL = function( parent, depth ) {
if( !parent )
parent = _root;
this.parent = parent; // parent clip of container
this.loadQueue = []; // queue of clips to be loaded
this.container = null; // clip into which all children are loaded
this.init( depth );
};// end: "constructor"

FakeMCL.prototype.init = function( depth ) {
if( !depth )
depth = this.parent.getNextHighestDepth();
// create an invisible container clip at parent._fakemcl
this.container = this.parent.createEmptyMovieClip( "_fakemcl", depth );
this.container._visible = false;
trace("<fakemcl> container "+this.container+" is at depth "+depth);
}// end: init()

FakeMCL.prototype.loadMovie = function( url ) {
this.loadQueue.push( url );
if( !this.loadInterval ) {
trace("<fakemcl> starting interval");
// try to tick once every 25ms (that’s once per frame at 40fps), we’re
// probably not running that fast, so it will just execute once per frame
// NOTE: you can (and might want to) throttle this back
this.loadInterval = setInterval( this.onInterval, 25, this );
}// end: start interval
}// end: loadMovie()

FakeMCL.prototype.onInterval = function( mcl ) {
// stop iterating if we’re completely out of clips to load
if( !mcl.loadQueue.length && !mcl.loadingClip ) {
trace("<fakemcl> queue is empty");
clearInterval( mcl.loadInterval );
// NOTE: you might want to do something here now that the whole queue is loaded
}// end: queue is empty
// start loading a clip if we aren’t already
if( !mcl.loadingClip ) {
var clipURL = mcl.loadQueue.shift();
var instanceName = "_"+clipURL.substr( 0, clipURL.indexOf(".") );
trace("<fakemcl> loading "+clipURL+" ("+instanceName+")");
mcl.loadingClip = mcl.container.createEmptyMovieClip( instanceName, mcl.container.getNextHighestDepth() );
mcl.loadingClip.loadMovie( clipURL );
// NOTE: clip init goes here
}// end: not loading anything
else {
// check status of currently loading movie
var percentLoaded = mcl.loadingClip.getBytesLoaded() / mcl.loadingClip.getBytesTotal();
trace("<fakemcl> loaded "+mcl.loadingClip.getBytesLoaded()+"/"+mcl.loadingClip.getBytesTotal());
if( percentLoaded >= 1.0 && mcl.loadingClip.getBytesTotal() ) {
// we’re done loading
trace("<fakemcl> done, "+mcl.loadingClip);
mcl.loadingClip = null;
// NOTE: callback for individual clip loading goes here
}// end: currently loading
}// end: onInterval()

Again, this is skeleton code and isn’t terribly useful as is. I’ve put some notes in the code where you might want to do more interesting things to adapt the durned thing to your application. Also, feel free to yoink the trace statements, they can get awful spammy ๐Ÿ˜‰

This skeleton supports queuing up a whole list of swf’s for loading, but in actual use, it is probably going to be more useful for you to just load one swf at a time. Shrug.


Put the following code on a frame of your timeline:
#include "FakeMCL.as"

var mcl = new FakeMCL( this, 10 );
And hopefully, you’ll get some output like this:
<fakemcl> container _level0._fakemcl is at depth 10
<fakemcl> starting interval
<fakemcl> loading fish.swf (_fish)
<fakemcl> loaded 0/-1
<fakemcl> loaded 1465744/1465744
<fakemcl> done, _level0._fakemcl._fish
<fakemcl> loading bird.swf (_bird)
<fakemcl> loaded 1427856/1427856
<fakemcl> done, _level0._fakemcl._bird
<fakemcl> queue is empty
When all is done running, you’ve got those clips at _fakemcl._bird and _fakemcl._fish that you can toy with however you need. Chances are, you probably want to know when the loading is actually done, however. That’ll take some editing of this code. Put a stop() on the frame you call FakeMCL.loadMovie() from and then put “mcl.parent.play()” in the load complete block, etc…

open flash happiness

This morning, Adobe announced that they are open sourcing Flex (under the MPL). Their FAQ is pretty informative.

Slashdot‘s gallery of morons is lambasting the announcement as just a PR stunt, as a scared response to Microsoft’s recent announcement of WPF/E Silverlight, and likely as a joint conspiracy between Sony, the Bush administration, and Jack Thomspson to steal their mp3z. But you can’t make some idiots happy, no matter what you do.

I couldn’t be happier with this news. It’s a major win for not only Adobe (who gets fresh innovation and lots of good karma out of the deal) but also for the community in general. Flex is a tremendously powerful platform, it’s a serious platform. While Flash is just for pretty pictures, Flex is for content. It is fast to develop for, it is more reliable than AJAX (since it runs under a consistent VM that doesn’t change from browser to browser or OS to OS), and it looks better and runs faster than Java Swing (well, it doesn’t take much to look better than swing, or be faster than swing, but Flex does both, at the same time, and does it for less effort on the developer’s end).

Fact of the matter is, Adobe is open sourcing their compiler, their debugger, and their core language api. Really, the only thing they’re not opening up is the VM itself… but they’ve already done some of that. Adobe is also keeping control of the project, it’ll be hosted on their servers, etc… So between that, and their keeping the Flash 9 player closed source, the platform isn’t in danger of rapid death spiral type unreliability.

Ted Patrick has more details on his blog. Namely, the release schedule:

Starting Summer 2007 we will be posting daily builds of the Flex SDK and providing open access to a bug database online. The Flex community will have direct access to the same tools developers use internally to manage Flex quality and this will allow the Flex community to improve the quality of Flex directly.

In December of 2007 after the release of รขโ‚ฌล“Moxieรขโ‚ฌย (aka Flex 3) we will be posting all software assets into a public Subversion repository for public access. During this transition period we will be clarifying governance on the Flex SDK and how contributions will be handled in phases.

Naturally, I’ve got more questions about this, but… I’m too excited to care at the moment.

I have the sinking suspicion that as one of the few groups on the planet to adopt Flex 2 as a development platform from its launch, a few of my comrades and I will be among the first to actually contribute code to the new Flex 3 project. We may none of us be compiler jocks… but I tell you what. We are going to fix a few broken/clunky UI classes and are gonna give the native data classes a good jolt of needed features.

I giggle at the thought of how much work DataGrid is going to see the first month ๐Ÿ˜‰