global.settings = '';
global.resume = '';
+var pf = require('policyfile').createServer()
+pf.listen(8002);
+
var http = require('http'),
WebSocketRequest = require('websocket').request,
ws = require('websocket-server'),
--- /dev/null
+node_modules
\ No newline at end of file
--- /dev/null
+Copyright (c) 2011 Arnout Kazemier,3rd-Eden
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
--- /dev/null
+doc:
+ dox --title "FlashPolicyFileServer" lib/* > doc/index.html
+
+test:
+ expresso -I lib $(TESTFLAGS) tests/*.test.js
+
+.PHONY: test doc
\ No newline at end of file
--- /dev/null
+## LOL, WUT?
+It basically allows you to allow or disallow Flash Player sockets from accessing your site.
+
+## Installation
+
+```bash
+npm install policyfile
+```
+## Usage
+
+The server is based on the regular and know `net` and `http` server patterns. So it you can just listen
+for all the events that a `net` based server emits etc. But there is one extra event, the `connect_failed`
+event. This event is triggered when we are unable to listen on the supplied port number.
+
+### createServer
+Creates a new server instance and accepts 2 optional arguments:
+
+- `options` **Object** Options to configure the server instance
+ - `log` **Boolean** Enable logging to STDOUT and STDERR (defaults to true)
+- `origins` **Array** An Array of origins that are allowed by the server (defaults to *:*)
+
+```js
+var pf = require('policyfile');
+pf.createServer();
+pf.listen();
+```
+
+#### server.listen
+Start listening on the server and it takes 3 optional arguments
+
+- `port` **Number** On which port number should we listen? (defaults to 843, which is the first port number the FlashPlayer checks)
+- `server` **Server** A http server, if we are unable to accept requests or run the server we can also answer the policy requests inline over the supplied HTTP server.
+- `callback` **Function** A callback function that is called when listening to the server was successful.
+
+```js
+var pf = require('policyfile');
+pf.createServer();
+pf.listen(1337, function(){
+ console.log(':3 yay')
+});
+```
+
+Changing port numbers can be handy if you do not want to run your server as root and have port 843 forward to a non root port number (aka a number above 1024).
+
+```js
+var pf = require('policyfile')
+ , http = require('http');
+
+server = http.createServer(function(q,r){r.writeHead(200);r.end('hello world')});
+server.listen(80);
+
+pf.createServer();
+pf.listen(1337, server, function(){
+ console.log(':3 yay')
+});
+```
+
+Support for serving inline requests over a existing HTTP connection as the FlashPlayer will first check port 843, but if it's unable to get a response there it will send a policy file request over port 80, which is usually your http server.
+
+#### server.add
+Adds more origins to the policy file you can add as many arguments as you like.
+
+```js
+var pf = require('policyfile');
+pf.createServer(['google.com:80']);
+pf.listen();
+pf.add('blog.3rd-Eden.com:80', 'blog.3rd-Eden.com:8080'); // now has 3 origins
+```
+
+#### server.add
+Adds more origins to the policy file you can add as many arguments as you like.
+
+```js
+var pf = require('policyfile');
+pf.createServer(['blog.3rd-Eden.com:80', 'blog.3rd-Eden.com:8080']);
+pf.listen();
+pf.remove('blog.3rd-Eden.com:8080'); // only contains the :80 version now
+```
+
+#### server.close
+Shuts down the server
+
+```js
+var pf = require('policyfile');
+pf.createServer();
+pf.listen();
+pf.close(); // OH NVM.
+```
+
+## API
+http://3rd-eden.com/FlashPolicyFileServer/
+
+## Examples
+See https://github.com/3rd-Eden/FlashPolicyFileServer/tree/master/examples for examples
+
+## Licence
+
+MIT see LICENSE file in the repository
\ No newline at end of file
--- /dev/null
+<html>
+ <head>
+ <title>FlashPolicyFileServer</title>
+ <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
+ <style>body {
+ margin: 0;
+ padding: 0;
+ font: 14px/1.5 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif;
+ color: #252519;
+}
+a {
+ color: #252519;
+}
+a:hover {
+ text-decoration: underline;
+ color: #19469D;
+}
+p {
+ margin: 12px 0;
+}
+h1, h2, h3 {
+ margin: 0;
+ padding: 0;
+}
+table#source {
+ width: 100%;
+ border-collapse: collapse;
+}
+table#source td:first-child {
+ padding: 30px 40px 30px 40px;
+ vertical-align: top;
+}
+table#source td:first-child,
+table#source td:first-child pre {
+ width: 450px;
+}
+table#source td:last-child {
+ padding: 30px 0 30px 40px;
+ border-left: 1px solid #E5E5EE;
+ background: #F5F5FF;
+}
+table#source tr {
+ border-bottom: 1px solid #E5E5EE;
+}
+table#source tr.filename {
+ padding-top: 40px;
+ border-top: 1px solid #E5E5EE;
+}
+table#source tr.filename td:first-child {
+ text-transform: capitalize;
+}
+table#source tr.filename td:last-child {
+ font-size: 12px;
+}
+table#source tr.filename h2 {
+ margin: 0;
+ padding: 0;
+ cursor: pointer;
+}
+table#source tr.code h1,
+table#source tr.code h2,
+table#source tr.code h3 {
+ margin-top: 30px;
+ font-family: "Lucida Grande", "Helvetica Nueue", Arial, sans-serif;
+ font-size: 18px;
+}
+table#source tr.code h2 {
+ font-size: 16px;
+}
+table#source tr.code h3 {
+ font-size: 14px;
+}
+table#source tr.code ul {
+ margin: 15px 0 15px 35px;
+ padding: 0;
+}
+table#source tr.code ul li {
+ margin: 0;
+ padding: 1px 0;
+}
+table#source tr.code ul li p {
+ margin: 0;
+ padding: 0;
+}
+table#source tr.code td:first-child pre {
+ padding: 20px;
+}
+#ribbon {
+ position: fixed;
+ top: 0;
+ right: 0;
+}
+code .string { color: #219161; }
+code .regexp { color: #219161; }
+code .keyword { color: #954121; }
+code .number { color: #19469D; }
+code .comment { color: #bbb; }
+code .this { color: #19469D; }</style>
+ <script>
+ $(function(){
+ $('tr.code').hide();
+ $('tr.filename').toggle(function(){
+ $(this).nextUntil('.filename').fadeIn();
+ }, function(){
+ $(this).nextUntil('.filename').fadeOut();
+ });
+ });
+ </script>
+ </head>
+ <body>
+<table id="source"><tbody><tr><td><h1>FlashPolicyFileServer</h1></td><td></td></tr><tr class="filename"><td><h2 id="lib/server.js"><a href="#">server</a></h2></td><td>lib/server.js</td></tr><tr class="code">
+<td class="docs">
+<p>Module dependencies and cached references.
+ </p>
+</td>
+<td class="code">
+<pre><code><span class="keyword">var</span> <span class="variable">slice</span> = <span class="class">Array</span>.<span class="variable">prototype</span>.<span class="variable">slice</span>
+ , <span class="variable">net</span> = <span class="variable">require</span>(<span class="string">'net'</span>);</code></pre>
+</td>
+</tr>
+<tr class="code">
+<td class="docs">
+<p>The server that does the Policy File severing</p>
+
+<h2>Options</h2>
+
+<ul><li><code>log</code> false or a function that can output log information, defaults to console.log?</li></ul>
+
+<h2></h2>
+
+<ul><li><p><strong>param</strong>: <em>Object</em> options Options to customize the servers functionality.</p></li><li><p><strong>param</strong>: <em>Array</em> origins The origins that are allowed on this server, defaults to <code>*:*</code>.</p></li><li><p><strong>api</strong>: <em>public</em></p></li></ul>
+</td>
+<td class="code">
+<pre><code><span class="keyword">function</span> <span class="class">Server</span> (<span class="variable">options</span>, <span class="variable">origins</span>) {
+ <span class="keyword">var</span> <span class="variable">me</span> = <span class="this">this</span>;
+
+ <span class="this">this</span>.<span class="variable">origins</span> = <span class="variable">origins</span> || [<span class="string">'*:*'</span>];
+ <span class="this">this</span>.<span class="variable">port</span> = <span class="number integer">843</span>;
+ <span class="this">this</span>.<span class="variable">log</span> = <span class="variable">console</span>.<span class="variable">log</span>;
+
+ <span class="comment">// merge `this` with the options</span>
+ <span class="class">Object</span>.<span class="variable">keys</span>(<span class="variable">options</span>).<span class="variable">forEach</span>(<span class="keyword">function</span> (<span class="variable">key</span>) {
+ <span class="variable">me</span>[<span class="variable">key</span>] &<span class="variable">amp</span>;&<span class="variable">amp</span>; (<span class="variable">me</span>[<span class="variable">key</span>] = <span class="variable">options</span>[<span class="variable">key</span>])
+ });
+
+ <span class="comment">// create the net server</span>
+ <span class="this">this</span>.<span class="variable">socket</span> = <span class="variable">net</span>.<span class="variable">createServer</span>(<span class="keyword">function</span> <span class="variable">createServer</span> (<span class="variable">socket</span>) {
+ <span class="variable">socket</span>.<span class="variable">on</span>(<span class="string">'error'</span>, <span class="keyword">function</span> <span class="variable">socketError</span> () {
+ <span class="variable">me</span>.<span class="variable">responder</span>.<span class="variable">call</span>(<span class="variable">me</span>, <span class="variable">socket</span>);
+ });
+
+ <span class="variable">me</span>.<span class="variable">responder</span>.<span class="variable">call</span>(<span class="variable">me</span>, <span class="variable">socket</span>);
+ });
+
+ <span class="comment">// Listen for errors as the port might be blocked because we do not have root priv.</span>
+ <span class="this">this</span>.<span class="variable">socket</span>.<span class="variable">on</span>(<span class="string">'error'</span>, <span class="keyword">function</span> <span class="variable">serverError</span> (<span class="variable">err</span>) {
+ <span class="comment">// Special and common case error handling</span>
+ <span class="keyword">if</span> (<span class="variable">err</span>.<span class="variable">errno</span> == <span class="number integer">13</span>) {
+ <span class="variable">me</span>.<span class="variable">log</span> &<span class="variable">amp</span>;&<span class="variable">amp</span>; <span class="variable">me</span>.<span class="variable">log</span>(
+ <span class="string">'Unable to listen to port `'</span> + <span class="variable">me</span>.<span class="variable">port</span> + <span class="string">'` as your Node.js instance does not have root privileges. '</span> +
+ (
+ <span class="variable">me</span>.<span class="variable">server</span>
+ ? <span class="string">'The Flash Policy File requests will only be served inline over the supplied HTTP server. Inline serving is slower than a dedicated server instance.'</span>
+ : <span class="string">'No fallback server supplied, we will be unable to answer Flash Policy File requests.'</span>
+ )
+ );
+
+ <span class="variable">me</span>.<span class="variable">emit</span>(<span class="string">'connect_failed'</span>, <span class="variable">err</span>);
+ <span class="variable">me</span>.<span class="variable">socket</span>.<span class="variable">removeAllListeners</span>();
+ <span class="keyword">delete</span> <span class="variable">me</span>.<span class="variable">socket</span>;
+ } <span class="keyword">else</span> {
+ <span class="variable">me</span>.<span class="variable">log</span> &<span class="variable">amp</span>;&<span class="variable">amp</span>; <span class="variable">me</span>.<span class="variable">log</span>(<span class="string">'FlashPolicyFileServer received an error event:\n'</span> + (<span class="variable">err</span>.<span class="variable">message</span> ? <span class="variable">err</span>.<span class="variable">message</span> : <span class="variable">err</span>));
+ }
+ });
+
+ <span class="this">this</span>.<span class="variable">socket</span>.<span class="variable">on</span>(<span class="string">'timeout'</span>, <span class="keyword">function</span> <span class="variable">serverTimeout</span> () {});
+ <span class="this">this</span>.<span class="variable">socket</span>.<span class="variable">on</span>(<span class="string">'close'</span>, <span class="keyword">function</span> <span class="variable">serverClosed</span> (<span class="variable">err</span>) {
+ <span class="variable">err</span> &<span class="variable">amp</span>;&<span class="variable">amp</span>; <span class="variable">me</span>.<span class="variable">log</span> &<span class="variable">amp</span>;&<span class="variable">amp</span>; <span class="variable">me</span>.<span class="variable">log</span>(<span class="string">'Server closing due to an error: \n'</span> + (<span class="variable">err</span>.<span class="variable">message</span> ? <span class="variable">err</span>.<span class="variable">message</span> : <span class="variable">err</span>));
+
+ <span class="keyword">if</span> (<span class="variable">me</span>.<span class="variable">server</span>) {
+ <span class="comment">// Remove the inline policy listener if we close down</span>
+ <span class="comment">// but only when the server was `online` (see listen prototype)</span>
+ <span class="keyword">if</span> (<span class="variable">me</span>.<span class="variable">server</span>[<span class="string">'@'</span>] &<span class="variable">amp</span>;&<span class="variable">amp</span>; <span class="variable">me</span>.<span class="variable">server</span>.<span class="variable">online</span>) {
+ <span class="variable">me</span>.<span class="variable">server</span>.<span class="variable">removeListener</span>(<span class="string">'connection'</span>, <span class="variable">me</span>.<span class="variable">server</span>[<span class="string">'@'</span>]);
+ }
+
+ <span class="comment">// not online anymore</span>
+ <span class="keyword">delete</span> <span class="variable">me</span>.<span class="variable">server</span>.<span class="variable">online</span>;
+ }
+ });
+
+ <span class="comment">// Compile the initial `buffer`</span>
+ <span class="this">this</span>.<span class="variable">compile</span>();
+}</code></pre>
+</td>
+</tr>
+<tr class="code">
+<td class="docs">
+<p>Start listening for requests</p>
+
+<h2></h2>
+
+<ul><li><p><strong>param</strong>: <em>Number</em> port The port number it should be listening to.</p></li><li><p><strong>param</strong>: <em>Server</em> server A HTTP server instance, this will be used to listen for inline requests</p></li><li><p><strong>param</strong>: <em>Function</em> cb The callback needs to be called once server is ready</p></li><li><p><strong>api</strong>: <em>public</em></p></li></ul>
+</td>
+<td class="code">
+<pre><code><span class="class">Server</span>.<span class="variable">prototype</span>.<span class="variable">listen</span> = <span class="keyword">function</span> <span class="variable">listen</span> (<span class="variable">port</span>, <span class="variable">server</span>, <span class="variable">cb</span>){
+ <span class="keyword">var</span> <span class="variable">me</span> = <span class="this">this</span>
+ , <span class="variable">args</span> = <span class="variable">slice</span>.<span class="variable">call</span>(<span class="variable">arguments</span>, <span class="number integer">0</span>)
+ , <span class="variable">callback</span>;
+
+ <span class="comment">// assign the correct vars, for flexible arguments</span>
+ <span class="variable">args</span>.<span class="variable">forEach</span>(<span class="keyword">function</span> <span class="variable">args</span> (<span class="variable">arg</span>){
+ <span class="keyword">var</span> <span class="variable">type</span> = <span class="keyword">typeof</span> <span class="variable">arg</span>;
+
+ <span class="keyword">if</span> (<span class="variable">type</span> === <span class="string">'number'</span>) <span class="variable">me</span>.<span class="variable">port</span> = <span class="variable">arg</span>;
+ <span class="keyword">if</span> (<span class="variable">type</span> === <span class="string">'function'</span>) <span class="variable">callback</span> = <span class="variable">arg</span>;
+ <span class="keyword">if</span> (<span class="variable">type</span> === <span class="string">'object'</span>) <span class="variable">me</span>.<span class="variable">server</span> = <span class="variable">arg</span>;
+ });
+
+ <span class="keyword">if</span> (<span class="this">this</span>.<span class="variable">server</span>) {
+
+ <span class="comment">// no one in their right mind would ever create a `@` prototype, so Im just gonna store</span>
+ <span class="comment">// my function on the server, so I can remove it later again once the server(s) closes</span>
+ <span class="this">this</span>.<span class="variable">server</span>[<span class="string">'@'</span>] = <span class="keyword">function</span> <span class="variable">connection</span> (<span class="variable">socket</span>) {
+ <span class="variable">socket</span>.<span class="variable">once</span>(<span class="string">'data'</span>, <span class="keyword">function</span> <span class="variable">requestData</span> (<span class="variable">data</span>) {
+ <span class="comment">// if it's a Flash policy request, and we can write to the </span>
+ <span class="keyword">if</span> (
+ <span class="variable">data</span>
+ &<span class="variable">amp</span>;&<span class="variable">amp</span>; <span class="variable">data</span>[<span class="number integer">0</span>] === <span class="number integer">60</span>
+ &<span class="variable">amp</span>;&<span class="variable">amp</span>; <span class="variable">data</span>.<span class="variable">toString</span>() === <span class="string">'<policy-file-request/>\0'</span>
+ &<span class="variable">amp</span>;&<span class="variable">amp</span>; <span class="variable">socket</span>
+ &<span class="variable">amp</span>;&<span class="variable">amp</span>; (<span class="variable">socket</span>.<span class="variable">readyState</span> === <span class="string">'open'</span> || <span class="variable">socket</span>.<span class="variable">readyState</span> === <span class="string">'writeOnly'</span>)
+ ){
+ <span class="comment">// send the buffer</span>
+ <span class="keyword">try</span> { <span class="variable">socket</span>.<span class="variable">end</span>(<span class="variable">me</span>.<span class="variable">buffer</span>); }
+ <span class="keyword">catch</span> (<span class="variable">e</span>) {}
+ }
+ });
+ };
+
+ <span class="comment">// attach it</span>
+ <span class="this">this</span>.<span class="variable">server</span>.<span class="variable">on</span>(<span class="string">'connection'</span>, <span class="this">this</span>.<span class="variable">server</span>[<span class="string">'@'</span>]);
+ }
+
+ <span class="comment">// We add a callback method, so we can set a flag for when the server is `enabled` or `online`.</span>
+ <span class="comment">// this flag is needed because if a error occurs and the we cannot boot up the server the</span>
+ <span class="comment">// fallback functionality should not be removed during the `close` event</span>
+ <span class="this">this</span>.<span class="variable">port</span> &<span class="variable">gt</span>;= <span class="number integer">0</span> &<span class="variable">amp</span>;&<span class="variable">amp</span>; <span class="this">this</span>.<span class="variable">socket</span>.<span class="variable">listen</span>(<span class="this">this</span>.<span class="variable">port</span>, <span class="keyword">function</span> <span class="variable">serverListening</span> () {
+ <span class="variable">me</span>.<span class="variable">socket</span>.<span class="variable">online</span> = <span class="variable">true</span>;
+ <span class="keyword">if</span> (<span class="variable">callback</span>) {
+ <span class="variable">callback</span>.<span class="variable">call</span>(<span class="variable">me</span>);
+ <span class="variable">callback</span> = <span class="variable">undefined</span>;
+ }
+ });
+
+ <span class="keyword">return</span> <span class="this">this</span>;
+};</code></pre>
+</td>
+</tr>
+<tr class="code">
+<td class="docs">
+<p>Adds a new origin to the Flash Policy File.</p>
+
+<h2></h2>
+
+<ul><li><p><strong>param</strong>: <em>Arguments</em> The origins that need to be added.</p></li><li><p><strong>api</strong>: <em>public</em></p></li></ul>
+</td>
+<td class="code">
+<pre><code><span class="class">Server</span>.<span class="variable">prototype</span>.<span class="variable">add</span> = <span class="keyword">function</span> <span class="variable">add</span>(){
+ <span class="keyword">var</span> <span class="variable">args</span> = <span class="variable">slice</span>.<span class="variable">call</span>(<span class="variable">arguments</span>, <span class="number integer">0</span>)
+ , <span class="variable">i</span> = <span class="variable">args</span>.<span class="variable">length</span>;
+
+ <span class="comment">// flag duplicates</span>
+ <span class="keyword">while</span> (<span class="variable">i</span>--) {
+ <span class="keyword">if</span> (<span class="this">this</span>.<span class="variable">origins</span>.<span class="variable">indexOf</span>(<span class="variable">args</span>[<span class="variable">i</span>]) &<span class="variable">gt</span>;= <span class="number integer">0</span>){
+ <span class="variable">args</span>[<span class="variable">i</span>] = <span class="keyword">null</span>;
+ }
+ }
+
+ <span class="comment">// Add all the arguments to the array</span>
+ <span class="comment">// but first we want to remove all `falsy` values from the args</span>
+ <span class="class">Array</span>.<span class="variable">prototype</span>.<span class="variable">push</span>.<span class="variable">apply</span>(
+ <span class="this">this</span>.<span class="variable">origins</span>
+ , <span class="variable">args</span>.<span class="variable">filter</span>(<span class="keyword">function</span> <span class="variable">filter</span> (<span class="variable">value</span>) {
+ <span class="keyword">return</span> !!<span class="variable">value</span>;
+ })
+ );
+
+ <span class="this">this</span>.<span class="variable">compile</span>();
+ <span class="keyword">return</span> <span class="this">this</span>;
+};</code></pre>
+</td>
+</tr>
+<tr class="code">
+<td class="docs">
+<p>Removes a origin from the Flash Policy File.</p>
+
+<h2></h2>
+
+<ul><li><p><strong>param</strong>: <em>String</em> origin The origin that needs to be removed from the server</p></li><li><p><strong>api</strong>: <em>public</em></p></li></ul>
+</td>
+<td class="code">
+<pre><code><span class="class">Server</span>.<span class="variable">prototype</span>.<span class="variable">remove</span> = <span class="keyword">function</span> <span class="variable">remove</span> (<span class="variable">origin</span>){
+ <span class="keyword">var</span> <span class="variable">position</span> = <span class="this">this</span>.<span class="variable">origins</span>.<span class="variable">indexOf</span>(<span class="variable">origin</span>);
+
+ <span class="comment">// only remove and recompile if we have a match</span>
+ <span class="keyword">if</span> (<span class="variable">position</span> &<span class="variable">gt</span>; <span class="number integer">0</span>) {
+ <span class="this">this</span>.<span class="variable">origins</span>.<span class="variable">splice</span>(<span class="variable">position</span>, <span class="number integer">1</span>);
+ <span class="this">this</span>.<span class="variable">compile</span>();
+ }
+
+ <span class="keyword">return</span> <span class="this">this</span>;
+};</code></pre>
+</td>
+</tr>
+<tr class="code">
+<td class="docs">
+<p>Closes and cleans up the server</p>
+
+<ul><li><p><strong>api</strong>: <em>public</em></p></li></ul>
+</td>
+<td class="code">
+<pre><code><span class="class">Server</span>.<span class="variable">prototype</span>.<span class="variable">close</span> = <span class="keyword">function</span> <span class="variable">close</span> () {
+ <span class="this">this</span>.<span class="variable">socket</span>.<span class="variable">removeAllListeners</span>();
+ <span class="keyword">try</span> { <span class="this">this</span>.<span class="variable">socket</span>.<span class="variable">close</span>(); }
+ <span class="keyword">catch</span> (<span class="variable">e</span>) {}
+
+ <span class="keyword">return</span> <span class="this">this</span>;
+};</code></pre>
+</td>
+</tr>
+<tr class="code">
+<td class="docs">
+<p>Proxy the event listener requests to the created Net server
+ </p>
+</td>
+<td class="code">
+<pre><code><span class="class">Object</span>.<span class="variable">keys</span>(<span class="variable">process</span>.<span class="class">EventEmitter</span>.<span class="variable">prototype</span>).<span class="variable">forEach</span>(<span class="keyword">function</span> <span class="variable">proxy</span> (<span class="variable">key</span>){
+ <span class="class">Server</span>.<span class="variable">prototype</span>[<span class="variable">key</span>] = <span class="class">Server</span>.<span class="variable">prototype</span>[<span class="variable">key</span>] || <span class="keyword">function</span> () {
+ <span class="keyword">if</span> (<span class="this">this</span>.<span class="variable">socket</span>) {
+ <span class="this">this</span>.<span class="variable">socket</span>[<span class="variable">key</span>].<span class="variable">apply</span>(<span class="this">this</span>.<span class="variable">socket</span>, <span class="variable">arguments</span>);
+ }
+
+ <span class="keyword">return</span> <span class="this">this</span>;
+ };
+});</code></pre>
+</td>
+</tr>
+<tr class="code">
+<td class="docs">
+<p>Creates a new server instance.</p>
+
+<h2></h2>
+
+<ul><li><p><strong>param</strong>: <em>Object</em> options A options object to override the default config</p></li><li><p><strong>param</strong>: <em>Array</em> origins The origins that should be allowed by the server</p></li><li><p><strong>api</strong>: <em>public</em></p></li></ul>
+</td>
+<td class="code">
+<pre><code><span class="variable">exports</span>.<span class="variable">createServer</span> = <span class="keyword">function</span> <span class="variable">createServer</span> (<span class="variable">options</span>, <span class="variable">origins</span>) {
+ <span class="variable">origins</span> = <span class="class">Array</span>.<span class="variable">isArray</span>(<span class="variable">origins</span>)
+ ? <span class="variable">origins</span>
+ : (<span class="class">Array</span>.<span class="variable">isArray</span>(<span class="variable">options</span>) ? <span class="variable">options</span> : <span class="variable">false</span>);
+
+ <span class="variable">options</span> = !<span class="class">Array</span>.<span class="variable">isArray</span>(<span class="variable">options</span>) &<span class="variable">amp</span>;&<span class="variable">amp</span>; <span class="variable">options</span>
+ ? <span class="variable">options</span>
+ : {};
+
+ <span class="keyword">return</span> <span class="keyword">new</span> <span class="class">Server</span>(<span class="variable">options</span>, <span class="variable">origins</span>);
+};</code></pre>
+</td>
+</tr>
+<tr class="code">
+<td class="docs">
+<p>Provide a hook to the original server, so it can be extended if needed.</p>
+
+<h2></h2>
+
+<ul><li><p><strong>type</strong>: <em>Net.Server</em> </p></li></ul>
+</td>
+<td class="code">
+<pre><code><span class="variable">exports</span>.<span class="class">Server</span> = <span class="class">Server</span>;</code></pre>
+</td>
+</tr>
+<tr class="code">
+<td class="docs">
+<p>Module version</p>
+
+<h2></h2>
+
+<ul><li><p><strong>type</strong>: <em>String</em> </p></li></ul>
+</td>
+<td class="code">
+<pre><code><span class="variable">exports</span>.<span class="variable">version</span> = <span class="string">'0.0.5'</span>;
+</code></pre>
+</td>
+</tr> </body>
+</html></tbody></table>
\ No newline at end of file
--- /dev/null
+var http = require('http')
+ , fspfs = require('../');
+
+var server = http.createServer(function(q,r){ r.writeHead(200); r.end(':3') })
+ , flash = fspfs.createServer();
+
+server.listen(8080);
+flash.listen(8081,server);
\ No newline at end of file
--- /dev/null
+var http = require('http')
+ , fspfs = require('../');
+
+var flash = fspfs.createServer();
+flash.listen();
\ No newline at end of file
--- /dev/null
+module.exports = require('./lib/server.js');
\ No newline at end of file
--- /dev/null
+/**
+ * Module dependencies and cached references.
+ */
+
+var slice = Array.prototype.slice
+ , net = require('net');
+
+/**
+ * The server that does the Policy File severing
+ *
+ * Options:
+ * - `log` false or a function that can output log information, defaults to console.log?
+ *
+ * @param {Object} options Options to customize the servers functionality.
+ * @param {Array} origins The origins that are allowed on this server, defaults to `*:*`.
+ * @api public
+ */
+
+function Server (options, origins) {
+ var me = this;
+
+ this.origins = origins || ['*:*'];
+ this.port = 843;
+ this.log = console.log;
+
+ // merge `this` with the options
+ Object.keys(options).forEach(function (key) {
+ me[key] && (me[key] = options[key])
+ });
+
+ // create the net server
+ this.socket = net.createServer(function createServer (socket) {
+ socket.on('error', function socketError () {
+ me.responder.call(me, socket);
+ });
+
+ me.responder.call(me, socket);
+ });
+
+ // Listen for errors as the port might be blocked because we do not have root priv.
+ this.socket.on('error', function serverError (err) {
+ // Special and common case error handling
+ if (err.errno == 13) {
+ me.log && me.log(
+ 'Unable to listen to port `' + me.port + '` as your Node.js instance does not have root privileges. ' +
+ (
+ me.server
+ ? 'The Flash Policy File requests will only be served inline over the supplied HTTP server. Inline serving is slower than a dedicated server instance.'
+ : 'No fallback server supplied, we will be unable to answer Flash Policy File requests.'
+ )
+ );
+
+ me.emit('connect_failed', err);
+ me.socket.removeAllListeners();
+ delete me.socket;
+ } else {
+ me.log && me.log('FlashPolicyFileServer received an error event:\n' + (err.message ? err.message : err));
+ }
+ });
+
+ this.socket.on('timeout', function serverTimeout () {});
+ this.socket.on('close', function serverClosed (err) {
+ err && me.log && me.log('Server closing due to an error: \n' + (err.message ? err.message : err));
+
+ if (me.server) {
+ // Remove the inline policy listener if we close down
+ // but only when the server was `online` (see listen prototype)
+ if (me.server['@'] && me.server.online) {
+ me.server.removeListener('connection', me.server['@']);
+ }
+
+ // not online anymore
+ delete me.server.online;
+ }
+ });
+
+ // Compile the initial `buffer`
+ this.compile();
+}
+
+/**
+ * Start listening for requests
+ *
+ * @param {Number} port The port number it should be listening to.
+ * @param {Server} server A HTTP server instance, this will be used to listen for inline requests
+ * @param {Function} cb The callback needs to be called once server is ready
+ * @api public
+ */
+
+Server.prototype.listen = function listen (port, server, cb){
+ var me = this
+ , args = slice.call(arguments, 0)
+ , callback;
+
+ // assign the correct vars, for flexible arguments
+ args.forEach(function args (arg){
+ var type = typeof arg;
+
+ if (type === 'number') me.port = arg;
+ if (type === 'function') callback = arg;
+ if (type === 'object') me.server = arg;
+ });
+
+ if (this.server) {
+
+ // no one in their right mind would ever create a `@` prototype, so Im just gonna store
+ // my function on the server, so I can remove it later again once the server(s) closes
+ this.server['@'] = function connection (socket) {
+ socket.once('data', function requestData (data) {
+ // if it's a Flash policy request, and we can write to the
+ if (
+ data
+ && data[0] === 60
+ && data.toString() === '<policy-file-request/>\0'
+ && socket
+ && (socket.readyState === 'open' || socket.readyState === 'writeOnly')
+ ){
+ // send the buffer
+ try { socket.end(me.buffer); }
+ catch (e) {}
+ }
+ });
+ };
+
+ // attach it
+ this.server.on('connection', this.server['@']);
+ }
+
+ // We add a callback method, so we can set a flag for when the server is `enabled` or `online`.
+ // this flag is needed because if a error occurs and the we cannot boot up the server the
+ // fallback functionality should not be removed during the `close` event
+ this.port >= 0 && this.socket.listen(this.port, function serverListening () {
+ me.socket.online = true;
+ if (callback) {
+ callback.call(me);
+ callback = undefined;
+ }
+ });
+
+ return this;
+};
+
+/**
+ * Responds to socket connects and writes the compile policy file.
+ *
+ * @param {net.Socket} socket The socket that needs to receive the message
+ * @api private
+ */
+
+Server.prototype.responder = function responder (socket){
+ if (socket && socket.readyState == 'open' && socket.end) {
+ try { socket.end(this.buffer); }
+ catch (e) {}
+ }
+};
+
+/**
+ * Compiles the supplied origins to a Flash Policy File format and stores it in a Node.js Buffer
+ * this way it can be send over the wire without any performance loss.
+ *
+ * @api private
+ */
+
+Server.prototype.compile = function compile (){
+ var xml = [
+ '<?xml version="1.0"?>'
+ , '<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">'
+ , '<cross-domain-policy>'
+ ];
+
+ // add the allow access element
+ this.origins.forEach(function origin (origin){
+ var parts = origin.split(':');
+ xml.push('<allow-access-from domain="' + parts[0] + '" to-ports="'+ parts[1] +'"/>');
+ });
+
+ xml.push('</cross-domain-policy>');
+
+ // store the result in a buffer so we don't have to re-generate it all the time
+ this.buffer = new Buffer(xml.join(''), 'utf8');
+
+ return this;
+};
+
+/**
+ * Adds a new origin to the Flash Policy File.
+ *
+ * @param {Arguments} The origins that need to be added.
+ * @api public
+ */
+
+Server.prototype.add = function add(){
+ var args = slice.call(arguments, 0)
+ , i = args.length;
+
+ // flag duplicates
+ while (i--) {
+ if (this.origins.indexOf(args[i]) >= 0){
+ args[i] = null;
+ }
+ }
+
+ // Add all the arguments to the array
+ // but first we want to remove all `falsy` values from the args
+ Array.prototype.push.apply(
+ this.origins
+ , args.filter(function filter (value) {
+ return !!value;
+ })
+ );
+
+ this.compile();
+ return this;
+};
+
+/**
+ * Removes a origin from the Flash Policy File.
+ *
+ * @param {String} origin The origin that needs to be removed from the server
+ * @api public
+ */
+
+Server.prototype.remove = function remove (origin){
+ var position = this.origins.indexOf(origin);
+
+ // only remove and recompile if we have a match
+ if (position > 0) {
+ this.origins.splice(position, 1);
+ this.compile();
+ }
+
+ return this;
+};
+
+/**
+ * Closes and cleans up the server
+ *
+ * @api public
+ */
+
+Server.prototype.close = function close () {
+ this.socket.removeAllListeners();
+ try { this.socket.close(); }
+ catch (e) {}
+
+ return this;
+};
+
+/**
+ * Proxy the event listener requests to the created Net server
+ */
+
+Object.keys(process.EventEmitter.prototype).forEach(function proxy (key){
+ Server.prototype[key] = Server.prototype[key] || function () {
+ if (this.socket) {
+ this.socket[key].apply(this.socket, arguments);
+ }
+
+ return this;
+ };
+});
+
+/**
+ * Creates a new server instance.
+ *
+ * @param {Object} options A options object to override the default config
+ * @param {Array} origins The origins that should be allowed by the server
+ * @api public
+ */
+exports.createServer = function createServer (options, origins) {
+ origins = Array.isArray(origins)
+ ? origins
+ : (Array.isArray(options) ? options : false);
+
+ options = !Array.isArray(options) && options
+ ? options
+ : {};
+
+ return new Server(options, origins);
+};
+
+/**
+ * Provide a hook to the original server, so it can be extended if needed.
+ *
+ * @type {Net.Server}
+ */
+
+exports.Server = Server;
+
+/**
+ * Module version
+ *
+ * @type {String}
+ */
+
+exports.version = '0.0.5';
--- /dev/null
+{
+ "name": "policyfile",
+ "version": "0.0.5",
+ "author": {
+ "name": "Arnout Kazemier"
+ },
+ "description": "Flash Socket Policy File Server. A server to respond to Flash Socket Policy requests, both inline and through a dedicated server instance.",
+ "main": "index",
+ "keywords": [
+ "flash",
+ "socket",
+ "policy",
+ "file",
+ "server",
+ "Flash Socket Policy File Server",
+ "cross domain"
+ ],
+ "directories": {
+ "lib": "./lib"
+ },
+ "maintainers": [
+ {
+ "name": "Arnout Kazemier",
+ "email": "info@3rd-Eden.com",
+ "url": "http://blog.3rd-Eden.com"
+ }
+ ],
+ "license": {
+ "type": "MIT",
+ "url": "https://github.com/3rd-Eden/FlashPolicyFileServer/blob/master/LICENSE"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/3rd-Eden/FlashPolicyFileServer.git"
+ },
+ "readme": "## LOL, WUT?\nIt basically allows you to allow or disallow Flash Player sockets from accessing your site.\n\n## Installation\n\n```bash\nnpm install policyfile\n```\n## Usage\n\nThe server is based on the regular and know `net` and `http` server patterns. So it you can just listen\nfor all the events that a `net` based server emits etc. But there is one extra event, the `connect_failed`\nevent. This event is triggered when we are unable to listen on the supplied port number.\n\n### createServer\nCreates a new server instance and accepts 2 optional arguments:\n\n- `options` **Object** Options to configure the server instance\n - `log` **Boolean** Enable logging to STDOUT and STDERR (defaults to true)\n- `origins` **Array** An Array of origins that are allowed by the server (defaults to *:*)\n\n```js\nvar pf = require('policyfile');\npf.createServer();\npf.listen();\n```\n\n#### server.listen\nStart listening on the server and it takes 3 optional arguments\n\n- `port` **Number** On which port number should we listen? (defaults to 843, which is the first port number the FlashPlayer checks)\n- `server` **Server** A http server, if we are unable to accept requests or run the server we can also answer the policy requests inline over the supplied HTTP server.\n- `callback` **Function** A callback function that is called when listening to the server was successful.\n\n```js\nvar pf = require('policyfile');\npf.createServer();\npf.listen(1337, function(){\n console.log(':3 yay')\n});\n```\n\nChanging port numbers can be handy if you do not want to run your server as root and have port 843 forward to a non root port number (aka a number above 1024).\n\n```js\nvar pf = require('policyfile')\n , http = require('http');\n\nserver = http.createServer(function(q,r){r.writeHead(200);r.end('hello world')});\nserver.listen(80);\n\npf.createServer();\npf.listen(1337, server, function(){\n console.log(':3 yay')\n});\n```\n\nSupport for serving inline requests over a existing HTTP connection as the FlashPlayer will first check port 843, but if it's unable to get a response there it will send a policy file request over port 80, which is usually your http server.\n\n#### server.add\nAdds more origins to the policy file you can add as many arguments as you like.\n\n```js\nvar pf = require('policyfile');\npf.createServer(['google.com:80']);\npf.listen();\npf.add('blog.3rd-Eden.com:80', 'blog.3rd-Eden.com:8080'); // now has 3 origins\n```\n\n#### server.add\nAdds more origins to the policy file you can add as many arguments as you like.\n\n```js\nvar pf = require('policyfile');\npf.createServer(['blog.3rd-Eden.com:80', 'blog.3rd-Eden.com:8080']);\npf.listen();\npf.remove('blog.3rd-Eden.com:8080'); // only contains the :80 version now\n```\n\n#### server.close\nShuts down the server\n\n```js\nvar pf = require('policyfile');\npf.createServer();\npf.listen();\npf.close(); // OH NVM.\n```\n\n## API\nhttp://3rd-eden.com/FlashPolicyFileServer/\n\n## Examples\nSee https://github.com/3rd-Eden/FlashPolicyFileServer/tree/master/examples for examples\n\n## Licence\n\nMIT see LICENSE file in the repository",
+ "_id": "policyfile@0.0.5",
+ "dist": {
+ "shasum": "addf35d209b6a1071b110aff2294644324885f04"
+ },
+ "_from": "policyfile"
+}
--- /dev/null
+-----BEGIN CERTIFICATE-----
+MIIDXTCCAkWgAwIBAgIJAMUSOvlaeyQHMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV
+BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
+aWRnaXRzIFB0eSBMdGQwHhcNMTAxMTE2MDkzMjQ5WhcNMTMxMTE1MDkzMjQ5WjBF
+MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50
+ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
+CgKCAQEAz+LXZOjcQCJq3+ZKUFabj71oo/ex/XsBcFqtBThjjTw9CVEVwfPQQp4X
+wtPiB204vnYXwQ1/R2NdTQqCZu47l79LssL/u2a5Y9+0NEU3nQA5qdt+1FAE0c5o
+exPimXOrR3GWfKz7PmZ2O0117IeCUUXPG5U8umhDe/4mDF4ZNJiKc404WthquTqg
+S7rLQZHhZ6D0EnGnOkzlmxJMYPNHSOY1/6ivdNUUcC87awNEA3lgfhy25IyBK3QJ
+c+aYKNTbt70Lery3bu2wWLFGtmNiGlQTS4JsxImRsECTI727ObS7/FWAQsqW+COL
+0Sa5BuMFrFIpjPrEe0ih7vRRbdmXRwIDAQABo1AwTjAdBgNVHQ4EFgQUDnV4d6mD
+tOnluLoCjkUHTX/n4agwHwYDVR0jBBgwFoAUDnV4d6mDtOnluLoCjkUHTX/n4agw
+DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAFwV4MQfTo+qMv9JMiyno
+IEiqfOz4RgtmBqRnXUffcjS2dhc7/z+FPZnM79Kej8eLHoVfxCyWRHFlzm93vEdv
+wxOCrD13EDOi08OOZfxWyIlCa6Bg8cMAKqQzd2OvQOWqlRWBTThBJIhWflU33izX
+Qn5GdmYqhfpc+9ZHHGhvXNydtRQkdxVK2dZNzLBvBlLlRmtoClU7xm3A+/5dddeP
+AQHEPtyFlUw49VYtZ3ru6KqPms7MKvcRhYLsy9rwSfuuniMlx4d0bDR7TOkw0QQS
+A0N8MGQRQpzl4mw4jLzyM5d5QtuGBh2P6hPGa0YQxtI3RPT/p6ENzzBiAKXiSfzo
+xw==
+-----END CERTIFICATE-----
--- /dev/null
+-----BEGIN RSA PRIVATE KEY-----
+MIIEowIBAAKCAQEAz+LXZOjcQCJq3+ZKUFabj71oo/ex/XsBcFqtBThjjTw9CVEV
+wfPQQp4XwtPiB204vnYXwQ1/R2NdTQqCZu47l79LssL/u2a5Y9+0NEU3nQA5qdt+
+1FAE0c5oexPimXOrR3GWfKz7PmZ2O0117IeCUUXPG5U8umhDe/4mDF4ZNJiKc404
+WthquTqgS7rLQZHhZ6D0EnGnOkzlmxJMYPNHSOY1/6ivdNUUcC87awNEA3lgfhy2
+5IyBK3QJc+aYKNTbt70Lery3bu2wWLFGtmNiGlQTS4JsxImRsECTI727ObS7/FWA
+QsqW+COL0Sa5BuMFrFIpjPrEe0ih7vRRbdmXRwIDAQABAoIBAGe4+9VqZfJN+dsq
+8Osyuz01uQ8OmC0sAWTIqUlQgENIyf9rCJsUBlYmwR5BT6Z69XP6QhHdpSK+TiAR
+XUz0EqG9HYzcxHIBaACP7j6iRoQ8R4kbbiWKo0z3WqQGIOqFjvD/mKEuQdE5mEYw
+eOUCG6BnX1WY2Yr8WKd2AA/tp0/Y4d8z04u9eodMpSTbHTzYMJb5SbBN1vo6FY7q
+8zSuO0BMzXlAxUsCwHsk1GQHFr8Oh3zIR7bQGtMBouI+6Lhh7sjFYsfxJboqMTBV
+IKaA216M6ggHG7MU1/jeKcMGDmEfqQLQoyWp29rMK6TklUgipME2L3UD7vTyAVzz
+xbVOpZkCgYEA8CXW4sZBBrSSrLR5SB+Ubu9qNTggLowOsC/kVKB2WJ4+xooc5HQo
+mFhq1v/WxPQoWIxdYsfg2odlL+JclK5Qcy6vXmRSdAQ5lK9gBDKxZSYc3NwAw2HA
+zyHCTK+I0n8PBYQ+yGcrxu0WqTGnlLW+Otk4CejO34WlgHwbH9bbY5UCgYEA3ZvT
+C4+OoMHXlmICSt29zUrYiL33IWsR3/MaONxTEDuvgkOSXXQOl/8Ebd6Nu+3WbsSN
+bjiPC/JyL1YCVmijdvFpl4gjtgvfJifs4G+QHvO6YfsYoVANk4u6g6rUuBIOwNK4
+RwYxwDc0oysp+g7tPxoSgDHReEVKJNzGBe9NGGsCgYEA4O4QP4gCEA3B9BF2J5+s
+n9uPVxmiyvZUK6Iv8zP4pThTBBMIzNIf09G9AHPQ7djikU2nioY8jXKTzC3xGTHM
+GJZ5m6fLsu7iH+nDvSreDSeNkTBfZqGAvoGYQ8uGE+L+ZuRfCcXYsxIOT5s6o4c3
+Dle2rVFpsuKzCY00urW796ECgYBn3go75+xEwrYGQSer6WR1nTgCV29GVYXKPooy
+zmmMOT1Yw80NSkEw0pFD4cTyqVYREsTrPU0mn1sPfrOXxnGfZSVFpcR/Je9QVfQ7
+eW7GYxwfom335aqHVj10SxRqteP+UoWWnHujCPz94VRKZMakBddYCIGSan+G6YdS
+7sdmwwKBgBc2qj0wvGXDF2kCLwSGfWoMf8CS1+5fIiUIdT1e/+7MfDdbmLMIFVjF
+QKS3zVViXCbrG5SY6wS9hxoc57f6E2A8vcaX6zy2xkZlGHQCpWRtEM5R01OWJQaH
+HsHMmQZGUQVoDm1oRkDhrTFK4K3ukc3rAxzeTZ96utOQN8/KJsTv
+-----END RSA PRIVATE KEY-----
--- /dev/null
+var fspfs = require('../')
+ , fs = require('fs')
+ , http = require('http')
+ , https = require('https')
+ , net = require('net')
+ , should = require('should')
+ , assert = require('assert');
+
+module.exports = {
+ // Library version should be Semver compatible
+ 'Library version': function(){
+ fspfs.version.should.match(/^\d+\.\d+\.\d+$/);
+ }
+
+ // Creating a server instace should not cause any problems
+ // either using the new Server or createServer method.
+, 'Create Server instance': function(){
+ var server = fspfs.createServer()
+ , server2 = new fspfs.Server({log:false}, ['blog.3rd-Eden.com:1337']);
+
+ // server 2 options test
+ server2.log.should.be.false;
+ server2.origins.length.should.equal(1);
+ server2.origins[0].should.equal('blog.3rd-Eden.com:1337');
+
+ // server defaults
+ (typeof server.log).should.be.equal('function');
+ server.origins.length.should.equal(1);
+ server.origins[0].should.equal('*:*');
+
+ // instance checking, sanity check
+ assert.ok(server instanceof fspfs.Server);
+ assert.ok(!!server.buffer);
+
+ // more options testing
+ server = fspfs.createServer(['blog.3rd-Eden.com:80']);
+ server.origins.length.should.equal(1);
+ server.origins[0].should.equal('blog.3rd-Eden.com:80');
+
+ server = fspfs.createServer({log:false},['blog.3rd-Eden.com:80']);
+ server.log.should.be.false;
+ server.origins.length.should.equal(1);
+ server.origins[0].should.equal('blog.3rd-Eden.com:80');
+
+ }
+
+, 'Add origin': function(){
+ var server = fspfs.createServer();
+ server.add('google.com:80', 'blog.3rd-Eden.com:1337');
+
+ server.origins.length.should.equal(3);
+ server.origins.indexOf('google.com:80').should.be.above(0);
+
+ // don't allow duplicates
+ server.add('google.com:80', 'google.com:80');
+
+ var i = server.origins.length
+ , count = 0;
+
+ while(i--){
+ if (server.origins[i] === 'google.com:80'){
+ count++;
+ }
+ }
+
+ count.should.equal(1);
+ }
+
+, 'Remove origin': function(){
+ var server = fspfs.createServer();
+ server.add('google.com:80', 'blog.3rd-Eden.com:1337');
+ server.origins.length.should.equal(3);
+
+ server.remove('google.com:80');
+ server.origins.length.should.equal(2);
+ server.origins.indexOf('google.com:80').should.equal(-1);
+ }
+
+, 'Buffer': function(){
+ var server = fspfs.createServer();
+
+ Buffer.isBuffer(server.buffer).should.be.true;
+ server.buffer.toString().indexOf('to-ports="*"').should.be.above(0);
+ server.buffer.toString().indexOf('domain="*"').should.be.above(0);
+ server.buffer.toString().indexOf('domain="google.com"').should.equal(-1);
+
+ // The buffers should be rebuild when new origins are added
+ server.add('google.com:80');
+ server.buffer.toString().indexOf('to-ports="80"').should.be.above(0);
+ server.buffer.toString().indexOf('domain="google.com"').should.be.above(0);
+
+ server.remove('google.com:80');
+ server.buffer.toString().indexOf('to-ports="80"').should.equal(-1);
+ server.buffer.toString().indexOf('domain="google.com"').should.equal(-1);
+ }
+
+, 'Responder': function(){
+ var server = fspfs.createServer()
+ , calls = 0
+ // dummy socket to emulate a `real` socket
+ , dummySocket = {
+ readyState: 'open'
+ , end: function(buffer){
+ calls++;
+ Buffer.isBuffer(buffer).should.be.true;
+ buffer.toString().should.equal(server.buffer.toString());
+ }
+ };
+
+ server.responder(dummySocket);
+ calls.should.equal(1);
+ }
+
+, 'Event proxy': function(){
+ var server = fspfs.createServer()
+ , calls = 0;
+
+ Object.keys(process.EventEmitter.prototype).forEach(function proxy(key){
+ assert.ok(!!server[key] && typeof server[key] === 'function');
+ });
+
+ // test if it works by calling a none default event
+ server.on('pew', function(){
+ calls++;
+ });
+
+ server.emit('pew');
+ calls.should.equal(1);
+ }
+
+, 'inline response http': function(){
+ var port = 1335
+ , httpserver = http.createServer(function(q,r){r.writeHead(200);r.end(':3')})
+ , server = fspfs.createServer();
+
+ httpserver.listen(port, function(){
+ server.listen(port + 1, httpserver, function(){
+ var client = net.createConnection(port);
+ client.write('<policy-file-request/>\0');
+ client.on('error', function(err){
+ assert.ok(!err, err)
+ });
+ client.on('data', function(data){
+
+ var response = data.toString();
+ console.log(response);
+
+ response.indexOf('to-ports="*"').should.be.above(0);
+ response.indexOf('domain="*"').should.be.above(0);
+ response.indexOf('domain="google.com"').should.equal(-1);
+
+ // clean up
+ client.destroy();
+ server.close();
+ httpserver.close();
+ });
+ });
+ });
+ }
+
+, 'server response': function(){
+ var port = 1340
+ , server = fspfs.createServer();
+
+ server.listen(port, function(){
+ var client = net.createConnection(port);
+ client.write('<policy-file-request/>\0');
+ client.on('error', function(err){
+ assert.ok(!err, err)
+ });
+ client.on('data', function(data){
+
+ var response = data.toString();
+
+ response.indexOf('to-ports="*"').should.be.above(0);
+ response.indexOf('domain="*"').should.be.above(0);
+ response.indexOf('domain="google.com"').should.equal(-1);
+
+ // clean up
+ client.destroy();
+ server.close();
+ });
+ });
+ }
+
+, 'inline response https': function(){
+ var port = 1345
+ , ssl = {
+ key: fs.readFileSync(__dirname + '/ssl/ssl.private.key').toString()
+ , cert: fs.readFileSync(__dirname + '/ssl/ssl.crt').toString()
+ }
+ , httpserver = https.createServer(ssl, function(q,r){r.writeHead(200);r.end(':3')})
+ , server = fspfs.createServer();
+
+ httpserver.listen(port, function(){
+ server.listen(port + 1, httpserver, function(){
+ var client = net.createConnection(port);
+ client.write('<policy-file-request/>\0');
+ client.on('error', function(err){
+ assert.ok(!err, err)
+ });
+ client.on('data', function(data){
+
+ var response = data.toString();
+
+ response.indexOf('to-ports="*"').should.be.above(0);
+ response.indexOf('domain="*"').should.be.above(0);
+ response.indexOf('domain="google.com"').should.equal(-1);
+
+ // clean up
+ client.destroy();
+ server.close();
+ httpserver.close();
+ });
+ });
+ });
+ }
+
+, 'connect_failed': function(){
+ var server = fspfs.createServer();
+
+ server.on('connect_failed', function(){
+ assert.ok(true);
+ });
+
+ server.listen(function(){
+ assert.ok(false, 'Run this test without root access');
+ server.close();
+ });
+ }
+};
\ No newline at end of file
-
+ WEB_SOCKET_SWF_LOCATION = "WebSocketMain.swf";
var Emoticons=[];
var settings=new Object();
// {"invite":"ask","growlip":"","growlpw":"","prowlkey":"","prowlpriority":"","nmakey":"","nmapriority":""};
}
function connect(data){
- IRCConnection.data=data;
+ IRCConnection.data=data;
nickname = data[3];
var panel = createTaskPanel();
// var objStatus = Object.create(Channel).init('status');
// input.hide();
// $('span').hide();
return;
- }
-
+ }
connection = new WebSocket(location.href.split('http://').join('ws://'));
connection.win = win;
connection.onopen = function () {
}
-}( window.IRCConnection = window.IRCConnection || {}));
\ No newline at end of file
+}( window.IRCConnection = window.IRCConnection || {}));
<link href="windows_js_1.3/themes/alert.css" rel="stylesheet" type="text/css" />
<link href="windows_js_1.3/themes/alert_lite.css" rel="stylesheet" type="text/css" />
<link href="windows_js_1.3/themes/alphacube.css" rel="stylesheet" type="text/css" />
+ <script type="text/javascript" src="swfobject.js"></script>
+ <script type="text/javascript" src="web_socket.js"></script>
<script type="text/javascript" src="windows_js_1.3/javascripts/prototype.js"></script>
<script type="text/javascript" src="windows_js_1.3/javascripts/effects.js"></script>
<script type="text/javascript" src="windows_js_1.3/javascripts/window.js"></script>
--- /dev/null
+/* SWFObject v2.2 <http://code.google.com/p/swfobject/>
+ is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
+*/
+var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();
\ No newline at end of file
--- /dev/null
+// Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
+// License: New BSD License
+// Reference: http://dev.w3.org/html5/websockets/
+// Reference: http://tools.ietf.org/html/rfc6455
+
+(function() {
+
+ if (window.WEB_SOCKET_FORCE_FLASH) {
+ // Keeps going.
+ } else if (window.WebSocket) {
+ return;
+ } else if (window.MozWebSocket) {
+ // Firefox.
+ window.WebSocket = MozWebSocket;
+ return;
+ }
+
+ var logger;
+ if (window.WEB_SOCKET_LOGGER) {
+ logger = WEB_SOCKET_LOGGER;
+ } else if (window.console && window.console.log && window.console.error) {
+ // In some environment, console is defined but console.log or console.error is missing.
+ logger = window.console;
+ } else {
+ logger = {log: function(){ }, error: function(){ }};
+ }
+
+ // swfobject.hasFlashPlayerVersion("10.0.0") doesn't work with Gnash.
+ if (swfobject.getFlashPlayerVersion().major < 10) {
+ logger.error("Flash Player >= 10.0.0 is required.");
+ return;
+ }
+ if (location.protocol == "file:") {
+ logger.error(
+ "WARNING: web-socket-js doesn't work in file:///... URL " +
+ "unless you set Flash Security Settings properly. " +
+ "Open the page via Web server i.e. http://...");
+ }
+
+ /**
+ * Our own implementation of WebSocket class using Flash.
+ * @param {string} url
+ * @param {array or string} protocols
+ * @param {string} proxyHost
+ * @param {int} proxyPort
+ * @param {string} headers
+ */
+ window.WebSocket = function(url, protocols, proxyHost, proxyPort, headers) {
+ var self = this;
+ self.__id = WebSocket.__nextId++;
+ WebSocket.__instances[self.__id] = self;
+ self.readyState = WebSocket.CONNECTING;
+ self.bufferedAmount = 0;
+ self.__events = {};
+ if (!protocols) {
+ protocols = [];
+ } else if (typeof protocols == "string") {
+ protocols = [protocols];
+ }
+ // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
+ // Otherwise, when onopen fires immediately, onopen is called before it is set.
+ self.__createTask = setTimeout(function() {
+ WebSocket.__addTask(function() {
+ self.__createTask = null;
+ WebSocket.__flash.create(
+ self.__id, url, protocols, proxyHost || null, proxyPort || 0, headers || null);
+ });
+ }, 0);
+ };
+
+ /**
+ * Send data to the web socket.
+ * @param {string} data The data to send to the socket.
+ * @return {boolean} True for success, false for failure.
+ */
+ WebSocket.prototype.send = function(data) {
+ if (this.readyState == WebSocket.CONNECTING) {
+ throw "INVALID_STATE_ERR: Web Socket connection has not been established";
+ }
+ // We use encodeURIComponent() here, because FABridge doesn't work if
+ // the argument includes some characters. We don't use escape() here
+ // because of this:
+ // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
+ // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
+ // preserve all Unicode characters either e.g. "\uffff" in Firefox.
+ // Note by wtritch: Hopefully this will not be necessary using ExternalInterface. Will require
+ // additional testing.
+ var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data));
+ if (result < 0) { // success
+ return true;
+ } else {
+ this.bufferedAmount += result;
+ return false;
+ }
+ };
+
+ /**
+ * Close this web socket gracefully.
+ */
+ WebSocket.prototype.close = function() {
+ if (this.__createTask) {
+ clearTimeout(this.__createTask);
+ this.__createTask = null;
+ this.readyState = WebSocket.CLOSED;
+ return;
+ }
+ if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) {
+ return;
+ }
+ this.readyState = WebSocket.CLOSING;
+ WebSocket.__flash.close(this.__id);
+ };
+
+ /**
+ * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
+ *
+ * @param {string} type
+ * @param {function} listener
+ * @param {boolean} useCapture
+ * @return void
+ */
+ WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
+ if (!(type in this.__events)) {
+ this.__events[type] = [];
+ }
+ this.__events[type].push(listener);
+ };
+
+ /**
+ * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
+ *
+ * @param {string} type
+ * @param {function} listener
+ * @param {boolean} useCapture
+ * @return void
+ */
+ WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
+ if (!(type in this.__events)) return;
+ var events = this.__events[type];
+ for (var i = events.length - 1; i >= 0; --i) {
+ if (events[i] === listener) {
+ events.splice(i, 1);
+ break;
+ }
+ }
+ };
+
+ /**
+ * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
+ *
+ * @param {Event} event
+ * @return void
+ */
+ WebSocket.prototype.dispatchEvent = function(event) {
+ var events = this.__events[event.type] || [];
+ for (var i = 0; i < events.length; ++i) {
+ events[i](event);
+ }
+ var handler = this["on" + event.type];
+ if (handler) handler.apply(this, [event]);
+ };
+
+ /**
+ * Handles an event from Flash.
+ * @param {Object} flashEvent
+ */
+ WebSocket.prototype.__handleEvent = function(flashEvent) {
+
+ if ("readyState" in flashEvent) {
+ this.readyState = flashEvent.readyState;
+ }
+ if ("protocol" in flashEvent) {
+ this.protocol = flashEvent.protocol;
+ }
+
+ var jsEvent;
+ if (flashEvent.type == "open" || flashEvent.type == "error") {
+ jsEvent = this.__createSimpleEvent(flashEvent.type);
+ } else if (flashEvent.type == "close") {
+ jsEvent = this.__createSimpleEvent("close");
+ jsEvent.wasClean = flashEvent.wasClean ? true : false;
+ jsEvent.code = flashEvent.code;
+ jsEvent.reason = flashEvent.reason;
+ } else if (flashEvent.type == "message") {
+ var data = decodeURIComponent(flashEvent.message);
+ jsEvent = this.__createMessageEvent("message", data);
+ } else {
+ throw "unknown event type: " + flashEvent.type;
+ }
+
+ this.dispatchEvent(jsEvent);
+
+ };
+
+ WebSocket.prototype.__createSimpleEvent = function(type) {
+ if (document.createEvent && window.Event) {
+ var event = document.createEvent("Event");
+ event.initEvent(type, false, false);
+ return event;
+ } else {
+ return {type: type, bubbles: false, cancelable: false};
+ }
+ };
+
+ WebSocket.prototype.__createMessageEvent = function(type, data) {
+ if (document.createEvent && window.MessageEvent && !window.opera) {
+ var event = document.createEvent("MessageEvent");
+ event.initMessageEvent("message", false, false, data, null, null, window, null);
+ return event;
+ } else {
+ // IE and Opera, the latter one truncates the data parameter after any 0x00 bytes.
+ return {type: type, data: data, bubbles: false, cancelable: false};
+ }
+ };
+
+ /**
+ * Define the WebSocket readyState enumeration.
+ */
+ WebSocket.CONNECTING = 0;
+ WebSocket.OPEN = 1;
+ WebSocket.CLOSING = 2;
+ WebSocket.CLOSED = 3;
+
+ // Field to check implementation of WebSocket.
+ WebSocket.__isFlashImplementation = true;
+ WebSocket.__initialized = false;
+ WebSocket.__flash = null;
+ WebSocket.__instances = {};
+ WebSocket.__tasks = [];
+ WebSocket.__nextId = 0;
+
+ /**
+ * Load a new flash security policy file.
+ * @param {string} url
+ */
+ WebSocket.loadFlashPolicyFile = function(url){
+ WebSocket.__addTask(function() {
+ WebSocket.__flash.loadManualPolicyFile(url);
+ });
+ };
+
+ /**
+ * Loads WebSocketMain.swf and creates WebSocketMain object in Flash.
+ */
+ WebSocket.__initialize = function() {
+
+ if (WebSocket.__initialized) return;
+ WebSocket.__initialized = true;
+
+ if (WebSocket.__swfLocation) {
+ // For backword compatibility.
+ window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
+ }
+ if (!window.WEB_SOCKET_SWF_LOCATION) {
+ logger.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
+ return;
+ }
+ if (!window.WEB_SOCKET_SUPPRESS_CROSS_DOMAIN_SWF_ERROR &&
+ !WEB_SOCKET_SWF_LOCATION.match(/(^|\/)WebSocketMainInsecure\.swf(\?.*)?$/) &&
+ WEB_SOCKET_SWF_LOCATION.match(/^\w+:\/\/([^\/]+)/)) {
+ var swfHost = RegExp.$1;
+ if (location.host != swfHost) {
+ logger.error(
+ "[WebSocket] You must host HTML and WebSocketMain.swf in the same host " +
+ "('" + location.host + "' != '" + swfHost + "'). " +
+ "See also 'How to host HTML file and SWF file in different domains' section " +
+ "in README.md. If you use WebSocketMainInsecure.swf, you can suppress this message " +
+ "by WEB_SOCKET_SUPPRESS_CROSS_DOMAIN_SWF_ERROR = true;");
+ }
+ }
+ var container = document.createElement("div");
+ container.id = "webSocketContainer";
+ // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
+ // Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
+ // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
+ // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
+ // the best we can do as far as we know now.
+ container.style.position = "absolute";
+ if (WebSocket.__isFlashLite()) {
+ container.style.left = "0px";
+ container.style.top = "0px";
+ } else {
+ container.style.left = "-100px";
+ container.style.top = "-100px";
+ }
+ var holder = document.createElement("div");
+ holder.id = "webSocketFlash";
+ container.appendChild(holder);
+ document.body.appendChild(container);
+ // See this article for hasPriority:
+ // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
+ swfobject.embedSWF(
+ WEB_SOCKET_SWF_LOCATION,
+ "webSocketFlash",
+ "1" /* width */,
+ "1" /* height */,
+ "10.0.0" /* SWF version */,
+ null,
+ null,
+ {hasPriority: true, swliveconnect : true, allowScriptAccess: "always"},
+ null,
+ function(e) {
+ if (!e.success) {
+ logger.error("[WebSocket] swfobject.embedSWF failed");
+ }
+ }
+ );
+
+ };
+
+ /**
+ * Called by Flash to notify JS that it's fully loaded and ready
+ * for communication.
+ */
+ WebSocket.__onFlashInitialized = function() {
+ // We need to set a timeout here to avoid round-trip calls
+ // to flash during the initialization process.
+ setTimeout(function() {
+ WebSocket.__flash = document.getElementById("webSocketFlash");
+ WebSocket.__flash.setCallerUrl(location.href);
+ WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
+ for (var i = 0; i < WebSocket.__tasks.length; ++i) {
+ WebSocket.__tasks[i]();
+ }
+ WebSocket.__tasks = [];
+ }, 0);
+ };
+
+ /**
+ * Called by Flash to notify WebSockets events are fired.
+ */
+ WebSocket.__onFlashEvent = function() {
+ setTimeout(function() {
+ try {
+ // Gets events using receiveEvents() instead of getting it from event object
+ // of Flash event. This is to make sure to keep message order.
+ // It seems sometimes Flash events don't arrive in the same order as they are sent.
+ var events = WebSocket.__flash.receiveEvents();
+ for (var i = 0; i < events.length; ++i) {
+ WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]);
+ }
+ } catch (e) {
+ logger.error(e);
+ }
+ }, 0);
+ return true;
+ };
+
+ // Called by Flash.
+ WebSocket.__log = function(message) {
+ logger.log(decodeURIComponent(message));
+ };
+
+ // Called by Flash.
+ WebSocket.__error = function(message) {
+ logger.error(decodeURIComponent(message));
+ };
+
+ WebSocket.__addTask = function(task) {
+ if (WebSocket.__flash) {
+ task();
+ } else {
+ WebSocket.__tasks.push(task);
+ }
+ };
+
+ /**
+ * Test if the browser is running flash lite.
+ * @return {boolean} True if flash lite is running, false otherwise.
+ */
+ WebSocket.__isFlashLite = function() {
+ if (!window.navigator || !window.navigator.mimeTypes) {
+ return false;
+ }
+ var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
+ if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) {
+ return false;
+ }
+ return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
+ };
+
+ if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
+ // NOTE:
+ // This fires immediately if web_socket.js is dynamically loaded after
+ // the document is loaded.
+ swfobject.addDomLoadEvent(function() {
+ WebSocket.__initialize();
+ });
+ }
+
+})();