diff options
author | Alon Zakai <alonzakai@gmail.com> | 2012-09-27 16:11:55 -0700 |
---|---|---|
committer | Alon Zakai <alonzakai@gmail.com> | 2012-09-27 16:11:55 -0700 |
commit | 31f7b2a5a65d2d640343013dac4bb836c3bfba5f (patch) | |
tree | e677a00733440e57ab61fb00a696284c1d7b960b /third_party | |
parent | e546b42883bbcabb4657dfcdb523a93d0458f5b3 (diff) |
initial (not-yet-working) sockets implementation
Diffstat (limited to 'third_party')
72 files changed, 10395 insertions, 0 deletions
diff --git a/third_party/websockify/.gitignore b/third_party/websockify/.gitignore new file mode 100644 index 00000000..86b78922 --- /dev/null +++ b/third_party/websockify/.gitignore @@ -0,0 +1,10 @@ +*.pyc +*.o +*.so +other/.lein-deps-sum +other/classes +other/lib +.project +.pydevproject +target.cfg +target.cfg.d diff --git a/third_party/websockify/CHANGES.txt b/third_party/websockify/CHANGES.txt new file mode 100644 index 00000000..cbd3f73f --- /dev/null +++ b/third_party/websockify/CHANGES.txt @@ -0,0 +1,18 @@ +Changes +======= + +0.2.0 - Sep 17, 2012 +-------------------- + + * Binary data support in websock.js + * Target config file/dir and multiple targets with token selector + * IPv6 fixes + * SSL target support + * Proxy to/from unix socket + + +0.1.0 - May 11, 2012 +-------------------- + + * Initial versioned release. + diff --git a/third_party/websockify/LICENSE.txt b/third_party/websockify/LICENSE.txt new file mode 100644 index 00000000..916a77a0 --- /dev/null +++ b/third_party/websockify/LICENSE.txt @@ -0,0 +1,11 @@ +websockify is licensed under the LGPL version 3 (see docs/LICENSE.GPL-3 and +docs/LICENSE.LGPL-3) with the following exceptions: + + include/base64.js : Choice of MIT 1.1, GPL-2 or LGPL-2.1 + + include/web-socket-js/ : New BSD license. Source code at + https://github.com/gimite/web-socket-js + + other/kumina.c : Simplified BSD license (2 clause). + Original source at + https://github.com/kumina/wsproxy diff --git a/third_party/websockify/MANIFEST.in b/third_party/websockify/MANIFEST.in new file mode 100644 index 00000000..2dd46d25 --- /dev/null +++ b/third_party/websockify/MANIFEST.in @@ -0,0 +1 @@ +include CHANGES.txt *.py README.md LICENSE.txt diff --git a/third_party/websockify/Makefile b/third_party/websockify/Makefile new file mode 100644 index 00000000..7dc1bc4f --- /dev/null +++ b/third_party/websockify/Makefile @@ -0,0 +1,11 @@ +TARGETS=rebind.so +CFLAGS += -fPIC + +all: $(TARGETS) + +rebind.so: rebind.o + $(CC) $(LDFLAGS) $^ -shared -fPIC -ldl -o $@ + +clean: + rm -f rebind.o rebind.so + diff --git a/third_party/websockify/README.md b/third_party/websockify/README.md new file mode 100644 index 00000000..48c790af --- /dev/null +++ b/third_party/websockify/README.md @@ -0,0 +1,155 @@ +## websockify: WebSockets support for any application/server + +websockify was formerly named wsproxy and was part of the +[noVNC](https://github.com/kanaka/noVNC) project. + +At the most basic level, websockify just translates WebSockets traffic +to normal socket traffic. Websockify accepts the WebSockets handshake, +parses it, and then begins forwarding traffic between the client and +the target in both directions. + +### WebSockets binary data + +Websockify supports all versions of the WebSockets protocol (Hixie and +HyBI). The older Hixie versions of the protocol only support UTF-8 +text payloads. In order to transport binary data over UTF-8 an +encoding must used to encapsulate the data within UTF-8. Websockify +uses base64 to encode all traffic to and from the client. This does +not affect the data between websockify and the server. + +### Encrypted WebSocket connections (wss://) + +To encrypt the traffic using the WebSocket 'wss://' URI scheme you +need to generate a certificate for websockify to load. By default websockify +loads a certificate file name `self.pem` but the `--cert=CERT` option can +override the file name. You can generate a self-signed certificate using +openssl. When asked for the common name, use the hostname of the server where +the proxy will be running: + +``` +openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem +``` + + +### Websock Javascript library + + +The `include/websock.js` Javascript library library provides a Websock +object that is similar to the standard WebSocket object but Websock +enables communication with raw TCP sockets (i.e. the binary stream) +via websockify. This is accomplished by base64 encoding the data +stream between Websock and websockify. + +Websock has built-in receive queue buffering; the message event +does not contain actual data but is simply a notification that +there is new data available. Several rQ* methods are available to +read binary data off of the receive queue. + +The Websock API is documented on the [websock.js API wiki page](https://github.com/kanaka/websockify/wiki/websock.js) + +See the "Wrap a Program" section below for an example of using Websock +and websockify as a browser telnet client (`wstelnet.html`). + + +### Additional websockify features + +These are not necessary for the basic operation. + +* Daemonizing: When the `-D` option is specified, websockify runs + in the background as a daemon process. + +* SSL (the wss:// WebSockets URI): This is detected automatically by + websockify by sniffing the first byte sent from the client and then + wrapping the socket if the data starts with '\x16' or '\x80' + (indicating SSL). + +* Flash security policy: websockify detects flash security policy + requests (again by sniffing the first packet) and answers with an + appropriate flash security policy response (and then closes the + port). This means no separate flash security policy server is needed + for supporting the flash WebSockets fallback emulator. + +* Session recording: This feature that allows recording of the traffic + sent and received from the client to a file using the `--record` + option. + +* Mini-webserver: websockify can detect and respond to normal web + requests on the same port as the WebSockets proxy and Flash security + policy. This functionality is activate with the `--web DIR` option + where DIR is the root of the web directory to serve. + +* Wrap a program: see the "Wrap a Program" section below. + + +### Implementations of websockify + +The primary implementation of websockify is in python. There are +several alternate implementations in other languages (C, Node.js, +Clojure, Ruby) in the `other/` subdirectory (with varying levels of +functionality). + +In addition there are several other external projects that implement +the websockify "protocol". See the alternate implementation [Feature +Matrix](https://github.com/kanaka/websockify/wiki/Feature_Matrix) for +more information. + + +### Wrap a Program + +In addition to proxying from a source address to a target address +(which may be on a different system), websockify has the ability to +launch a program on the local system and proxy WebSockets traffic to +a normal TCP port owned/bound by the program. + +The is accomplished with a small LD_PRELOAD library (`rebind.so`) +which intercepts bind() system calls by the program. The specified +port is moved to a new localhost/loopback free high port. websockify +then proxies WebSockets traffic directed to the original port to the +new (moved) port of the program. + +The program wrap mode is invoked by replacing the target with `--` +followed by the program command line to wrap. + + `./websockify 2023 -- PROGRAM ARGS` + +The `--wrap-mode` option can be used to indicate what action to take +when the wrapped program exits or daemonizes. + +Here is an example of using websockify to wrap the vncserver command +(which backgrounds itself) for use with +[noVNC](https://github.com/kanaka/noVNC): + + `./websockify 5901 --wrap-mode=ignore -- vncserver -geometry 1024x768 :1` + +Here is an example of wrapping telnetd (from krb5-telnetd).telnetd +exits after the connection closes so the wrap mode is set to respawn +the command: + + `sudo ./websockify 2023 --wrap-mode=respawn -- telnetd -debug 2023` + +The `wstelnet.html` page demonstrates a simple WebSockets based telnet +client. + + +### Building the Python ssl module (for python 2.5 and older) + +* Install the build dependencies. On Ubuntu use this command: + + `sudo aptitude install python-dev bluetooth-dev` + +* Download, build the ssl module and symlink to it: + + `cd websockify/` + + `wget http://pypi.python.org/packages/source/s/ssl/ssl-1.15.tar.gz` + + `tar xvzf ssl-1.15.tar.gz` + + `cd ssl-1.15` + + `make` + + `cd ../` + + `ln -sf ssl-1.15/build/lib.linux-*/ssl ssl` + diff --git a/third_party/websockify/Windows/Windows Service Readme.txt b/third_party/websockify/Windows/Windows Service Readme.txt new file mode 100644 index 00000000..1ddc2f82 --- /dev/null +++ b/third_party/websockify/Windows/Windows Service Readme.txt @@ -0,0 +1,39 @@ +----------------------------------- +Windows noVNC Websockify Service +----------------------------------- + +The "noVNC Websocket Service.exe" file is a windows service wrapper created with Visual Studio 2010 to create a windows service to start stop the noVNC Websocket Server. All files used to create the wrapper can be found in 'noVNC Websocket Service Project' folder. + +To download the precompiled executables please grab the zip in the downloads section of websockify project: +https://github.com/kanaka/websockify + +--------------------------- +Installation +--------------------------- + +1. This service requires websockify.exe be in the same directory. Instructions on how to compile websockify python script as a windows executable can be found here: +https://github.com/kanaka/noVNC/wiki/Compiling-Websockify-to-Windows-Executable + +2.To add this service to a Windows PC you need to run the commandline as administrator and then run this line: + +sc create "noVNC Websocket Server" binPath= "PATH TO noVNC eg C:\noVNC\utils\Windows\Websocket Service.exe" DisplayName= "noVNC Websocket Server" + +3 .Once this is run you will be able to access the service via Control Panel > Admin Tools > Services. In here you can specify whether you want the service to run automatically and start at stop the service. + +--------------------------- +Configuration +--------------------------- +The file noVNCConfig.ini must be in the same directory as "noVNC Websocket Service.exe". + +This file contains a single line which is the websockify.exe statup arguements. An example is: +192.168.0.1:5901 192.168.0.1:5900 + +All websockify supported arguements will work if added here. + +--------------------------- +Deletion +--------------------------- + +You can delete the service at any time by running the commandline as admin and using this command: +sc delete "noVNC Websocket Server". + diff --git a/third_party/websockify/Windows/noVNC Websocket Service Project/Program.cs b/third_party/websockify/Windows/noVNC Websocket Service Project/Program.cs new file mode 100644 index 00000000..2d07c330 --- /dev/null +++ b/third_party/websockify/Windows/noVNC Websocket Service Project/Program.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.ServiceProcess; +using System.Text; + +namespace MELT_Command_Websocket +{ + static class Program + { + /// <summary> + /// The main entry point for the application. + /// </summary> + static void Main() + { + ServiceBase[] ServicesToRun; + ServicesToRun = new ServiceBase[] + { + new Service1() + }; + ServiceBase.Run(ServicesToRun); + } + } +} diff --git a/third_party/websockify/Windows/noVNC Websocket Service Project/ProjectInstaller.Designer.cs b/third_party/websockify/Windows/noVNC Websocket Service Project/ProjectInstaller.Designer.cs new file mode 100644 index 00000000..3dab5bb7 --- /dev/null +++ b/third_party/websockify/Windows/noVNC Websocket Service Project/ProjectInstaller.Designer.cs @@ -0,0 +1,61 @@ +namespace MELT_Command_Websocket +{ + partial class ProjectInstaller + { + /// <summary> + /// Required designer variable. + /// </summary> + private System.ComponentModel.IContainer components = null; + + /// <summary> + /// Clean up any resources being used. + /// </summary> + /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// <summary> + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// </summary> + private void InitializeComponent() + { + this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller(); + this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller(); + // + // serviceProcessInstaller1 + // + this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.NetworkService; + this.serviceProcessInstaller1.Installers.AddRange(new System.Configuration.Install.Installer[] { + this.serviceInstaller1}); + this.serviceProcessInstaller1.Password = null; + this.serviceProcessInstaller1.Username = null; + // + // serviceInstaller1 + // + this.serviceInstaller1.Description = "noVNC Websocket Service"; + this.serviceInstaller1.DisplayName = "noVNC Websocket Service"; + this.serviceInstaller1.ServiceName = "noVNC Websocket Service"; + this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic; + // + // ProjectInstaller + // + this.Installers.AddRange(new System.Configuration.Install.Installer[] { + this.serviceProcessInstaller1}); + + } + + #endregion + + private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1; + private System.ServiceProcess.ServiceInstaller serviceInstaller1; + } +}
\ No newline at end of file diff --git a/third_party/websockify/Windows/noVNC Websocket Service Project/ProjectInstaller.cs b/third_party/websockify/Windows/noVNC Websocket Service Project/ProjectInstaller.cs new file mode 100644 index 00000000..783bb15b --- /dev/null +++ b/third_party/websockify/Windows/noVNC Websocket Service Project/ProjectInstaller.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration.Install; +using System.Linq; + + +namespace MELT_Command_Websocket +{ + [RunInstaller(true)] + public partial class ProjectInstaller : System.Configuration.Install.Installer + { + public ProjectInstaller() + { + InitializeComponent(); + } + } +} diff --git a/third_party/websockify/Windows/noVNC Websocket Service Project/ProjectInstaller.resx b/third_party/websockify/Windows/noVNC Websocket Service Project/ProjectInstaller.resx new file mode 100644 index 00000000..fbda1aec --- /dev/null +++ b/third_party/websockify/Windows/noVNC Websocket Service Project/ProjectInstaller.resx @@ -0,0 +1,129 @@ +<?xml version="1.0" encoding="utf-8"?> +<root> + <!-- + Microsoft ResX Schema + + Version 2.0 + + The primary goals of this format is to allow a simple XML format + that is mostly human readable. The generation and parsing of the + various data types are done through the TypeConverter classes + associated with the data types. + + Example: + + ... ado.net/XML headers & schema ... + <resheader name="resmimetype">text/microsoft-resx</resheader> + <resheader name="version">2.0</resheader> + <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> + <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> + <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> + <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> + <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> + <value>[base64 mime encoded serialized .NET Framework object]</value> + </data> + <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> + <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> + <comment>This is a comment</comment> + </data> + + There are any number of "resheader" rows that contain simple + name/value pairs. + + Each data row contains a name, and value. The row also contains a + type or mimetype. Type corresponds to a .NET class that support + text/value conversion through the TypeConverter architecture. + Classes that don't support this are serialized and stored with the + mimetype set. + + The mimetype is used for serialized objects, and tells the + ResXResourceReader how to depersist the object. This is currently not + extensible. For a given mimetype the value must be set accordingly: + + Note - application/x-microsoft.net.object.binary.base64 is the format + that the ResXResourceWriter will generate, however the reader can + read any of the formats listed below. + + mimetype: application/x-microsoft.net.object.binary.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.soap.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Soap.SoapFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.bytearray.base64 + value : The object must be serialized into a byte array + : using a System.ComponentModel.TypeConverter + : and then encoded with base64 encoding. + --> + <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> + <xsd:element name="root" msdata:IsDataSet="true"> + <xsd:complexType> + <xsd:choice maxOccurs="unbounded"> + <xsd:element name="metadata"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" /> + </xsd:sequence> + <xsd:attribute name="name" use="required" type="xsd:string" /> + <xsd:attribute name="type" type="xsd:string" /> + <xsd:attribute name="mimetype" type="xsd:string" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="assembly"> + <xsd:complexType> + <xsd:attribute name="alias" type="xsd:string" /> + <xsd:attribute name="name" type="xsd:string" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="data"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> + <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> + <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="resheader"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" /> + </xsd:complexType> + </xsd:element> + </xsd:choice> + </xsd:complexType> + </xsd:element> + </xsd:schema> + <resheader name="resmimetype"> + <value>text/microsoft-resx</value> + </resheader> + <resheader name="version"> + <value>2.0</value> + </resheader> + <resheader name="reader"> + <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <resheader name="writer"> + <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <metadata name="serviceProcessInstaller1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> + <value>17, 56</value> + </metadata> + <metadata name="serviceInstaller1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> + <value>196, 17</value> + </metadata> + <metadata name="$this.TrayLargeIcon" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> + <value>False</value> + </metadata> +</root>
\ No newline at end of file diff --git a/third_party/websockify/Windows/noVNC Websocket Service Project/Properties/AssemblyInfo.cs b/third_party/websockify/Windows/noVNC Websocket Service Project/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..832319ee --- /dev/null +++ b/third_party/websockify/Windows/noVNC Websocket Service Project/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MELT Command Websocket")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("MELT Command Websocket")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("5ab831cb-6852-4ce1-849c-b26725b0e10b")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/third_party/websockify/Windows/noVNC Websocket Service Project/Service1.Designer.cs b/third_party/websockify/Windows/noVNC Websocket Service Project/Service1.Designer.cs new file mode 100644 index 00000000..c569eca8 --- /dev/null +++ b/third_party/websockify/Windows/noVNC Websocket Service Project/Service1.Designer.cs @@ -0,0 +1,37 @@ +namespace MELT_Command_Websocket +{ + partial class Service1 + { + /// <summary> + /// Required designer variable. + /// </summary> + private System.ComponentModel.IContainer components = null; + + /// <summary> + /// Clean up any resources being used. + /// </summary> + /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// <summary> + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// </summary> + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + this.ServiceName = "Service1"; + } + + #endregion + } +} diff --git a/third_party/websockify/Windows/noVNC Websocket Service Project/Service1.cs b/third_party/websockify/Windows/noVNC Websocket Service Project/Service1.cs new file mode 100644 index 00000000..ce94bf6b --- /dev/null +++ b/third_party/websockify/Windows/noVNC Websocket Service Project/Service1.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Linq; +using System.ServiceProcess; +using System.Text; +using System.IO; + +namespace MELT_Command_Websocket +{ + public partial class Service1 : ServiceBase + { + Process websockify; + public Service1() + { + InitializeComponent(); + } + + protected override void OnStart(string[] args) + { + + string configpath = AppDomain.CurrentDomain.BaseDirectory + "\\noVNCConfig.ini"; + string sockifypath = AppDomain.CurrentDomain.BaseDirectory + "\\websockify.exe"; + //Load commandline arguements from config file. + StreamReader streamReader = new StreamReader(configpath); + string arguements = streamReader.ReadLine(); + streamReader.Close(); + + //Start websockify. + websockify = System.Diagnostics.Process.Start(sockifypath, arguements); + } + + protected override void OnStop() + { + //Service stopped. Close websockify. + websockify.Kill(); + } + } +} diff --git a/third_party/websockify/Windows/noVNC Websocket Service Project/noVNC Websocket.csproj b/third_party/websockify/Windows/noVNC Websocket Service Project/noVNC Websocket.csproj new file mode 100644 index 00000000..368d1839 --- /dev/null +++ b/third_party/websockify/Windows/noVNC Websocket Service Project/noVNC Websocket.csproj @@ -0,0 +1,75 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">x86</Platform> + <ProductVersion>8.0.30703</ProductVersion> + <SchemaVersion>2.0</SchemaVersion> + <ProjectGuid>{6B86AE7B-6BBD-4E74-8802-5995E8B6D27D}</ProjectGuid> + <OutputType>WinExe</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>noVNC_Websocket_Service</RootNamespace> + <AssemblyName>noVNC Websocket Service</AssemblyName> + <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> + <FileAlignment>512</FileAlignment> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' "> + <PlatformTarget>x86</PlatformTarget> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' "> + <PlatformTarget>x86</PlatformTarget> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="System.Configuration.Install" /> + <Reference Include="System.Core" /> + <Reference Include="System.Management" /> + <Reference Include="System.Xml.Linq" /> + <Reference Include="System.Data.DataSetExtensions" /> + <Reference Include="System.Data" /> + <Reference Include="System.ServiceProcess" /> + <Reference Include="System.Xml" /> + </ItemGroup> + <ItemGroup> + <Compile Include="ProjectInstaller.cs"> + <SubType>Component</SubType> + </Compile> + <Compile Include="ProjectInstaller.Designer.cs"> + <DependentUpon>ProjectInstaller.cs</DependentUpon> + </Compile> + <Compile Include="Service1.cs"> + <SubType>Component</SubType> + </Compile> + <Compile Include="Service1.Designer.cs"> + <DependentUpon>Service1.cs</DependentUpon> + </Compile> + <Compile Include="Program.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + </ItemGroup> + <ItemGroup> + <EmbeddedResource Include="ProjectInstaller.resx"> + <DependentUpon>ProjectInstaller.cs</DependentUpon> + </EmbeddedResource> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <!-- To modify your build process, add your task inside one of the targets below and uncomment it. + Other similar extension points exist, see Microsoft.Common.targets. + <Target Name="BeforeBuild"> + </Target> + <Target Name="AfterBuild"> + </Target> + --> +</Project>
\ No newline at end of file diff --git a/third_party/websockify/Windows/noVNC Websocket Service Project/noVNC Websocket.sln b/third_party/websockify/Windows/noVNC Websocket Service Project/noVNC Websocket.sln new file mode 100644 index 00000000..140de1be --- /dev/null +++ b/third_party/websockify/Windows/noVNC Websocket Service Project/noVNC Websocket.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "noVNC Websocket", "noVNC Websocket.csproj", "{6B86AE7B-6BBD-4E74-8802-5995E8B6D27D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x86 = Debug|x86 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {6B86AE7B-6BBD-4E74-8802-5995E8B6D27D}.Debug|x86.ActiveCfg = Debug|x86 + {6B86AE7B-6BBD-4E74-8802-5995E8B6D27D}.Debug|x86.Build.0 = Debug|x86 + {6B86AE7B-6BBD-4E74-8802-5995E8B6D27D}.Release|x86.ActiveCfg = Release|x86 + {6B86AE7B-6BBD-4E74-8802-5995E8B6D27D}.Release|x86.Build.0 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/third_party/websockify/docs/LICENSE.GPL-3 b/third_party/websockify/docs/LICENSE.GPL-3 new file mode 100644 index 00000000..94a04532 --- /dev/null +++ b/third_party/websockify/docs/LICENSE.GPL-3 @@ -0,0 +1,621 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS diff --git a/third_party/websockify/docs/LICENSE.LGPL-3 b/third_party/websockify/docs/LICENSE.LGPL-3 new file mode 100644 index 00000000..65c5ca88 --- /dev/null +++ b/third_party/websockify/docs/LICENSE.LGPL-3 @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/third_party/websockify/docs/TODO b/third_party/websockify/docs/TODO new file mode 100644 index 00000000..cc4b4776 --- /dev/null +++ b/third_party/websockify/docs/TODO @@ -0,0 +1,9 @@ +- Go implementation + +- Support multiple targets that are selected by the path line. Some + sort of wildcarding of ports too. + +- Support SSL targets too. + +- wstelnet: support CSI L and CSI M + diff --git a/third_party/websockify/docs/flash_policy.txt b/third_party/websockify/docs/flash_policy.txt new file mode 100644 index 00000000..df325c0d --- /dev/null +++ b/third_party/websockify/docs/flash_policy.txt @@ -0,0 +1,4 @@ +Manual setup: + +DATA="echo \'<cross-domain-policy><allow-access-from domain=\\\"*\\\" to-ports=\\\"*\\\" /></cross-domain-policy>\'" +/usr/bin/socat -T 1 TCP-L:843,reuseaddr,fork,crlf SYSTEM:"$DATA" diff --git a/third_party/websockify/docs/latency_results.txt b/third_party/websockify/docs/latency_results.txt new file mode 100644 index 00000000..454a590e --- /dev/null +++ b/third_party/websockify/docs/latency_results.txt @@ -0,0 +1,114 @@ +This data is raw copy from the latency tester set to send a frame with +a little over 2000 KB of data every 10ms. + +The number of packets sent and received is just a visual counter and +is just the total when I chose to stop the test (around 3000 or so +packets). + +The latency measure are from the point the packet was sent to when it +was received back again in milliseconds. One notable data point +missing from this is how long it actually took for the client to send +3000 packets because sending large packets can put load on the browser +and it may be a lot longer than 10ms before the timer event to +send the next packet fires. So even with low latency numbers, the +actual send rate may be fairly low because sending the WebSockets +frames is impacting the performance of the browser in general. + + +------------------------------------------------------------ + +Native WebSockets implementations, 2000 byte payload, 10ms delay + +Chrome 8.0.552 - native WebSockets + Packets sent: 2998 + Packets Received: 2998 + Average Latency: 1.84 + 40 Frame Running Average Latency: 1.90 + Minimum Latency: 1.00 + Maximum Latency: 10.00 + +firefox 4.0b9 - WebSockets enabled + Packets sent: 3011 + Packets Received: 3011 + Average Latency: 6.45 + 40 Frame Running Average Latency: 6.08 + Minimum Latency: 5.00 + Maximum Latency: 119.00 + +Opera 11 - WebSockets enabled + Packets sent: 3065 + Packets Received: 3064 + Average Latency: 9.56 + 40 Frame Running Average Latency: 8.15 + Minimum Latency: 4.00 + Maximum Latency: 53.00 + +------------------------------------------------------------ + +New web-socket-js (20f837425d4), 2000 byte payload, 10ms delay + +firefox 4.0b9 - no WebSockets + Packets sent: 3088 + Packets Received: 3087 + Average Latency: 16.71 + 40 Frame Running Average Latency: 16.80 + Minimum Latency: 7.00 + Maximum Latency: 75.00 + + - First 1000 sent in 13 seconds + - Second 1000 sent in 12 seconds + - Third 1000 sent in 12 seconds + +firefox 3.6.10 - no WebSockets + Packets sent: 3100 + Packets Received: 3099 + Average Latency: 17.32 + 40 Frame Running Average Latency: 16.73 + Minimum Latency: 6.00 + Maximum Latency: 72.00 + +Opera 11 - no WebSockets + Packets sent: 3007 + Packets Received: 3007 + Average Latency: 465.91 + 40 Frame Running Average Latency: 147.95 + Minimum Latency: 12.00 + Maximum Latency: 9143.00 + + - average starts at around 28ms + - time for each 500 packets: 13s, 16s, 25s, 37s, 50s, 72s + - also start seeing sent, receive lags around 1200 packets + +--------------------------------------------------------------- + +Old web-socket-js (9e7663771), 2000 byte payload, 10ms delay + +firefox 4.0b9 - no WebSockets + Packets sent: 3024 + Packets Received: 3020 + Average Latency: 80.59 + 40 Frame Running Average Latency: 60.15 + Minimum Latency: 10.00 + Maximm Latency: 348.00 + + +firefox 3.6.10 - no WebSockets + Packets sent: 2777 + Packets Received: 2775 + Average Latency: 34.89 + 40 Frame Running Average Latency: 24.50 + Minimum Latency: 10.00 + Maximum Latency: 208.00 + + +Opera 11 - no Websockets + Packets sent: 3012 + Packets Received: 3011 + Average Latency: 380.87 + 40 Frame Running Average Latency: 341.90 + Minimum Latency: 28.00 + Maximum Latency: 2175.00 + + - average starts at around 290ms + - time for each 1000 packets: 23s, 38s, 65s + diff --git a/third_party/websockify/docs/notes b/third_party/websockify/docs/notes new file mode 100644 index 00000000..b3cc0cfb --- /dev/null +++ b/third_party/websockify/docs/notes @@ -0,0 +1,17 @@ +Some implementation notes: + +There is an included flash object (web-socket-js) that is used to +emulate websocket support on browsers without websocket support +(currently only Chrome has WebSocket support). + +Javascript doesn't have a bytearray type, so what you get out of +a WebSocket object is just Javascript strings. Javascript has UTF-16 +unicode strings and anything sent through the WebSocket gets converted +to UTF-8 and vice-versa. So, one additional (and necessary) function +of wsproxy is base64 encoding/decoding what is sent to/from the +browser. + +Building web-socket-js emulator: + +cd include/web-socket-js/flash-src +mxmlc -static-link-runtime-shared-libraries WebSocketMain.as diff --git a/third_party/websockify/docs/release.txt b/third_party/websockify/docs/release.txt new file mode 100644 index 00000000..5750c88a --- /dev/null +++ b/third_party/websockify/docs/release.txt @@ -0,0 +1,9 @@ +- Update setup.py and CHANGES.txt and commit +- Create version tag and tarball from tag + WVER=0.1.0 + git tag v${WVER} + git push origin master + git push origin v${WVER} + git archive --format=tar --prefix=websockify-${WVER}/ v${WVER} > websockify-${WVER}.tar + gzip websockify-${WVER}.tar +- Upload tarball to repo diff --git a/third_party/websockify/docs/websockify.1 b/third_party/websockify/docs/websockify.1 new file mode 100644 index 00000000..ab04b7a7 --- /dev/null +++ b/third_party/websockify/docs/websockify.1 @@ -0,0 +1,110 @@ +.TH websockify 1 "June 7, 2012" "version 0.3" "USER COMMANDS" + +.SH NAME + +websockify - WebSockets to TCP socket bridge + +.SH SYNOPSIS + + websockify [options] [source_addr:]source_port target_addr:target_port + websockify [options] [source_addr:]source_port \-\- WRAP_COMMAND_LINE + +.SH OPTIONS + + -h, --help show this help message and exit + -v, --verbose verbose messages and per frame traffic + --record=FILE record sessions to FILE.[session_number] + -D, --daemon become a daemon (background process) + --run-once handle a single WebSocket connection and exit + --timeout=TIMEOUT after TIMEOUT seconds exit when not connected + --cert=CERT SSL certificate file + --key=KEY SSL key file (if separate from cert) + --ssl-only disallow non-encrypted connections + --web=DIR run webserver on same port. Serve files from DIR. + --wrap-mode=MODE action to take when the wrapped program exits or + daemonizes: exit (default), ignore, respawn + +.SH DESCRIPTION + +At the most basic level, websockify just translates WebSockets traffic to normal TCP socket traffic. Websockify accepts the WebSockets handshake, parses it, and then begins forwarding traffic between the client and the target in both directions. + +websockify was formerly named wsproxy and was part of the noVNC project. + +.SH NOTES + +.SS WebSockets binary data + +Websockify supports all versions of the WebSockets protocol (Hixie and HyBI). The older Hixie versions of the protocol only support UTF-8 text payloads. In order to transport binary data over UTF-8 an encoding must used to encapsulate the data within UTF-8. Websockify uses base64 to encode all traffic to and from the client. This does not affect the data between websockify and the server. + +.SS Encrypted WebSocket connections (wss://) + +To encrypt the traffic using the WebSocket 'wss://' URI scheme you need to generate a certificate for websockify to load. By default websockify loads a certificate file name self.pem but the --cert=CERT option can override the file name. You can generate a self-signed certificate using openssl. When asked for the common name, use the hostname of the server where the proxy will be running: + +openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem + +.SS Websock Javascript library + +The websock.js (see https://github.com/kanaka/websockify) Javascript library library provides a Websock object that is similar to the standard WebSocket object but Websock enables communication with raw TCP sockets (i.e. the binary stream) via websockify. This is accomplished by base64 encoding the data stream between Websock and websockify. + +Websock has built-in receive queue buffering; the message event does not contain actual data but is simply a notification that there is new data available. Several rQ* methods are available to read binary data off of the receive queue. + +The Websock API is documented on the websock.js API wiki page: + +https://github.com/kanaka/websockify/wiki/websock.js + +See the "Wrap a Program" section below for an example of using Websock and websockify as a browser telnet client (wstelnet.html). + +.SS Additional websockify features + +These are not necessary for the basic operation. + +.IP * +Daemonizing: When the -D option is specified, websockify runs in the background as a daemon process. + +.IP * +SSL (the wss:// WebSockets URI): This is detected automatically by websockify by sniffing the first byte sent from the client and then wrapping the socket if the data starts with '\\x16' or '\\x80' (indicating SSL). + +.IP * +Flash security policy: websockify detects flash security policy requests (again by sniffing the first packet) and answers with an appropriate flash security policy response (and then closes the port). This means no separate flash security policy server is needed for supporting the flash WebSockets fallback emulator. + +.IP * +Session recording: This feature that allows recording of the traffic sent and received from the client to a file using the --record option. + +.IP * +Mini-webserver: websockify can detect and respond to normal web requests on the same port as the WebSockets proxy and Flash security policy. This functionality is activate with the --web DIR option where DIR is the root of the web directory to serve. + +.IP * +Wrap a program: see the "Wrap a Program" section below. + +.SS Wrap a Program + +In addition to proxying from a source address to a target address (which may be on a different system), websockify has the ability to launch a program on the local system and proxy WebSockets traffic to a normal TCP port owned/bound by the program. + +The is accomplished with a small LD_PRELOAD library (rebind.so) which intercepts bind() system calls by the program. The specified port is moved to a new localhost/loopback free high port. websockify then proxies WebSockets traffic directed to the original port to the new (moved) port of the program. + +The program wrap mode is invoked by replacing the target with -- followed by the program command line to wrap. + +`./websockify 2023 -- PROGRAM ARGS` + +The --wrap-mode option can be used to indicate what action to take when the wrapped program exits or daemonizes. + +Here is an example of using websockify to wrap the vncserver command (which backgrounds itself) for use with noVNC: + +`./websockify 5901 --wrap-mode=ignore -- vncserver -geometry 1024x768 :1` + +Here is an example of wrapping telnetd (from krb5-telnetd).telnetd exits after the connection closes so the wrap mode is set to respawn the command: + +`sudo ./websockify 2023 --wrap-mode=respawn -- telnetd -debug 2023` + +The wstelnet.html page demonstrates a simple WebSockets based telnet client. + + +.SH AUTHOR +Joel Martin (github@martintribe.org) + +.SH SEE ALSO + +https://github.com/kanaka/websockify/ + +https://github.com/kanaka/websockify/wiki/ + diff --git a/third_party/websockify/include/VT100.js b/third_party/websockify/include/VT100.js new file mode 100644 index 00000000..6a325e13 --- /dev/null +++ b/third_party/websockify/include/VT100.js @@ -0,0 +1,919 @@ +// VT100.js -- a text terminal emulator in JavaScript with a ncurses-like +// interface and a POSIX-like interface. (The POSIX-like calls are +// implemented on top of the ncurses-like calls, not the other way round.) +// +// Released under the GNU LGPL v2.1, by Frank Bi <bi@zompower.tk> +// +// 2007-08-12 - refresh(): +// - factor out colour code to html_colours_() +// - fix handling of A_REVERSE | A_DIM +// - simplify initial <br /> output code +// - fix underlining colour +// - fix attron() not to turn off attributes +// - decouple A_STANDOUT and A_BOLD +// 2007-08-11 - getch() now calls refresh() +// 2007-08-06 - Safari compat fix -- turn '\r' into '\n' for onkeypress +// 2007-08-05 - Opera compat fixes for onkeypress +// 2007-07-30 - IE compat fixes: +// - change key handling code +// - add <br />...<br /> so that 1st and last lines align +// 2007-07-28 - change wrapping behaviour -- writing at the right edge no +// longer causes the cursor to immediately wrap around +// - add <b>...</b> to output to make A_STANDOUT stand out more +// - add handling of backspace, tab, return keys +// - fix doc. of VT100() constructor +// - change from GPL to LGPL +// 2007-07-09 - initial release +// +// class VT100 +// A_NORMAL, A_UNDERLINE, A_REVERSE, A_BLINK, A_DIM, A_BOLD, A_STANDOUT +// =class constants= +// Attribute constants. +// VT100(wd, ht, scr_id) =constructor= +// Creates a virtual terminal with width `wd', and +// height `ht'. The terminal will be displayed between +// <pre>...</pre> tags which have element ID `scr_id'. +// addch(ch [, attr]) +// Writes out the character `ch'. If `attr' is given, +// it specifies the attributes for the character, +// otherwise the current attributes are used. +// addstr(stuff) Writes out the string `stuff' using the current +// attributes. +// attroff(mode) Turns off any current options given in mode. +// attron(mode) Turns on any options given in mode. +// attrset(mode) Sets the current options to mode. +// bkgdset(attr) Sets the background attributes to attr. +// clear() Clears the terminal using the background attributes, +// and homes the cursor. +// clrtobol() Clears the portion of the terminal from the cursor +// to the bottom. +// clrtoeol() Clears the portion of the current line after the +// cursor. +// curs_set(vis [, grab]) +// If `vis' is 0, makes the cursor invisible; otherwise +// make it visible. If `grab' is given and true, starts +// capturing keyboard events (for `getch()'); if given +// and false, stops capturing events. +// echo() Causes key strokes to be automatically echoed on the +// terminal. +// erase() Same as `clear()'. +// getch(isr) Arranges to call `isr' when a key stroke is +// received. The received character and the terminal +// object are passed as arguments to `isr'. +// getmaxyx() Returns an associative array with the maximum row +// (`y') and column (`x') numbers for the terminal. +// getyx() Returns an associative array with the current row +// (`y') and column (`x') of the cursor. +// move(r, c) Moves the cursor to row `r', column `c'. +// noecho() Stops automatically echoing key strokes. +// refresh() Updates the display. +// scroll() Scrolls the terminal up one line. +// standend() Same as `attrset(VT100.A_NORMAL)'. +// standout() Same as `attron(VT100.A_STANDOUT)'. +// write(stuff) Writes `stuff' to the terminal and immediately +// updates the display; (some) escape sequences are +// interpreted and acted on. + +// constructor +function VT100(wd, ht, scr_id) +{ + var r; + var c; + var scr = document.getElementById(scr_id); + this.wd_ = wd; + this.ht_ = ht; + this.scrolled_ = 0; + this.bkgd_ = { + mode: VT100.A_NORMAL, + fg: VT100.COLOR_WHITE, + bg: VT100.COLOR_BLACK + }; + this.c_attr_ = { + mode: VT100.A_NORMAL, + fg: VT100.COLOR_WHITE, + bg: VT100.COLOR_BLACK + }; + this.text_ = new Array(ht); + this.attr_ = new Array(ht); + for (r = 0; r < ht; ++r) { + this.text_[r] = new Array(wd); + this.attr_[r] = new Array(wd); + } + this.scr_ = scr; + this.cursor_vis_ = true; + this.grab_events_ = false; + this.getch_isr_ = undefined; + this.key_buf_ = []; + this.echo_ = true; + this.esc_state_ = 0; + // Internal debug setting. + this.debug_ = 0; + this.clear(); + this.refresh(); +} + +// public constants -- colours and colour pairs +VT100.COLOR_BLACK = 0; +VT100.COLOR_BLUE = 1; +VT100.COLOR_GREEN = 2; +VT100.COLOR_CYAN = 3; +VT100.COLOR_RED = 4; +VT100.COLOR_MAGENTA = 5; +VT100.COLOR_YELLOW = 6; +VT100.COLOR_WHITE = 7; +VT100.COLOR_PAIRS = 256; +VT100.COLORS = 8; +// public constants -- attributes +VT100.A_NORMAL = 0; +VT100.A_UNDERLINE = 1; +VT100.A_REVERSE = 2; +VT100.A_BLINK = 4; +VT100.A_DIM = 8; +VT100.A_BOLD = 16; +VT100.A_STANDOUT = 32; +VT100.A_PROTECT = VT100.A_INVIS = 0; // ? +// other public constants +VT100.TABSIZE = 8; +// private constants +VT100.ATTR_FLAGS_ = VT100.A_UNDERLINE | VT100.A_REVERSE | VT100.A_BLINK | + VT100.A_DIM | VT100.A_BOLD | VT100.A_STANDOUT | + VT100.A_PROTECT | VT100.A_INVIS; +VT100.COLOR_SHIFT_ = 6; +VT100.browser_ie_ = (navigator.appName.indexOf("Microsoft") != -1); +VT100.browser_opera_ = (navigator.appName.indexOf("Opera") != -1); +// class variables +VT100.the_vt_ = undefined; + +// class methods + +// this is actually an event handler +VT100.handle_onkeypress_ = function VT100_handle_onkeypress(event) +{ + var vt = VT100.the_vt_, ch; + if (vt === undefined) + return true; + if (VT100.browser_ie_ || VT100.browser_opera_) { + ch = event.keyCode; + if (ch == 13) + ch = 10; + else if (ch > 255 || (ch < 32 && ch != 8)) + return true; + ch = String.fromCharCode(ch); + } else { + ch = event.charCode; + //dump("ch: " + ch + "\n"); + //dump("ctrl?: " + event.ctrlKey + "\n"); + vt.debug("onkeypress:: keyCode: " + event.keyCode + ", ch: " + event.charCode); + if (ch) { + if (ch > 255) + return true; + if (event.ctrlKey && event.shiftKey) { + // Don't send the copy/paste commands. + var charStr = String.fromCharCode(ch); + if (charStr == 'C' || charStr == 'V') { + return false; + } + } + if (event.ctrlKey) { + ch = String.fromCharCode(ch - 96); + } else { + ch = String.fromCharCode(ch); + if (ch == '\r') + ch = '\n'; + } + } else { + switch (event.keyCode) { + case event.DOM_VK_BACK_SPACE: + ch = '\b'; + break; + case event.DOM_VK_TAB: + ch = '\t'; + // Stop tab from moving to another element. + event.preventDefault(); + break; + case event.DOM_VK_RETURN: + case event.DOM_VK_ENTER: + ch = '\n'; + break; + case event.DOM_VK_UP: + ch = '\x1b[A'; + break; + case event.DOM_VK_DOWN: + ch = '\x1b[B'; + break; + case event.DOM_VK_RIGHT: + ch = '\x1b[C'; + break; + case event.DOM_VK_LEFT: + ch = '\x1b[D'; + break; + case event.DOM_VK_DELETE: + ch = '\x1b[3~'; + break; + case event.DOM_VK_HOME: + ch = '\x1b[H'; + break; + case event.DOM_VK_ESCAPE: + ch = '\x1bc'; + break; + default: + return true; + } + } + } + vt.key_buf_.push(ch); + setTimeout(VT100.go_getch_, 0); + return false; +} + +// this is actually an event handler +VT100.handle_onkeydown_ = function VT100_handle_onkeydown() +{ + var vt = VT100.the_vt_, ch; + switch (event.keyCode) { + case 8: + ch = '\b'; break; + default: + return true; + } + vt.key_buf_.push(ch); + setTimeout(VT100.go_getch_, 0); + return false; +} + +VT100.go_getch_ = function VT100_go_getch() +{ + var vt = VT100.the_vt_; + if (vt === undefined) + return; + var isr = vt.getch_isr_; + vt.getch_isr_ = undefined; + if (isr === undefined) + return; + var ch = vt.key_buf_.shift(); + if (ch === undefined) { + vt.getch_isr_ = isr; + return; + } + if (vt.echo_) + vt.addch(ch); + isr(ch, vt); +} + +// object methods + +VT100.prototype.may_scroll_ = function() +{ + var ht = this.ht_, cr = this.row_; + while (cr >= ht) { + this.scroll(); + --cr; + } + this.row_ = cr; +} + +VT100.prototype.html_colours_ = function(attr) +{ + var fg, bg, co0, co1; + fg = attr.fg; + bg = attr.bg; + switch (attr.mode & (VT100.A_REVERSE | VT100.A_DIM | VT100.A_BOLD)) { + case 0: + case VT100.A_DIM | VT100.A_BOLD: + co0 = '00'; co1 = 'c0'; + break; + case VT100.A_BOLD: + co0 = '00'; co1 = 'ff'; + break; + case VT100.A_DIM: + if (fg == VT100.COLOR_BLACK) + co0 = '40'; + else + co0 = '00'; + co1 = '40'; + break; + case VT100.A_REVERSE: + case VT100.A_REVERSE | VT100.A_DIM | VT100.A_BOLD: + co0 = 'c0'; co1 = '40'; + break; + case VT100.A_REVERSE | VT100.A_BOLD: + co0 = 'c0'; co1 = '00'; + break; + default: + if (fg == VT100.COLOR_BLACK) + co0 = '80'; + else + co0 = 'c0'; + co1 = 'c0'; + } + return { + f: '#' + (fg & 4 ? co1 : co0) + + (fg & 2 ? co1 : co0) + + (fg & 1 ? co1 : co0), + b: '#' + (bg & 4 ? co1 : co0) + + (bg & 2 ? co1 : co0) + + (bg & 1 ? co1 : co0) + }; +} + +VT100.prototype.addch = function(ch, attr) +{ + var cc = this.col_; + this.debug("addch:: ch: " + ch + ", attr: " + attr); + switch (ch) { + case '\b': + if (cc != 0) + --cc; + break; + case '\n': + ++this.row_; + cc = 0; + this.clrtoeol(); + this.may_scroll_(); + break; + case '\r': + this.may_scroll_(); + cc = 0; + break; + case '\t': + this.may_scroll_(); + cc += VT100.TABSIZE - cc % VT100.TABSIZE; + if (cc >= this.wd_) { + ++this.row_; + cc -= this.wd_; + } + break; + default: + if (attr === undefined) + attr = this._cloneAttr(this.c_attr_); + if (cc >= this.wd_) { + ++this.row_; + cc = 0; + } + this.may_scroll_(); + this.text_[this.row_][cc] = ch; + this.attr_[this.row_][cc] = attr; + ++cc; + } + this.col_ = cc; +} + +VT100.prototype.addstr = function(stuff) +{ + for (var i = 0; i < stuff.length; ++i) + this.addch(stuff.charAt(i)); +} + +VT100.prototype._cloneAttr = function VT100_cloneAttr(a) +{ + return { + mode: a.mode, + fg: a.fg, + bg: a.bg + }; +} + +VT100.prototype.attroff = function(a) +{ + //dump("attroff: " + a + "\n"); + a &= VT100.ATTR_FLAGS_; + this.c_attr_.mode &= ~a; +} + +VT100.prototype.attron = function(a) +{ + //dump("attron: " + a + "\n"); + a &= VT100.ATTR_FLAGS_; + this.c_attr_.mode |= a; +} + +VT100.prototype.attrset = function(a) +{ + //dump("attrset: " + a + "\n"); + this.c_attr_.mode = a; +} + +VT100.prototype.fgset = function(fg) +{ + //dump("fgset: " + fg + "\n"); + this.c_attr_.fg = fg; +} + +VT100.prototype.bgset = function(bg) +{ + //dump("bgset: " + bg + "\n"); + if (bg !== 0) { + this.warn("bgset: " + bg + "\n"); + } + this.c_attr_.bg = bg; +} + +VT100.prototype.bkgdset = function(a) +{ + this.bkgd_ = a; +} + +VT100.prototype.clear = function() +{ + this.debug("clear"); + this.row_ = this.col_ = 0; + this.scrolled_ = 0; + for (r = 0; r < this.ht_; ++r) { + for (c = 0; c < this.wd_; ++c) { + this.text_[r][c] = ' '; + this.attr_[r][c] = this._cloneAttr(this.bkgd_); + } + } +} + +VT100.prototype.clrtobot = function() +{ + this.debug("clrtobot, row: " + this.row_); + var ht = this.ht_; + var wd = this.wd_; + this.clrtoeol(); + for (var r = this.row_ + 1; r < ht; ++r) { + for (var c = 0; c < wd; ++c) { + this.text_[r][c] = ' '; + this.attr_[r][c] = this.bkgd_; + } + } +} + +VT100.prototype.clrtoeol = function() +{ + this.debug("clrtoeol, col: " + this.col_); + var r = this.row_; + if (r >= this.ht_) + return; + for (var c = this.col_; c < this.wd_; ++c) { + this.text_[r][c] = ' '; + this.attr_[r][c] = this.bkgd_; + } +} + +VT100.prototype.clearpos = function(row, col) +{ + this.debug("clearpos (" + row + ", " + col + ")"); + if (row < 0 || row >= this.ht_) + return; + if (col < 0 || col >= this.wd_) + return; + this.text_[row][col] = ' '; + this.attr_[row][col] = this.bkgd_; +} + +VT100.prototype.curs_set = function(vis, grab, eventist) +{ + this.debug("curs_set:: vis: " + vis + ", grab: " + grab); + if (vis !== undefined) + this.cursor_vis_ = (vis > 0); + if (eventist === undefined) + eventist = window; + if (grab === true || grab === false) { + if (grab === this.grab_events_) + return; + if (grab) { + this.grab_events_ = true; + VT100.the_vt_ = this; + eventist.addEventListener("keypress", VT100.handle_onkeypress_, false); + if (VT100.browser_ie_) + document.onkeydown = VT100.handle_onkeydown_; + } else { + eventist.removeEventListener("keypress", VT100.handle_onkeypress_, false); + if (VT100.browser_ie_) + document.onkeydown = VT100.handle_onkeydown_; + this.grab_events_ = false; + VT100.the_vt_ = undefined; + } + } +} + +VT100.prototype.echo = function() +{ + this.debug("echo on"); + this.echo_ = true; +} + +VT100.prototype.erase = VT100.prototype.clear; + +VT100.prototype.getch = function(isr) +{ + this.debug("getch"); + this.refresh(); + this.getch_isr_ = isr; + setTimeout(VT100.go_getch_, 0); +} + +VT100.prototype.getmaxyx = function() +{ + return { y: this.ht_ - 1, x: this.wd_ - 1 }; +} + +VT100.prototype.getyx = function() +{ + return { y: this.row_, x: this.col_ }; +} + +VT100.prototype.move = function(r, c) +{ + this.debug("move: (" + r + ", " + c + ")"); + if (r < 0) + r = 0; + else if (r >= this.ht_) + r = this.ht_ - 1; + if (c < 0) + c = 0; + else if (c >= this.wd_) + c = this.wd_ - 1; + this.row_ = r; + this.col_ = c; +} + +VT100.prototype.noecho = function() +{ + this.debug("echo off"); + this.echo_ = false; +} + +VT100.prototype.refresh = function() +{ + this.debug("refresh"); + var r, c, stuff = "", start_tag = "", end_tag = "", at = -1, n_at, ch, + pair, cr, cc, ht, wd, cv, added_end_tag; + ht = this.ht_; + wd = this.wd_; + cr = this.row_; + cc = this.col_; + cv = this.cursor_vis_; + var innerHTML = this.scr_.innerHTML; + if (cc >= wd) + cc = wd - 1; + for (r = 0; r < ht; ++r) { + if (r > 0) { + stuff += '\n'; + } + for (c = 0; c < wd; ++c) { + added_end_tag = false; + n_at = this.attr_[r][c]; + if (cv && r == cr && c == cc) { + // Draw the cursor here. + n_at = this._cloneAttr(n_at); + n_at.mode ^= VT100.A_REVERSE; + } + // If the attributes changed, make a new span. + if (n_at.mode != at.mode || n_at.fg != at.fg || n_at.bg != at.bg) { + if (c > 0) { + stuff += end_tag; + } + start_tag = ""; + end_tag = ""; + if (n_at.mode & VT100.A_BLINK) { + start_tag = "<blink>"; + end_tag = "</blink>" + end_tag; + } + if (n_at.mode & VT100.A_STANDOUT) + n_at.mode |= VT100.A_BOLD; + pair = this.html_colours_(n_at); + start_tag += '<span style="color:' + pair.f + + ';background-color:' + pair.b; + if (n_at.mode & VT100.A_UNDERLINE) + start_tag += ';text-decoration:underline'; + start_tag += ';">'; + stuff += start_tag; + end_tag = "</span>" + end_tag; + at = n_at; + added_end_tag = true; + } else if (c == 0) { + stuff += start_tag; + } + ch = this.text_[r][c]; + switch (ch) { + case '&': + stuff += '&'; break; + case '<': + stuff += '<'; break; + case '>': + stuff += '>'; break; + case ' ': + //stuff += ' '; break; + stuff += ' '; break; + default: + stuff += ch; + } + } + if (!added_end_tag) + stuff += end_tag; + } + this.scr_.innerHTML = "<b>" + stuff + "</b>\n"; +} + +VT100.prototype.scroll = function() +{ + this.scrolled_ += 1; + this.debug("scrolled: " + this.scrolled_); + var n_text = this.text_[0], n_attr = this.attr_[0], + ht = this.ht_, wd = this.wd_; + for (var r = 1; r < ht; ++r) { + this.text_[r - 1] = this.text_[r]; + this.attr_[r - 1] = this.attr_[r]; + } + this.text_[ht - 1] = n_text; + this.attr_[ht - 1] = n_attr; + for (var c = 0; c < wd; ++c) { + n_text[c] = ' '; + n_attr[c] = this.bkgd_; + } +} + +VT100.prototype.standend = function() +{ + //this.debug("standend"); + this.attrset(0); +} + +VT100.prototype.standout = function() +{ + //this.debug("standout"); + this.attron(VT100.A_STANDOUT); +} + +VT100.prototype.write = function(stuff) +{ + var ch, x, r, c, i, j, yx, myx; + for (i = 0; i < stuff.length; ++i) { + ch = stuff.charAt(i); + if (ch == '\x0D') { + this.debug("write:: ch: " + ch.charCodeAt(0) + ", '\\x0D'"); + } else { + this.debug("write:: ch: " + ch.charCodeAt(0) + ", '" + (ch == '\x1b' ? "ESC" : ch) + "'"); + } + //dump("ch: " + ch.charCodeAt(0) + ", '" + (ch == '\x1b' ? "ESC" : ch) + "'\n"); + switch (ch) { + case '\x00': + case '\x7f': + case '\x07': /* bell, ignore it */ + this.debug("write:: ignoring bell character: " + ch); + continue; + case '\a': + case '\b': + case '\t': + case '\r': + this.addch(ch); + continue; + case '\n': + case '\v': + case '\f': // what a mess + yx = this.getyx(); + myx = this.getmaxyx(); + if (yx.y >= myx.y) { + this.scroll(); + this.move(myx.y, 0); + } else + this.move(yx.y + 1, 0); + continue; + case '\x18': + case '\x1a': + this.esc_state_ = 0; + this.debug("write:: set escape state: 0"); + continue; + case '\x1b': + this.esc_state_ = 1; + this.debug("write:: set escape state: 1"); + continue; + case '\x9b': + this.esc_state_ = 2; + this.debug("write:: set escape state: 2"); + continue; + } + // not a recognized control character + switch (this.esc_state_) { + case 0: // not in escape sequence + this.addch(ch); + break; + case 1: // just saw ESC + switch (ch) { + case '[': + this.esc_state_ = 2; + this.debug("write:: set escape state: 2"); + break; + case '=': + /* Set keypade mode (ignored) */ + this.debug("write:: set keypade mode: ignored"); + this.esc_state_ = 0; + break; + case '>': + /* Reset keypade mode (ignored) */ + this.debug("write:: reset keypade mode: ignored"); + this.esc_state_ = 0; + break; + case 'H': + /* Set tab at cursor column (ignored) */ + this.debug("write:: set tab cursor column: ignored"); + this.esc_state_ = 0; + break; + } + break; + case 2: // just saw CSI + switch (ch) { + case 'K': + /* Erase in Line */ + this.esc_state_ = 0; + this.clrtoeol(); + continue; + case 'H': + /* Move to (0,0). */ + this.esc_state_ = 0; + this.move(0, 0); + continue; + case 'J': + /* Clear to the bottom. */ + this.esc_state_ = 0; + this.clrtobot(); + continue; + case '?': + /* Special VT100 mode handling. */ + this.esc_state_ = 5; + this.debug("write:: special vt100 mode"); + continue; + } + // Drop through to next case. + this.csi_parms_ = [0]; + this.debug("write:: set escape state: 3"); + this.esc_state_ = 3; + case 3: // saw CSI and parameters + switch (ch) { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + x = this.csi_parms_.pop(); + this.csi_parms_.push(x * 10 + ch * 1); + this.debug("csi_parms_: " + this.csi_parms_); + continue; + case ';': + if (this.csi_parms_.length < 17) + this.csi_parms_.push(0); + continue; + } + this.esc_state_ = 0; + switch (ch) { + case 'A': + // Cursor Up <ESC>[{COUNT}A + this.move(this.row_ - Math.max(1, this.csi_parms_[0]), + this.col_); + break; + case 'B': + // Cursor Down <ESC>[{COUNT}B + this.move(this.row_ + Math.max(1, this.csi_parms_[0]), + this.col_); + break; + case 'C': + // Cursor Forward <ESC>[{COUNT}C + this.move(this.row_, + this.col_ + Math.max(1, this.csi_parms_[0])); + break; + case 'c': + this.warn("write:: got TERM query"); + break; + case 'D': + // Cursor Backward <ESC>[{COUNT}D + this.move(this.row_, + this.col_ - Math.max(1, this.csi_parms_[0])); + break; + case 'f': + case 'H': + // Cursor Home <ESC>[{ROW};{COLUMN}H + this.csi_parms_.push(0); + this.move(this.csi_parms_[0] - 1, + this.csi_parms_[1] - 1); + break; + case 'J': + switch (this.csi_parms_[0]) { + case 0: + this.clrtobot(); + break; + case 2: + this.clear(); + this.move(0, 0); + } + break; + case 'm': + for (j=0; j<this.csi_parms_.length; ++j) { + x = this.csi_parms_[j]; + switch (x) { + case 0: + this.standend(); + this.fgset(this.bkgd_.fg); + this.bgset(this.bkgd_.bg); + break; + case 1: + this.attron(VT100.A_BOLD); + break; + case 30: + this.fgset(VT100.COLOR_BLACK); + break; + case 31: + this.fgset(VT100.COLOR_RED); + break; + case 32: + this.fgset(VT100.COLOR_GREEN); + break; + case 33: + this.fgset(VT100.COLOR_YELLOW); + break; + case 34: + this.fgset(VT100.COLOR_BLUE); + break; + case 35: + this.fgset(VT100.COLOR_MAGENTA); + break; + case 36: + this.fgset(VT100.COLOR_CYAN); + break; + case 37: + this.fgset(VT100.COLOR_WHITE); + break; + case 40: + this.bgset(VT100.COLOR_BLACK); + break; + case 41: + this.bgset(VT100.COLOR_RED); + break; + case 42: + this.bgset(VT100.COLOR_GREEN); + break; + case 44: + this.bgset(VT100.COLOR_YELLOW); + break; + case 44: + this.bgset(VT100.COLOR_BLUE); + break; + case 45: + this.bgset(VT100.COLOR_MAGENTA); + break; + case 46: + this.bgset(VT100.COLOR_CYAN); + break; + case 47: + this.bgset(VT100.COLOR_WHITE); + break; + } + } + break; + case 'r': + // 1,24r - set scrolling region (ignored) + break; + case '[': + this.debug("write:: set escape state: 4"); + this.esc_state_ = 4; + break; + case 'g': + // 0g: clear tab at cursor (ignored) + // 3g: clear all tabs (ignored) + break; + default: + this.warn("write:: unknown command: " + ch); + this.csi_parms_ = []; + break; + } + break; + case 4: // saw CSI [ + this.esc_state_ = 0; // gobble char. + break; + case 5: // Special mode handling, saw <ESC>[? + // Expect a number - the reset type + this.csi_parms_ = [ch]; + this.esc_state_ = 6; + break; + case 6: // Reset mode handling, saw <ESC>[?1 + // Expect a letter - the mode target, example: + // <ESC>[?1l : cursor key mode = cursor + // <ESC>[?1h : save current screen, create new empty + // screen and position at 0,0 + // <ESC>[?5l : White on blk + // XXX: Ignored for now. + //dump("Saw reset mode: <ESC>[?" + this.csi_parms_[0] + ch + "\n"); + this.esc_state_ = 0; + this.debug("write:: set escape state: 0"); + break; + } + } + this.refresh(); +} + +VT100.prototype.debug = function(message) { + if (this.debug_) { + dump(message + "\n"); + } +} + +VT100.prototype.warn = function(message) { + dump(message + "\n"); +} diff --git a/third_party/websockify/include/base64.js b/third_party/websockify/include/base64.js new file mode 100644 index 00000000..e9b3c522 --- /dev/null +++ b/third_party/websockify/include/base64.js @@ -0,0 +1,147 @@ +/* + * Modified from: + * http://lxr.mozilla.org/mozilla/source/extensions/xml-rpc/src/nsXmlRpcClient.js#956 + */ + +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Mozilla XML-RPC Client component. + * + * The Initial Developer of the Original Code is + * Digital Creations 2, Inc. + * Portions created by the Initial Developer are Copyright (C) 2000 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Martijn Pieters <mj@digicool.com> (original author) + * Samuel Sieb <samuel@sieb.net> + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +/*jslint white: false, bitwise: false, plusplus: false */ +/*global console */ + +var Base64 = { + +/* Convert data (an array of integers) to a Base64 string. */ +toBase64Table : 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', +base64Pad : '=', + +encode: function (data) { + "use strict"; + var result = '', + chrTable = Base64.toBase64Table.split(''), + pad = Base64.base64Pad, + length = data.length, + i; + // Convert every three bytes to 4 ascii characters. + for (i = 0; i < (length - 2); i += 3) { + result += chrTable[data[i] >> 2]; + result += chrTable[((data[i] & 0x03) << 4) + (data[i+1] >> 4)]; + result += chrTable[((data[i+1] & 0x0f) << 2) + (data[i+2] >> 6)]; + result += chrTable[data[i+2] & 0x3f]; + } + + // Convert the remaining 1 or 2 bytes, pad out to 4 characters. + if (length%3) { + i = length - (length%3); + result += chrTable[data[i] >> 2]; + if ((length%3) === 2) { + result += chrTable[((data[i] & 0x03) << 4) + (data[i+1] >> 4)]; + result += chrTable[(data[i+1] & 0x0f) << 2]; + result += pad; + } else { + result += chrTable[(data[i] & 0x03) << 4]; + result += pad + pad; + } + } + + return result; +}, + +/* Convert Base64 data to a string */ +toBinaryTable : [ + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, + 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, + 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, + -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, + 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 +], + +decode: function (data, offset) { + "use strict"; + offset = typeof(offset) !== 'undefined' ? offset : 0; + var binTable = Base64.toBinaryTable, + pad = Base64.base64Pad, + result, result_length, idx, i, c, padding, + leftbits = 0, // number of bits decoded, but yet to be appended + leftdata = 0, // bits decoded, but yet to be appended + data_length = data.indexOf('=') - offset; + + if (data_length < 0) { data_length = data.length - offset; } + + /* Every four characters is 3 resulting numbers */ + result_length = (data_length >> 2) * 3 + Math.floor((data_length%4)/1.5); + result = new Array(result_length); + + // Convert one by one. + for (idx = 0, i = offset; i < data.length; i++) { + c = binTable[data.charCodeAt(i) & 0x7f]; + padding = (data.charAt(i) === pad); + // Skip illegal characters and whitespace + if (c === -1) { + console.error("Illegal character code " + data.charCodeAt(i) + " at position " + i); + continue; + } + + // Collect data into leftdata, update bitcount + leftdata = (leftdata << 6) | c; + leftbits += 6; + + // If we have 8 or more bits, append 8 bits to the result + if (leftbits >= 8) { + leftbits -= 8; + // Append if not padding. + if (!padding) { + result[idx++] = (leftdata >> leftbits) & 0xff; + } + leftdata &= (1 << leftbits) - 1; + } + } + + // If there are any bits left, the base64 string was corrupted + if (leftbits) { + throw {name: 'Base64-Error', + message: 'Corrupted base64 string'}; + } + + return result; +} + +}; /* End of Base64 namespace */ diff --git a/third_party/websockify/include/keysym.js b/third_party/websockify/include/keysym.js new file mode 100644 index 00000000..b24ac889 --- /dev/null +++ b/third_party/websockify/include/keysym.js @@ -0,0 +1,99 @@ +/* + * from noVNC: HTML5 VNC client + * Copyright (C) 2010 Joel Martin + * Licensed under LGPL-3 (see LICENSE.txt) + */ + +/* Translate DOM key down/up event to keysym value */ +function getKeysym(e) { + var evt, keysym; + evt = (e ? e : window.event); + + /* Remap modifier and special keys */ + switch ( evt.keyCode ) { + case 8 : keysym = 0xFF08; break; // BACKSPACE + case 9 : keysym = 0xFF09; break; // TAB + case 13 : keysym = 0xFF0D; break; // ENTER + case 27 : keysym = 0xFF1B; break; // ESCAPE + case 45 : keysym = 0xFF63; break; // INSERT + case 46 : keysym = 0xFFFF; break; // DELETE + case 36 : keysym = 0xFF50; break; // HOME + case 35 : keysym = 0xFF57; break; // END + case 33 : keysym = 0xFF55; break; // PAGE_UP + case 34 : keysym = 0xFF56; break; // PAGE_DOWN + case 37 : keysym = 0xFF51; break; // LEFT + case 38 : keysym = 0xFF52; break; // UP + case 39 : keysym = 0xFF53; break; // RIGHT + case 40 : keysym = 0xFF54; break; // DOWN + case 112 : keysym = 0xFFBE; break; // F1 + case 113 : keysym = 0xFFBF; break; // F2 + case 114 : keysym = 0xFFC0; break; // F3 + case 115 : keysym = 0xFFC1; break; // F4 + case 116 : keysym = 0xFFC2; break; // F5 + case 117 : keysym = 0xFFC3; break; // F6 + case 118 : keysym = 0xFFC4; break; // F7 + case 119 : keysym = 0xFFC5; break; // F8 + case 120 : keysym = 0xFFC6; break; // F9 + case 121 : keysym = 0xFFC7; break; // F10 + case 122 : keysym = 0xFFC8; break; // F11 + case 123 : keysym = 0xFFC9; break; // F12 + case 16 : keysym = 0xFFE1; break; // SHIFT + case 17 : keysym = 0xFFE3; break; // CONTROL + //case 18 : keysym = 0xFFE7; break; // Left Meta (Mac Option) + case 18 : keysym = 0xFFE9; break; // Left ALT (Mac Command) + default : keysym = evt.keyCode; break; + } + + /* Remap symbols */ + switch (keysym) { + case 186 : keysym = 59; break; // ; (IE) + case 187 : keysym = 61; break; // = (IE) + case 188 : keysym = 44; break; // , (Mozilla, IE) + case 109 : // - (Mozilla) + if (Util.Engine.gecko) { + keysym = 45; } + break; + case 189 : keysym = 45; break; // - (IE) + case 190 : keysym = 46; break; // . (Mozilla, IE) + case 191 : keysym = 47; break; // / (Mozilla, IE) + case 192 : keysym = 96; break; // ` (Mozilla, IE) + case 219 : keysym = 91; break; // [ (Mozilla, IE) + case 220 : keysym = 92; break; // \ (Mozilla, IE) + case 221 : keysym = 93; break; // ] (Mozilla, IE) + case 222 : keysym = 39; break; // ' (Mozilla, IE) + } + + /* Remap shifted and unshifted keys */ + if (!!evt.shiftKey) { + switch (keysym) { + case 48 : keysym = 41 ; break; // ) (shifted 0) + case 49 : keysym = 33 ; break; // ! (shifted 1) + case 50 : keysym = 64 ; break; // @ (shifted 2) + case 51 : keysym = 35 ; break; // # (shifted 3) + case 52 : keysym = 36 ; break; // $ (shifted 4) + case 53 : keysym = 37 ; break; // % (shifted 5) + case 54 : keysym = 94 ; break; // ^ (shifted 6) + case 55 : keysym = 38 ; break; // & (shifted 7) + case 56 : keysym = 42 ; break; // * (shifted 8) + case 57 : keysym = 40 ; break; // ( (shifted 9) + + case 59 : keysym = 58 ; break; // : (shifted `) + case 61 : keysym = 43 ; break; // + (shifted ;) + case 44 : keysym = 60 ; break; // < (shifted ,) + case 45 : keysym = 95 ; break; // _ (shifted -) + case 46 : keysym = 62 ; break; // > (shifted .) + case 47 : keysym = 63 ; break; // ? (shifted /) + case 96 : keysym = 126; break; // ~ (shifted `) + case 91 : keysym = 123; break; // { (shifted [) + case 92 : keysym = 124; break; // | (shifted \) + case 93 : keysym = 125; break; // } (shifted ]) + case 39 : keysym = 34 ; break; // " (shifted ') + } + } else if ((keysym >= 65) && (keysym <=90)) { + /* Remap unshifted A-Z */ + keysym += 32; + } + + return keysym; +} + diff --git a/third_party/websockify/include/util.js b/third_party/websockify/include/util.js new file mode 100644 index 00000000..ddc1914c --- /dev/null +++ b/third_party/websockify/include/util.js @@ -0,0 +1,303 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2011 Joel Martin + * Licensed under LGPL-3 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +"use strict"; +/*jslint bitwise: false, white: false */ +/*global window, console, document, navigator, ActiveXObject */ + +// Globals defined here +var Util = {}; + + +/* + * Make arrays quack + */ + +Array.prototype.push8 = function (num) { + this.push(num & 0xFF); +}; + +Array.prototype.push16 = function (num) { + this.push((num >> 8) & 0xFF, + (num ) & 0xFF ); +}; +Array.prototype.push32 = function (num) { + this.push((num >> 24) & 0xFF, + (num >> 16) & 0xFF, + (num >> 8) & 0xFF, + (num ) & 0xFF ); +}; + +// IE does not support map (even in IE9) +//This prototype is provided by the Mozilla foundation and +//is distributed under the MIT license. +//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license +if (!Array.prototype.map) +{ + Array.prototype.map = function(fun /*, thisp*/) + { + var len = this.length; + if (typeof fun != "function") + throw new TypeError(); + + var res = new Array(len); + var thisp = arguments[1]; + for (var i = 0; i < len; i++) + { + if (i in this) + res[i] = fun.call(thisp, this[i], i, this); + } + + return res; + }; +} + +/* + * ------------------------------------------------------ + * Namespaced in Util + * ------------------------------------------------------ + */ + +/* + * Logging/debug routines + */ + +Util._log_level = 'warn'; +Util.init_logging = function (level) { + if (typeof level === 'undefined') { + level = Util._log_level; + } else { + Util._log_level = level; + } + if (typeof window.console === "undefined") { + if (typeof window.opera !== "undefined") { + window.console = { + 'log' : window.opera.postError, + 'warn' : window.opera.postError, + 'error': window.opera.postError }; + } else { + window.console = { + 'log' : function(m) {}, + 'warn' : function(m) {}, + 'error': function(m) {}}; + } + } + + Util.Debug = Util.Info = Util.Warn = Util.Error = function (msg) {}; + switch (level) { + case 'debug': Util.Debug = function (msg) { console.log(msg); }; + case 'info': Util.Info = function (msg) { console.log(msg); }; + case 'warn': Util.Warn = function (msg) { console.warn(msg); }; + case 'error': Util.Error = function (msg) { console.error(msg); }; + case 'none': + break; + default: + throw("invalid logging type '" + level + "'"); + } +}; +Util.get_logging = function () { + return Util._log_level; +}; +// Initialize logging level +Util.init_logging(); + + +// Set configuration default for Crockford style function namespaces +Util.conf_default = function(cfg, api, defaults, v, mode, type, defval, desc) { + var getter, setter; + + // Default getter function + getter = function (idx) { + if ((type in {'arr':1, 'array':1}) && + (typeof idx !== 'undefined')) { + return cfg[v][idx]; + } else { + return cfg[v]; + } + }; + + // Default setter function + setter = function (val, idx) { + if (type in {'boolean':1, 'bool':1}) { + if ((!val) || (val in {'0':1, 'no':1, 'false':1})) { + val = false; + } else { + val = true; + } + } else if (type in {'integer':1, 'int':1}) { + val = parseInt(val, 10); + } else if (type === 'func') { + if (!val) { + val = function () {}; + } + } + if (typeof idx !== 'undefined') { + cfg[v][idx] = val; + } else { + cfg[v] = val; + } + }; + + // Set the description + api[v + '_description'] = desc; + + // Set the getter function + if (typeof api['get_' + v] === 'undefined') { + api['get_' + v] = getter; + } + + // Set the setter function with extra sanity checks + if (typeof api['set_' + v] === 'undefined') { + api['set_' + v] = function (val, idx) { + if (mode in {'RO':1, 'ro':1}) { + throw(v + " is read-only"); + } else if ((mode in {'WO':1, 'wo':1}) && + (typeof cfg[v] !== 'undefined')) { + throw(v + " can only be set once"); + } + setter(val, idx); + }; + } + + // Set the default value + if (typeof defaults[v] !== 'undefined') { + defval = defaults[v]; + } else if ((type in {'arr':1, 'array':1}) && + (! (defval instanceof Array))) { + defval = []; + } + // Coerce existing setting to the right type + //Util.Debug("v: " + v + ", defval: " + defval + ", defaults[v]: " + defaults[v]); + setter(defval); +}; + +// Set group of configuration defaults +Util.conf_defaults = function(cfg, api, defaults, arr) { + var i; + for (i = 0; i < arr.length; i++) { + Util.conf_default(cfg, api, defaults, arr[i][0], arr[i][1], + arr[i][2], arr[i][3], arr[i][4]); + } +}; + + +/* + * Cross-browser routines + */ + +// Get DOM element position on page +Util.getPosition = function (obj) { + var x = 0, y = 0; + if (obj.offsetParent) { + do { + x += obj.offsetLeft; + y += obj.offsetTop; + obj = obj.offsetParent; + } while (obj); + } + return {'x': x, 'y': y}; +}; + +// Get mouse event position in DOM element +Util.getEventPosition = function (e, obj, scale) { + var evt, docX, docY, pos; + //if (!e) evt = window.event; + evt = (e ? e : window.event); + evt = (evt.changedTouches ? evt.changedTouches[0] : evt.touches ? evt.touches[0] : evt); + if (evt.pageX || evt.pageY) { + docX = evt.pageX; + docY = evt.pageY; + } else if (evt.clientX || evt.clientY) { + docX = evt.clientX + document.body.scrollLeft + + document.documentElement.scrollLeft; + docY = evt.clientY + document.body.scrollTop + + document.documentElement.scrollTop; + } + pos = Util.getPosition(obj); + if (typeof scale === "undefined") { + scale = 1; + } + return {'x': (docX - pos.x) / scale, 'y': (docY - pos.y) / scale}; +}; + + +// Event registration. Based on: http://www.scottandrew.com/weblog/articles/cbs-events +Util.addEvent = function (obj, evType, fn){ + if (obj.attachEvent){ + var r = obj.attachEvent("on"+evType, fn); + return r; + } else if (obj.addEventListener){ + obj.addEventListener(evType, fn, false); + return true; + } else { + throw("Handler could not be attached"); + } +}; + +Util.removeEvent = function(obj, evType, fn){ + if (obj.detachEvent){ + var r = obj.detachEvent("on"+evType, fn); + return r; + } else if (obj.removeEventListener){ + obj.removeEventListener(evType, fn, false); + return true; + } else { + throw("Handler could not be removed"); + } +}; + +Util.stopEvent = function(e) { + if (e.stopPropagation) { e.stopPropagation(); } + else { e.cancelBubble = true; } + + if (e.preventDefault) { e.preventDefault(); } + else { e.returnValue = false; } +}; + + +// Set browser engine versions. Based on mootools. +Util.Features = {xpath: !!(document.evaluate), air: !!(window.runtime), query: !!(document.querySelector)}; + +Util.Engine = { + // Version detection break in Opera 11.60 (errors on arguments.callee.caller reference) + //'presto': (function() { + // return (!window.opera) ? false : ((arguments.callee.caller) ? 960 : ((document.getElementsByClassName) ? 950 : 925)); }()), + 'presto': (function() { return (!window.opera) ? false : true; }()), + + 'trident': (function() { + return (!window.ActiveXObject) ? false : ((window.XMLHttpRequest) ? ((document.querySelectorAll) ? 6 : 5) : 4); }()), + 'webkit': (function() { + try { return (navigator.taintEnabled) ? false : ((Util.Features.xpath) ? ((Util.Features.query) ? 525 : 420) : 419); } catch (e) { return false; } }()), + //'webkit': (function() { + // return ((typeof navigator.taintEnabled !== "unknown") && navigator.taintEnabled) ? false : ((Util.Features.xpath) ? ((Util.Features.query) ? 525 : 420) : 419); }()), + 'gecko': (function() { + return (!document.getBoxObjectFor && window.mozInnerScreenX == null) ? false : ((document.getElementsByClassName) ? 19 : 18); }()) +}; +if (Util.Engine.webkit) { + // Extract actual webkit version if available + Util.Engine.webkit = (function(v) { + var re = new RegExp('WebKit/([0-9\.]*) '); + v = (navigator.userAgent.match(re) || ['', v])[1]; + return parseFloat(v, 10); + })(Util.Engine.webkit); +} + +Util.Flash = (function(){ + var v, version; + try { + v = navigator.plugins['Shockwave Flash'].description; + } catch(err1) { + try { + v = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version'); + } catch(err2) { + v = '0 r0'; + } + } + version = v.match(/\d+/g); + return {version: parseInt(version[0] || 0 + '.' + version[1], 10) || 0, build: parseInt(version[2], 10) || 0}; +}()); diff --git a/third_party/websockify/include/web-socket-js/README.txt b/third_party/websockify/include/web-socket-js/README.txt new file mode 100644 index 00000000..2e32ea7f --- /dev/null +++ b/third_party/websockify/include/web-socket-js/README.txt @@ -0,0 +1,109 @@ +* How to try + +Assuming you have Web server (e.g. Apache) running at http://example.com/ . + +- Download web_socket.rb from: + http://github.com/gimite/web-socket-ruby/tree/master +- Run sample Web Socket server (echo server) in example.com with: (#1) + $ ruby web-socket-ruby/samples/echo_server.rb example.com 10081 +- If your server already provides socket policy file at port 843, modify the file to allow access to port 10081. Otherwise you can skip this step. See below for details. +- Publish the web-socket-js directory with your Web server (e.g. put it in ~/public_html). +- Change ws://localhost:10081 to ws://example.com:10081 in sample.html. +- Open sample.html in your browser. +- After "onopen" is shown, input something, click [Send] and confirm echo back. + +#1: First argument of echo_server.rb means that it accepts Web Socket connection from HTML pages in example.com. + + +* Troubleshooting + +If it doesn't work, try these: + +1. Try Chrome and Firefox 3.x. +- It doesn't work on Chrome: +-- It's likely an issue of your code or the server. Debug your code as usual e.g. using console.log. +- It works on Chrome but it doesn't work on Firefox: +-- It's likely an issue of web-socket-js specific configuration (e.g. 3 and 4 below). +- It works on both Chrome and Firefox, but it doesn't work on your browser: +-- Check "Supported environment" section below. Your browser may not be supported by web-socket-js. + +2. Add this line before your code: + WEB_SOCKET_DEBUG = true; +and use Developer Tools (Chrome/Safari) or Firebug (Firefox) to see if console.log outputs any errors. + +3. Make sure you do NOT open your HTML page as local file e.g. file:///.../sample.html. web-socket-js doesn't work on local file. Open it via Web server e.g. http:///.../sample.html. + +4. If you are NOT using web-socket-ruby as your WebSocket server, you need to place Flash socket policy file on your server. See "Flash socket policy file" section below for details. + +5. Check if sample.html bundled with web-socket-js works. + +6. Make sure the port used for WebSocket (10081 in example above) is not blocked by your server/client's firewall. + +7. Install debugger version of Flash Player available here to see Flash errors: +http://www.adobe.com/support/flashplayer/downloads.html + + +* Supported environments + +It should work on: +- Google Chrome 4 or later (just uses native implementation) +- Firefox 3.x, Internet Explorer 8 + Flash Player 9 or later + +It may or may not work on other browsers such as Safari, Opera or IE 6. Patch for these browsers are appreciated, but I will not work on fixing issues specific to these browsers by myself. + + +* Flash socket policy file + +This implementation uses Flash's socket, which means that your server must provide Flash socket policy file to declare the server accepts connections from Flash. + +If you use web-socket-ruby available at +http://github.com/gimite/web-socket-ruby/tree/master +, you don't need anything special, because web-socket-ruby handles Flash socket policy file request. But if you already provide socket policy file at port 843, you need to modify the file to allow access to Web Socket port, because it precedes what web-socket-ruby provides. + +If you use other Web Socket server implementation, you need to provide socket policy file yourself. See +http://www.lightsphere.com/dev/articles/flash_socket_policy.html +for details and sample script to run socket policy file server. node.js implementation is available here: +http://github.com/LearnBoost/Socket.IO-node/blob/master/lib/socket.io/transports/flashsocket.js + +Actually, it's still better to provide socket policy file at port 843 even if you use web-socket-ruby. Flash always try to connect to port 843 first, so providing the file at port 843 makes startup faster. + + +* Cookie considerations + +Cookie is sent if Web Socket host is the same as the origin of JavaScript. Otherwise it is not sent, because I don't know way to send right Cookie (which is Cookie of the host of Web Socket, I heard). + +Note that it's technically possible that client sends arbitrary string as Cookie and any other headers (by modifying this library for example) once you place Flash socket policy file in your server. So don't trust Cookie and other headers if you allow connection from untrusted origin. + + +* Proxy considerations + +The WebSocket spec (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol) specifies instructions for User Agents to support proxied connections by implementing the HTTP CONNECT method. + +The AS3 Socket class doesn't implement this mechanism, which renders it useless for the scenarios where the user trying to open a socket is behind a proxy. + +The class RFC2817Socket (by Christian Cantrell) effectively lets us implement this, as long as the proxy settings are known and provided by the interface that instantiates the WebSocket. As such, if you want to support proxied conncetions, you'll have to supply this information to the WebSocket constructor when Flash is being used. One way to go about it would be to ask the user for proxy settings information if the initial connection fails. + + +* How to host HTML file and SWF file in different domains + +By default, HTML file and SWF file must be in the same domain. You can follow steps below to allow hosting them in different domain. + +WARNING: If you use the method below, HTML files in ANY domains can send arbitrary TCP data to your WebSocket server, regardless of configuration in Flash socket policy file. Arbitrary TCP data means that they can even fake request headers including Origin and Cookie. + +- Unzip WebSocketMainInsecure.zip to extract WebSocketMainInsecure.swf. +- Put WebSocketMainInsecure.swf on your server, instead of WebSocketMain.swf. +- In JavaScript, set WEB_SOCKET_SWF_LOCATION to URL of your WebSocketMainInsecure.swf. + + +* How to build WebSocketMain.swf + +Install Flex 4 SDK: +http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+4 + +$ cd flash-src +$ ./build.sh + + +* License + +New BSD License. diff --git a/third_party/websockify/include/web-socket-js/WebSocketMain.swf b/third_party/websockify/include/web-socket-js/WebSocketMain.swf Binary files differnew file mode 100644 index 00000000..81744669 --- /dev/null +++ b/third_party/websockify/include/web-socket-js/WebSocketMain.swf diff --git a/third_party/websockify/include/web-socket-js/swfobject.js b/third_party/websockify/include/web-socket-js/swfobject.js new file mode 100644 index 00000000..8eafe9dd --- /dev/null +++ b/third_party/websockify/include/web-socket-js/swfobject.js @@ -0,0 +1,4 @@ +/* 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 diff --git a/third_party/websockify/include/web-socket-js/web_socket.js b/third_party/websockify/include/web-socket-js/web_socket.js new file mode 100755 index 00000000..06cc5d02 --- /dev/null +++ b/third_party/websockify/include/web-socket-js/web_socket.js @@ -0,0 +1,391 @@ +// 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(); + }); + } + +})(); diff --git a/third_party/websockify/include/websock.js b/third_party/websockify/include/websock.js new file mode 100644 index 00000000..ccb7d4c1 --- /dev/null +++ b/third_party/websockify/include/websock.js @@ -0,0 +1,427 @@ +/* + * Websock: high-performance binary WebSockets + * Copyright (C) 2012 Joel Martin + * Licensed under LGPL-3 (see LICENSE.txt) + * + * Websock is similar to the standard WebSocket object but Websock + * enables communication with raw TCP sockets (i.e. the binary stream) + * via websockify. This is accomplished by base64 encoding the data + * stream between Websock and websockify. + * + * Websock has built-in receive queue buffering; the message event + * does not contain actual data but is simply a notification that + * there is new data available. Several rQ* methods are available to + * read binary data off of the receive queue. + */ + +/*jslint browser: true, bitwise: false, plusplus: false */ +/*global Util, Base64 */ + + +// Load Flash WebSocket emulator if needed + +// To force WebSocket emulator even when native WebSocket available +//window.WEB_SOCKET_FORCE_FLASH = true; +// To enable WebSocket emulator debug: +//window.WEB_SOCKET_DEBUG=1; + +if (window.WebSocket && !window.WEB_SOCKET_FORCE_FLASH) { + Websock_native = true; +} else if (window.MozWebSocket && !window.WEB_SOCKET_FORCE_FLASH) { + Websock_native = true; + window.WebSocket = window.MozWebSocket; +} else { + /* no builtin WebSocket so load web_socket.js */ + + Websock_native = false; + (function () { + function get_INCLUDE_URI() { + return (typeof INCLUDE_URI !== "undefined") ? + INCLUDE_URI : "include/"; + } + + var start = "<script src='" + get_INCLUDE_URI(), + end = "'><\/script>", extra = ""; + + window.WEB_SOCKET_SWF_LOCATION = get_INCLUDE_URI() + + "web-socket-js/WebSocketMain.swf"; + if (Util.Engine.trident) { + Util.Debug("Forcing uncached load of WebSocketMain.swf"); + window.WEB_SOCKET_SWF_LOCATION += "?" + Math.random(); + } + extra += start + "web-socket-js/swfobject.js" + end; + extra += start + "web-socket-js/web_socket.js" + end; + document.write(extra); + }()); +} + + +function Websock() { +"use strict"; + +var api = {}, // Public API + websocket = null, // WebSocket object + mode = 'base64', // Current WebSocket mode: 'binary', 'base64' + rQ = [], // Receive queue + rQi = 0, // Receive queue index + rQmax = 10000, // Max receive queue size before compacting + sQ = [], // Send queue + + eventHandlers = { + 'message' : function() {}, + 'open' : function() {}, + 'close' : function() {}, + 'error' : function() {} + }, + + test_mode = false; + + +// +// Queue public functions +// + +function get_sQ() { + return sQ; +} + +function get_rQ() { + return rQ; +} +function get_rQi() { + return rQi; +} +function set_rQi(val) { + rQi = val; +} + +function rQlen() { + return rQ.length - rQi; +} + +function rQpeek8() { + return (rQ[rQi] ); +} +function rQshift8() { + return (rQ[rQi++] ); +} +function rQunshift8(num) { + if (rQi === 0) { + rQ.unshift(num); + } else { + rQi -= 1; + rQ[rQi] = num; + } + +} +function rQshift16() { + return (rQ[rQi++] << 8) + + (rQ[rQi++] ); +} +function rQshift32() { + return (rQ[rQi++] << 24) + + (rQ[rQi++] << 16) + + (rQ[rQi++] << 8) + + (rQ[rQi++] ); +} +function rQshiftStr(len) { + if (typeof(len) === 'undefined') { len = rQlen(); } + var arr = rQ.slice(rQi, rQi + len); + rQi += len; + return String.fromCharCode.apply(null, arr); +} +function rQshiftBytes(len) { + if (typeof(len) === 'undefined') { len = rQlen(); } + rQi += len; + return rQ.slice(rQi-len, rQi); +} + +function rQslice(start, end) { + if (end) { + return rQ.slice(rQi + start, rQi + end); + } else { + return rQ.slice(rQi + start); + } +} + +// Check to see if we must wait for 'num' bytes (default to FBU.bytes) +// to be available in the receive queue. Return true if we need to +// wait (and possibly print a debug message), otherwise false. +function rQwait(msg, num, goback) { + var rQlen = rQ.length - rQi; // Skip rQlen() function call + if (rQlen < num) { + if (goback) { + if (rQi < goback) { + throw("rQwait cannot backup " + goback + " bytes"); + } + rQi -= goback; + } + //Util.Debug(" waiting for " + (num-rQlen) + + // " " + msg + " byte(s)"); + return true; // true means need more data + } + return false; +} + +// +// Private utility routines +// + +function encode_message() { + if (mode === 'binary') { + // Put in a binary arraybuffer + return (new Uint8Array(sQ)).buffer; + } else { + // base64 encode + return Base64.encode(sQ); + } +} + +function decode_message(data) { + //Util.Debug(">> decode_message: " + data); + if (mode === 'binary') { + // push arraybuffer values onto the end + rQ.push.apply(rQ, (new Uint8Array(data))); + } else { + // base64 decode and concat to the end + rQ = rQ.concat(Base64.decode(data, 0)); + } + //Util.Debug(">> decode_message, rQ: " + rQ); +} + + +// +// Public Send functions +// + +function flush() { + if (websocket.bufferedAmount !== 0) { + Util.Debug("bufferedAmount: " + websocket.bufferedAmount); + } + if (websocket.bufferedAmount < api.maxBufferedAmount) { + //Util.Debug("arr: " + arr); + //Util.Debug("sQ: " + sQ); + if (sQ.length > 0) { + websocket.send(encode_message(sQ)); + sQ = []; + } + return true; + } else { + Util.Info("Delaying send, bufferedAmount: " + + websocket.bufferedAmount); + return false; + } +} + +// overridable for testing +function send(arr) { + //Util.Debug(">> send_array: " + arr); + sQ = sQ.concat(arr); + return flush(); +} + +function send_string(str) { + //Util.Debug(">> send_string: " + str); + api.send(str.split('').map( + function (chr) { return chr.charCodeAt(0); } ) ); +} + +// +// Other public functions + +function recv_message(e) { + //Util.Debug(">> recv_message: " + e.data.length); + + try { + decode_message(e.data); + if (rQlen() > 0) { + eventHandlers.message(); + // Compact the receive queue + if (rQ.length > rQmax) { + //Util.Debug("Compacting receive queue"); + rQ = rQ.slice(rQi); + rQi = 0; + } + } else { + Util.Debug("Ignoring empty message"); + } + } catch (exc) { + if (typeof exc.stack !== 'undefined') { + Util.Warn("recv_message, caught exception: " + exc.stack); + } else if (typeof exc.description !== 'undefined') { + Util.Warn("recv_message, caught exception: " + exc.description); + } else { + Util.Warn("recv_message, caught exception:" + exc); + } + if (typeof exc.name !== 'undefined') { + eventHandlers.error(exc.name + ": " + exc.message); + } else { + eventHandlers.error(exc); + } + } + //Util.Debug("<< recv_message"); +} + + +// Set event handlers +function on(evt, handler) { + eventHandlers[evt] = handler; +} + +function init(protocols) { + rQ = []; + rQi = 0; + sQ = []; + websocket = null; + + var bt = false, + wsbt = false, + try_binary = false; + + // Check for full typed array support + if (('Uint8Array' in window) && + ('set' in Uint8Array.prototype)) { + bt = true; + } + + // Check for full binary type support in WebSockets + // TODO: this sucks, the property should exist on the prototype + // but it does not. + try { + if (bt && ('binaryType' in (new WebSocket("ws://localhost:17523")))) { + Util.Info("Detected binaryType support in WebSockets"); + wsbt = true; + } + } catch (exc) { + // Just ignore failed test localhost connections + } + + // Default protocols if not specified + if (typeof(protocols) === "undefined") { + if (wsbt) { + protocols = ['binary', 'base64']; + } else { + protocols = 'base64'; + } + } + + // If no binary support, make sure it was not requested + if (!wsbt) { + if (protocols === 'binary') { + throw("WebSocket binary sub-protocol requested but not supported"); + } + if (typeof(protocols) === "object") { + var new_protocols = []; + for (var i = 0; i < protocols.length; i++) { + if (protocols[i] === 'binary') { + Util.Error("Skipping unsupported WebSocket binary sub-protocol"); + } else { + new_protocols.push(protocols[i]); + } + } + if (new_protocols.length > 0) { + protocols = new_protocols; + } else { + throw("Only WebSocket binary sub-protocol was requested and not supported."); + } + } + } + + return protocols; +} + +function open(uri, protocols) { + protocols = init(protocols); + + if (test_mode) { + websocket = {}; + } else { + websocket = new WebSocket(uri, protocols); + } + + websocket.onmessage = recv_message; + websocket.onopen = function() { + Util.Debug(">> WebSock.onopen"); + if (websocket.protocol) { + mode = websocket.protocol; + Util.Info("Server chose sub-protocol: " + websocket.protocol); + } else { + mode = 'base64'; + Util.Error("Server select no sub-protocol!: " + websocket.protocol); + } + if (mode === 'binary') { + websocket.binaryType = 'arraybuffer'; + } + eventHandlers.open(); + Util.Debug("<< WebSock.onopen"); + }; + websocket.onclose = function(e) { + Util.Debug(">> WebSock.onclose"); + eventHandlers.close(e); + Util.Debug("<< WebSock.onclose"); + }; + websocket.onerror = function(e) { + Util.Debug(">> WebSock.onerror: " + e); + eventHandlers.error(e); + Util.Debug("<< WebSock.onerror"); + }; +} + +function close() { + if (websocket) { + if ((websocket.readyState === WebSocket.OPEN) || + (websocket.readyState === WebSocket.CONNECTING)) { + Util.Info("Closing WebSocket connection"); + websocket.close(); + } + websocket.onmessage = function (e) { return; }; + } +} + +// Override internal functions for testing +// Takes a send function, returns reference to recv function +function testMode(override_send) { + test_mode = true; + api.send = override_send; + api.close = function () {}; + return recv_message; +} + +function constructor() { + // Configuration settings + api.maxBufferedAmount = 200; + + // Direct access to send and receive queues + api.get_sQ = get_sQ; + api.get_rQ = get_rQ; + api.get_rQi = get_rQi; + api.set_rQi = set_rQi; + + // Routines to read from the receive queue + api.rQlen = rQlen; + api.rQpeek8 = rQpeek8; + api.rQshift8 = rQshift8; + api.rQunshift8 = rQunshift8; + api.rQshift16 = rQshift16; + api.rQshift32 = rQshift32; + api.rQshiftStr = rQshiftStr; + api.rQshiftBytes = rQshiftBytes; + api.rQslice = rQslice; + api.rQwait = rQwait; + + api.flush = flush; + api.send = send; + api.send_string = send_string; + + api.on = on; + api.init = init; + api.open = open; + api.close = close; + api.testMode = testMode; + + return api; +} + +return constructor(); + +} diff --git a/third_party/websockify/include/webutil.js b/third_party/websockify/include/webutil.js new file mode 100644 index 00000000..2966cd79 --- /dev/null +++ b/third_party/websockify/include/webutil.js @@ -0,0 +1,148 @@ +/* + * from noVNC: HTML5 VNC client + * Copyright (C) 2010 Joel Martin + * Licensed under LGPL-3 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +"use strict"; +/*jslint bitwise: false, white: false */ +/*global Util, window, document */ + +// Globals defined here +var WebUtil = {}, $D; + +/* + * Simple DOM selector by ID + */ +if (!window.$D) { + window.$D = function (id) { + if (document.getElementById) { + return document.getElementById(id); + } else if (document.all) { + return document.all[id]; + } else if (document.layers) { + return document.layers[id]; + } + return undefined; + }; +} + + +/* + * ------------------------------------------------------ + * Namespaced in WebUtil + * ------------------------------------------------------ + */ + +// init log level reading the logging HTTP param +WebUtil.init_logging = function() { + Util._log_level = (document.location.href.match( + /logging=([A-Za-z0-9\._\-]*)/) || + ['', Util._log_level])[1]; + + Util.init_logging(); +}; +WebUtil.init_logging(); + + +WebUtil.dirObj = function (obj, depth, parent) { + var i, msg = "", val = ""; + if (! depth) { depth=2; } + if (! parent) { parent= ""; } + + // Print the properties of the passed-in object + for (i in obj) { + if ((depth > 1) && (typeof obj[i] === "object")) { + // Recurse attributes that are objects + msg += WebUtil.dirObj(obj[i], depth-1, parent + "." + i); + } else { + //val = new String(obj[i]).replace("\n", " "); + if (typeof(obj[i]) === "undefined") { + val = "undefined"; + } else { + val = obj[i].toString().replace("\n", " "); + } + if (val.length > 30) { + val = val.substr(0,30) + "..."; + } + msg += parent + "." + i + ": " + val + "\n"; + } + } + return msg; +}; + +// Read a query string variable +WebUtil.getQueryVar = function(name, defVal) { + var re = new RegExp('[?][^#]*' + name + '=([^&#]*)'); + if (typeof defVal === 'undefined') { defVal = null; } + return (document.location.href.match(re) || ['',defVal])[1]; +}; + + +/* + * Cookie handling. Dervied from: http://www.quirksmode.org/js/cookies.html + */ + +// No days means only for this browser session +WebUtil.createCookie = function(name,value,days) { + var date, expires; + if (days) { + date = new Date(); + date.setTime(date.getTime()+(days*24*60*60*1000)); + expires = "; expires="+date.toGMTString(); + } + else { + expires = ""; + } + document.cookie = name+"="+value+expires+"; path=/"; +}; + +WebUtil.readCookie = function(name, defaultValue) { + var i, c, nameEQ = name + "=", ca = document.cookie.split(';'); + for(i=0; i < ca.length; i += 1) { + c = ca[i]; + while (c.charAt(0) === ' ') { c = c.substring(1,c.length); } + if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length,c.length); } + } + return (typeof defaultValue !== 'undefined') ? defaultValue : null; +}; + +WebUtil.eraseCookie = function(name) { + WebUtil.createCookie(name,"",-1); +}; + +/* + * Alternate stylesheet selection + */ +WebUtil.getStylesheets = function() { var i, links, sheets = []; + links = document.getElementsByTagName("link"); + for (i = 0; i < links.length; i += 1) { + if (links[i].title && + links[i].rel.toUpperCase().indexOf("STYLESHEET") > -1) { + sheets.push(links[i]); + } + } + return sheets; +}; + +// No sheet means try and use value from cookie, null sheet used to +// clear all alternates. +WebUtil.selectStylesheet = function(sheet) { + var i, link, sheets = WebUtil.getStylesheets(); + if (typeof sheet === 'undefined') { + sheet = 'default'; + } + for (i=0; i < sheets.length; i += 1) { + link = sheets[i]; + if (link.title === sheet) { + Util.Debug("Using stylesheet " + sheet); + link.disabled = false; + } else { + //Util.Debug("Skipping stylesheet " + link.title); + link.disabled = true; + } + } + return sheet; +}; diff --git a/third_party/websockify/include/wsirc.js b/third_party/websockify/include/wsirc.js new file mode 100644 index 00000000..bef8f8de --- /dev/null +++ b/third_party/websockify/include/wsirc.js @@ -0,0 +1,235 @@ +/* + * WebSockets IRC client + * Copyright (C) 2011 Joel Martin + * Licensed under LGPL-3 (see LICENSE.txt) + * + * Includes VT100.js from: + * http://code.google.com/p/sshconsole + * Which was modified from: + * http://fzort.org/bi/o.php#vt100_js + + * IRC Client protocol: + * http://www.faqs.org/rfcs/rfc2812.html + */ + + +function IRC(target, connect_callback, disconnect_callback) { + +var that = {}, // Public API interface + vt100, ws, sQ = [], + state = "unconnected", + irc_nick, irc_channel, + termType = "VT100"; + + +Array.prototype.pushStr = function (str) { + var n = str.length; + for (var i=0; i < n; i++) { + this.push(str.charCodeAt(i)); + } +} + +function do_send() { + if (sQ.length > 0) { + Util.Debug("Sending " + sQ); + ws.send(sQ); + sQ = []; + } +} + +function do_recv() { + console.log(">> do_recv"); + var rQ, rQi, i; + + while (ws.rQlen() > 1) { + rQ = ws.get_rQ(); + rQi = ws.get_rQi(); + for (i = rQi; i < rQ.length; i++) { + if (rQ[i] === 10) { + break; + } + } + if (i >= rQ.length) { + // No line break found + break; + } + recvMsg(ws.rQshiftStr((i-rQi) + 1)); + } + //console.log("<< do_recv"); +} + +// Handle an IRC message +function recvMsg(msg) { + Util.Debug(">> recvMsg('" + msg + "')"); + + var tokens = msg.split(' '), in_params = true, + prefix, command, params = [], trailing = []; + + Util.Info(" tokens: " + tokens); + + if (tokens[0].charAt(0) === ":") { + prefix = tokens.shift(); + } + + command = tokens.shift(); + + while (tokens.length > 0) { + if (tokens[0].charAt(0) === ":") { + in_params = false; + } + if (in_params) { + params.push(tokens.shift()); + } else { + trailing.push(tokens.shift()); + } + } + + Util.Info(" prefix: " + prefix); + Util.Info(" command: " + command); + Util.Info(" params: " + params); + Util.Info(" trailing: " + trailing); + + // Show raw received + vt100.write(msg); + + switch (command) { + case "004": + state = "registered"; + vt100.write("Joining channel #" + irc_channel); + sendCmd("JOIN #" + irc_channel); + break; + case "JOIN": + state = "joined"; + vt100.write("Joined channel #" + irc_channel); + break; + + } + + Util.Debug("<< recvMsg('" + msg + "')"); +} + +function sendCmd(msg) { + Util.Info("Sending: " + msg); + sQ.pushStr(msg + "\r\n"); + do_send(); +} + +that.sendMsg = function(msg) { + // TODO parse into message + sendCmd("PRIVMSG #" + irc_channel + " :" + msg); +} + + +that.connect = function(host, port, encrypt, nick, channel) { + var host = host, + port = port, + scheme = "ws://", uri; + + irc_nick = nick; + irc_channel = channel; + + Util.Debug(">> connect"); + if ((!host) || (!port)) { + alert("must set host and port"); + return false; + } + + if (ws) { + ws.close(); + } + + if (encrypt) { + scheme = "wss://"; + } + uri = scheme + host + ":" + port; + Util.Info("connecting to " + uri); + + ws.open(uri); + + Util.Debug("<< connect"); + + return true; +} + +that.disconnect = function() { + Util.Debug(">> disconnect"); + if (ws) { + ws.close(); + } + + disconnect_callback(); + Util.Debug("<< disconnect"); +} + + +function constructor() { + /* Initialize Websock object */ + ws = new Websock(); + + ws.on('message', do_recv); + ws.on('open', function(e) { + Util.Info(">> WebSockets.onopen"); + // Send registration commands + state = "connected"; + sendCmd("NICK " + irc_nick); + // TODO: how to determine this? + sendCmd("USER joelm 0 * :Joel Martin"); + connect_callback(); + Util.Info("<< WebSockets.onopen"); + }); + ws.on('close', function(e) { + Util.Info(">> WebSockets.onclose"); + that.disconnect(); + Util.Info("<< WebSockets.onclose"); + }); + ws.on('error', function(e) { + Util.Info(">> WebSockets.onerror"); + that.disconnect(); + Util.Info("<< WebSockets.onerror"); + }); + + /* Initialize the terminal emulator/renderer */ + + vt100 = new VT100(80, 24, target); + + // Show cursor + vt100.curs_set(true, false); + + /* + * Override VT100 I/O routines + */ + + // Set handler for sending characters + vt100.getch( + function send_chr(chr, vt) { + var i; + Util.Debug(">> send_chr: " + chr); + for (i = 0; i < chr.length; i++) { + sQ.push(chr.charCodeAt(i)); + } + do_send(); + vt100.getch(send_chr); + } + ); + + vt100.debug = function(message) { + Util.Debug(message + "\n"); + } + + vt100.warn = function(message) { + Util.Warn(message + "\n"); + } + + vt100.curs_set = function(vis, grab, eventist) + { + this.debug("curs_set:: vis: " + vis + ", grab: " + grab); + if (vis !== undefined) + this.cursor_vis_ = (vis > 0); + } + + return that; +} + +return constructor(); // Return the public API interface + +} // End of Telnet() diff --git a/third_party/websockify/include/wstelnet.js b/third_party/websockify/include/wstelnet.js new file mode 100644 index 00000000..fca45f3c --- /dev/null +++ b/third_party/websockify/include/wstelnet.js @@ -0,0 +1,335 @@ +/* + * WebSockets telnet client + * Copyright (C) 2011 Joel Martin + * Licensed under LGPL-3 (see LICENSE.txt) + * + * Includes VT100.js from: + * http://code.google.com/p/sshconsole + * Which was modified from: + * http://fzort.org/bi/o.php#vt100_js + * + * Telnet protocol: + * http://www.networksorcery.com/enp/protocol/telnet.htm + * http://www.networksorcery.com/enp/rfc/rfc1091.txt + * + * ANSI escape sequeneces: + * http://en.wikipedia.org/wiki/ANSI_escape_code + * http://ascii-table.com/ansi-escape-sequences-vt-100.php + * http://www.termsys.demon.co.uk/vtansi.htm + * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html + * + * ASCII codes: + * http://en.wikipedia.org/wiki/ASCII + * http://www.hobbyprojects.com/ascii-table/ascii-table.html + * + * Other web consoles: + * http://stackoverflow.com/questions/244750/ajax-console-window-with-ansi-vt100-support + */ + + + + +function Telnet(target, connect_callback, disconnect_callback) { + +var that = {}, // Public API interface + vt100, ws, sQ = []; + termType = "VT100"; + + +Array.prototype.pushStr = function (str) { + var n = str.length; + for (var i=0; i < n; i++) { + this.push(str.charCodeAt(i)); + } +} + +function do_send() { + if (sQ.length > 0) { + Util.Debug("Sending " + sQ); + ws.send(sQ); + sQ = []; + } +} + +function do_recv() { + //console.log(">> do_recv"); + var arr = ws.rQshiftBytes(ws.rQlen()), str = "", + chr, cmd, code, value; + + Util.Debug("Received array '" + arr + "'"); + while (arr.length > 0) { + chr = arr.shift(); + switch (chr) { + case 255: // IAC + cmd = chr; + code = arr.shift(); + value = arr.shift(); + switch (code) { + case 254: // DONT + Util.Debug("Got Cmd DONT '" + value + "', ignoring"); + break; + case 253: // DO + Util.Debug("Got Cmd DO '" + value + "'"); + if (value === 24) { + // Terminal type + Util.Info("Send WILL '" + value + "' (TERM-TYPE)"); + sQ.push(255, 251, value); + } else { + // Refuse other DO requests with a WONT + Util.Debug("Send WONT '" + value + "'"); + sQ.push(255, 252, value); + } + break; + case 252: // WONT + Util.Debug("Got Cmd WONT '" + value + "', ignoring"); + break; + case 251: // WILL + Util.Debug("Got Cmd WILL '" + value + "'"); + if (value === 1) { + // Server will echo, turn off local echo + vt100.noecho(); + // Affirm echo with DO + Util.Info("Send Cmd DO '" + value + "' (echo)"); + sQ.push(255, 253, value); + } else { + // Reject other WILL offers with a DONT + Util.Debug("Send Cmd DONT '" + value + "'"); + sQ.push(255, 254, value); + } + break; + case 250: // SB (subnegotiation) + if (value === 24) { + Util.Info("Got IAC SB TERM-TYPE SEND(1) IAC SE"); + // TERM-TYPE subnegotiation + if (arr[0] === 1 && + arr[1] === 255 && + arr[2] === 240) { + arr.shift(); arr.shift(); arr.shift(); + Util.Info("Send IAC SB TERM-TYPE IS(0) '" + + termType + "' IAC SE"); + sQ.push(255, 250, 24, 0); + sQ.pushStr(termType); + sQ.push(255, 240); + } else { + Util.Info("Invalid subnegotiation received" + arr); + } + } else { + Util.Info("Ignoring SB " + value); + } + break; + default: + Util.Info("Got Cmd " + cmd + " " + value + ", ignoring"); } + continue; + case 242: // Data Mark (Synch) + cmd = chr; + code = arr.shift(); + value = arr.shift(); + Util.Info("Ignoring Data Mark (Synch)"); + break; + default: // everything else + str += String.fromCharCode(chr); + } + } + + if (sQ) { + do_send(); + } + + if (str) { + vt100.write(str); + } + + //console.log("<< do_recv"); +} + + + +that.connect = function(host, port, encrypt) { + var host = host, + port = port, + scheme = "ws://", uri; + + Util.Debug(">> connect"); + if ((!host) || (!port)) { + console.log("must set host and port"); + return; + } + + if (ws) { + ws.close(); + } + + if (encrypt) { + scheme = "wss://"; + } + uri = scheme + host + ":" + port; + Util.Info("connecting to " + uri); + + ws.open(uri); + + Util.Debug("<< connect"); +} + +that.disconnect = function() { + Util.Debug(">> disconnect"); + if (ws) { + ws.close(); + } + vt100.curs_set(true, false); + + disconnect_callback(); + Util.Debug("<< disconnect"); +} + + +function constructor() { + /* Initialize Websock object */ + ws = new Websock(); + + ws.on('message', do_recv); + ws.on('open', function(e) { + Util.Info(">> WebSockets.onopen"); + vt100.curs_set(true, true); + connect_callback(); + Util.Info("<< WebSockets.onopen"); + }); + ws.on('close', function(e) { + Util.Info(">> WebSockets.onclose"); + that.disconnect(); + Util.Info("<< WebSockets.onclose"); + }); + ws.on('error', function(e) { + Util.Info(">> WebSockets.onerror"); + that.disconnect(); + Util.Info("<< WebSockets.onerror"); + }); + + /* Initialize the terminal emulator/renderer */ + + vt100 = new VT100(80, 24, target); + + + /* + * Override VT100 I/O routines + */ + + // Set handler for sending characters + vt100.getch( + function send_chr(chr, vt) { + var i; + Util.Debug(">> send_chr: " + chr); + for (i = 0; i < chr.length; i++) { + sQ.push(chr.charCodeAt(i)); + } + do_send(); + vt100.getch(send_chr); + } + ); + + vt100.debug = function(message) { + Util.Debug(message + "\n"); + } + + vt100.warn = function(message) { + Util.Warn(message + "\n"); + } + + vt100.curs_set = function(vis, grab, eventist) + { + this.debug("curs_set:: vis: " + vis + ", grab: " + grab); + if (vis !== undefined) + this.cursor_vis_ = (vis > 0); + if (eventist === undefined) + eventist = window; + if (grab === true || grab === false) { + if (grab === this.grab_events_) + return; + if (grab) { + this.grab_events_ = true; + VT100.the_vt_ = this; + Util.addEvent(eventist, 'keydown', vt100.key_down); + Util.addEvent(eventist, 'keyup', vt100.key_up); + } else { + Util.removeEvent(eventist, 'keydown', vt100.key_down); + Util.removeEvent(eventist, 'keyup', vt100.key_up); + this.grab_events_ = false; + VT100.the_vt_ = undefined; + } + } + } + + vt100.key_down = function(e) { + var vt = VT100.the_vt_, keysym, ch, str = ""; + + if (vt === undefined) + return true; + + keysym = getKeysym(e); + + if (keysym < 128) { + if (e.ctrlKey) { + if (keysym == 64) { + // control 0 + ch = 0; + } else if ((keysym >= 97) && (keysym <= 122)) { + // control codes 1-26 + ch = keysym - 96; + } else if ((keysym >= 91) && (keysym <= 95)) { + // control codes 27-31 + ch = keysym - 64; + } else { + Util.Info("Debug unknown control keysym: " + keysym); + } + } else { + ch = keysym; + } + str = String.fromCharCode(ch); + } else { + switch (keysym) { + case 65505: // Shift, do not send directly + break; + case 65507: // Ctrl, do not send directly + break; + case 65293: // Carriage return, line feed + str = '\n'; break; + case 65288: // Backspace + str = '\b'; break; + case 65307: // Escape + str = '\x1b'; break; + case 65361: // Left arrow + str = '\x1b[D'; break; + case 65362: // Up arrow + str = '\x1b[A'; break; + case 65363: // Right arrow + str = '\x1b[C'; break; + case 65364: // Down arrow + str = '\x1b[B'; break; + default: + Util.Info("Unrecoginized keysym " + keysym); + } + } + + if (str) { + vt.key_buf_.push(str); + setTimeout(VT100.go_getch_, 0); + } + + Util.stopEvent(e); + return false; + } + + vt100.key_up = function(e) { + var vt = VT100.the_vt_; + if (vt === undefined) + return true; + Util.stopEvent(e); + return false; + } + + + return that; +} + +return constructor(); // Return the public API interface + +} // End of Telnet() diff --git a/third_party/websockify/other/Makefile b/third_party/websockify/other/Makefile new file mode 100644 index 00000000..f8d28645 --- /dev/null +++ b/third_party/websockify/other/Makefile @@ -0,0 +1,14 @@ +TARGETS=websockify +CFLAGS += -fPIC + +all: $(TARGETS) + +websockify: websockify.o websocket.o + $(CC) $(LDFLAGS) $^ -lssl -lcrypto -lresolv -o $@ + +websocket.o: websocket.c websocket.h +websockify.o: websockify.c websocket.h + +clean: + rm -f websockify *.o + diff --git a/third_party/websockify/other/README.md b/third_party/websockify/other/README.md new file mode 100644 index 00000000..1851e2aa --- /dev/null +++ b/third_party/websockify/other/README.md @@ -0,0 +1,51 @@ +This directory contain alternate implementations of +WebSockets-to-TCP-Socket proxies (for noVNC). + +## websockify.c (C) + +### Description + +This is a C version of the original websockify. It is more limited in +functionality than the original. + + +## websockify.js + +### Description + +This is a Node.JS (server-side event driven Javascript) implementation +of websockify. + + +## kumina.c (C) + +### Description + +The upstream source of the kumina proxy is [here](https://github.com/kumina/wsproxy). + +[This article](http://blog.kumina.nl/2011/06/proxying-and-multiplexing-novnc-using-wsproxy/) +describes the kumina proxy. + +kumina is an application that is run from inetd, which allows noVNC +to connect to an unmodified VNC server. Furthermore, it makes use of +the recently added support in noVNC for file names. The file name is +used to denote the port number. Say, you connect to: + + ws://host:41337/25900 + +The kumina proxy opens a connection to: + + vnc://host:25900/ + +The address to which kumina connects, is the same as the address to +which the client connected (using getsockname()). + +### Configuration + +kumina can be enabled by adding the following line to inetd.conf: + + 41337 stream tcp nowait nobody /usr/sbin/kumina kumina 25900 25909 + +The two parameters of kumina denote the minimum and the maximum allowed +port numbers. This allows a single kumina instance to multiplex +connections to multiple VNC servers. diff --git a/third_party/websockify/other/launch.sh b/third_party/websockify/other/launch.sh new file mode 100755 index 00000000..613250c6 --- /dev/null +++ b/third_party/websockify/other/launch.sh @@ -0,0 +1,108 @@ +#!/usr/bin/env bash + +usage() { + if [ "$*" ]; then + echo "$*" + echo + fi + echo "Usage: ${NAME} [--listen PORT] [--vnc VNC_HOST:PORT] [--cert CERT]" + echo + echo "Starts the WebSockets proxy and a mini-webserver and " + echo "provides a cut-and-paste URL to go to." + echo + echo " --listen PORT Port for proxy/webserver to listen on" + echo " Default: 6080" + echo " --vnc VNC_HOST:PORT VNC server host:port proxy target" + echo " Default: localhost:5900" + echo " --cert CERT Path to combined cert/key file" + echo " Default: self.pem" + exit 2 +} + +NAME="$(basename $0)" +HERE="$(cd "$(dirname "$0")" && pwd)" +PORT="6080" +VNC_DEST="localhost:5900" +CERT="" +proxy_pid="" + +die() { + echo "$*" + exit 1 +} + +cleanup() { + trap - TERM QUIT INT EXIT + trap "true" CHLD # Ignore cleanup messages + echo + if [ -n "${proxy_pid}" ]; then + echo "Terminating WebSockets proxy (${proxy_pid})" + kill ${proxy_pid} + fi +} + +# Process Arguments + +# Arguments that only apply to chrooter itself +while [ "$*" ]; do + param=$1; shift; OPTARG=$1 + case $param in + --listen) PORT="${OPTARG}"; shift ;; + --vnc) VNC_DEST="${OPTARG}"; shift ;; + --cert) CERT="${OPTARG}"; shift ;; + -h|--help) usage ;; + -*) usage "Unknown chrooter option: ${param}" ;; + *) break ;; + esac +done + +# Sanity checks +which netstat >/dev/null 2>&1 \ + || die "Must have netstat installed" + +netstat -ltn | grep -qs "${PORT}.*LISTEN" \ + && die "Port ${PORT} in use. Try --listen PORT" + +trap "cleanup" TERM QUIT INT EXIT + +# Find vnc.html +if [ -e "$(pwd)/vnc.html" ]; then + WEB=$(pwd) +elif [ -e "${HERE}/../vnc.html" ]; then + WEB=${HERE}/../ +elif [ -e "${HERE}/vnc.html" ]; then + WEB=${HERE} +else + die "Could not find vnc.html" +fi + +# Find self.pem +if [ -n "${CERT}" ]; then + if [ ! -e "${CERT}" ]; then + die "Could not find ${CERT}" + fi +elif [ -e "$(pwd)/self.pem" ]; then + CERT="$(pwd)/self.pem" +elif [ -e "${HERE}/../self.pem" ]; then + CERT="${HERE}/../self.pem" +elif [ -e "${HERE}/self.pem" ]; then + CERT="${HERE}/self.pem" +else + echo "Warning: could not find self.pem" +fi + +echo "Starting webserver and WebSockets proxy on port ${PORT}" +${HERE}/wsproxy.py --web ${WEB} ${CERT:+--cert ${CERT}} ${PORT} ${VNC_DEST} & +proxy_pid="$!" +sleep 1 +if ! ps -p ${proxy_pid} >/dev/null; then + proxy_pid= + echo "Failed to start WebSockets proxy" + exit 1 +fi + +echo -e "\n\nNavigate to to this URL:\n" +echo -e " http://$(hostname):${PORT}/vnc.html?host=$(hostname)&port=${PORT}\n" +echo -e "Press Ctrl-C to exit\n\n" + +wait ${proxy_pid} diff --git a/third_party/websockify/other/project.clj b/third_party/websockify/other/project.clj new file mode 100644 index 00000000..fb2c0ba5 --- /dev/null +++ b/third_party/websockify/other/project.clj @@ -0,0 +1,13 @@ +(defproject websockify "1.0.0-SNAPSHOT" + :description "Clojure implementation of Websockify" + :url "https://github.com/kanaka/websockify" + :dependencies [[org.clojure/clojure "1.2.1"] + [org.clojure/tools.cli "0.2.1"] + [ring/ring-jetty-adapter "1.0.0-beta2"] + [org.eclipse.jetty/jetty-websocket "7.5.4.v20111024"] + [org.eclipse.jetty/jetty-server "7.5.4.v20111024"] + [org.eclipse.jetty/jetty-servlet "7.5.4.v20111024"] + [org.jboss.netty/netty "3.2.5.Final"]] + ;:dev-dependencies [[swank-clojure "1.3.0-SNAPSHOT"]] + :main websockify + ) diff --git a/third_party/websockify/other/websocket.c b/third_party/websockify/other/websocket.c new file mode 100644 index 00000000..c365409c --- /dev/null +++ b/third_party/websockify/other/websocket.c @@ -0,0 +1,802 @@ +/* + * WebSocket lib with support for "wss://" encryption. + * Copyright 2010 Joel Martin + * Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) + * + * You can make a cert/key with openssl using: + * openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem + * as taken from http://docs.python.org/dev/library/ssl.html#certificates + */ +#include <unistd.h> +#include <stdio.h> +#include <stdlib.h> +#include <errno.h> +#include <strings.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <netdb.h> +#include <signal.h> // daemonizing +#include <fcntl.h> // daemonizing +#include <openssl/err.h> +#include <openssl/ssl.h> +#include <resolv.h> /* base64 encode/decode */ +#include <openssl/md5.h> /* md5 hash */ +#include <openssl/sha.h> /* sha1 hash */ +#include "websocket.h" + +/* + * Global state + * + * Warning: not thread safe + */ +int ssl_initialized = 0; +int pipe_error = 0; +settings_t settings; + + +void traffic(char * token) { + if ((settings.verbose) && (! settings.daemon)) { + fprintf(stdout, "%s", token); + fflush(stdout); + } +} + +void error(char *msg) +{ + perror(msg); +} + +void fatal(char *msg) +{ + perror(msg); + exit(1); +} + +/* resolve host with also IP address parsing */ +int resolve_host(struct in_addr *sin_addr, const char *hostname) +{ + if (!inet_aton(hostname, sin_addr)) { + struct addrinfo *ai, *cur; + struct addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + if (getaddrinfo(hostname, NULL, &hints, &ai)) + return -1; + for (cur = ai; cur; cur = cur->ai_next) { + if (cur->ai_family == AF_INET) { + *sin_addr = ((struct sockaddr_in *)cur->ai_addr)->sin_addr; + freeaddrinfo(ai); + return 0; + } + } + freeaddrinfo(ai); + return -1; + } + return 0; +} + + +/* + * SSL Wrapper Code + */ + +ssize_t ws_recv(ws_ctx_t *ctx, void *buf, size_t len) { + if (ctx->ssl) { + //handler_msg("SSL recv\n"); + return SSL_read(ctx->ssl, buf, len); + } else { + return recv(ctx->sockfd, buf, len, 0); + } +} + +ssize_t ws_send(ws_ctx_t *ctx, const void *buf, size_t len) { + if (ctx->ssl) { + //handler_msg("SSL send\n"); + return SSL_write(ctx->ssl, buf, len); + } else { + return send(ctx->sockfd, buf, len, 0); + } +} + +ws_ctx_t *alloc_ws_ctx() { + ws_ctx_t *ctx; + if (! (ctx = malloc(sizeof(ws_ctx_t))) ) + { fatal("malloc()"); } + + if (! (ctx->cin_buf = malloc(BUFSIZE)) ) + { fatal("malloc of cin_buf"); } + if (! (ctx->cout_buf = malloc(BUFSIZE)) ) + { fatal("malloc of cout_buf"); } + if (! (ctx->tin_buf = malloc(BUFSIZE)) ) + { fatal("malloc of tin_buf"); } + if (! (ctx->tout_buf = malloc(BUFSIZE)) ) + { fatal("malloc of tout_buf"); } + + ctx->headers = malloc(sizeof(headers_t)); + ctx->ssl = NULL; + ctx->ssl_ctx = NULL; + return ctx; +} + +int free_ws_ctx(ws_ctx_t *ctx) { + free(ctx->cin_buf); + free(ctx->cout_buf); + free(ctx->tin_buf); + free(ctx->tout_buf); + free(ctx); +} + +ws_ctx_t *ws_socket(ws_ctx_t *ctx, int socket) { + ctx->sockfd = socket; +} + +ws_ctx_t *ws_socket_ssl(ws_ctx_t *ctx, int socket, char * certfile, char * keyfile) { + int ret; + char msg[1024]; + char * use_keyfile; + ws_socket(ctx, socket); + + if (keyfile && (keyfile[0] != '\0')) { + // Separate key file + use_keyfile = keyfile; + } else { + // Combined key and cert file + use_keyfile = certfile; + } + + // Initialize the library + if (! ssl_initialized) { + SSL_library_init(); + OpenSSL_add_all_algorithms(); + SSL_load_error_strings(); + ssl_initialized = 1; + + } + + ctx->ssl_ctx = SSL_CTX_new(TLSv1_server_method()); + if (ctx->ssl_ctx == NULL) { + ERR_print_errors_fp(stderr); + fatal("Failed to configure SSL context"); + } + + if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, use_keyfile, + SSL_FILETYPE_PEM) <= 0) { + sprintf(msg, "Unable to load private key file %s\n", use_keyfile); + fatal(msg); + } + + if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, certfile, + SSL_FILETYPE_PEM) <= 0) { + sprintf(msg, "Unable to load certificate file %s\n", certfile); + fatal(msg); + } + +// if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, "DEFAULT") != 1) { +// sprintf(msg, "Unable to set cipher\n"); +// fatal(msg); +// } + + // Associate socket and ssl object + ctx->ssl = SSL_new(ctx->ssl_ctx); + SSL_set_fd(ctx->ssl, socket); + + ret = SSL_accept(ctx->ssl); + if (ret < 0) { + ERR_print_errors_fp(stderr); + return NULL; + } + + return ctx; +} + +int ws_socket_free(ws_ctx_t *ctx) { + if (ctx->ssl) { + SSL_free(ctx->ssl); + ctx->ssl = NULL; + } + if (ctx->ssl_ctx) { + SSL_CTX_free(ctx->ssl_ctx); + ctx->ssl_ctx = NULL; + } + if (ctx->sockfd) { + shutdown(ctx->sockfd, SHUT_RDWR); + close(ctx->sockfd); + ctx->sockfd = 0; + } +} + +/* ------------------------------------------------------- */ + + +int encode_hixie(u_char const *src, size_t srclength, + char *target, size_t targsize) { + int sz = 0, len = 0; + target[sz++] = '\x00'; + len = b64_ntop(src, srclength, target+sz, targsize-sz); + if (len < 0) { + return len; + } + sz += len; + target[sz++] = '\xff'; + return sz; +} + +int decode_hixie(char *src, size_t srclength, + u_char *target, size_t targsize, + unsigned int *opcode, unsigned int *left) { + char *start, *end, cntstr[4]; + int i, len, framecount = 0, retlen = 0; + unsigned char chr; + if ((src[0] != '\x00') || (src[srclength-1] != '\xff')) { + handler_emsg("WebSocket framing error\n"); + return -1; + } + *left = srclength; + + if (srclength == 2 && + (src[0] == '\xff') && + (src[1] == '\x00')) { + // client sent orderly close frame + *opcode = 0x8; // Close frame + return 0; + } + *opcode = 0x1; // Text frame + + start = src+1; // Skip '\x00' start + do { + /* We may have more than one frame */ + end = (char *)memchr(start, '\xff', srclength); + *end = '\x00'; + len = b64_pton(start, target+retlen, targsize-retlen); + if (len < 0) { + return len; + } + retlen += len; + start = end + 2; // Skip '\xff' end and '\x00' start + framecount++; + } while (end < (src+srclength-1)); + if (framecount > 1) { + snprintf(cntstr, 3, "%d", framecount); + traffic(cntstr); + } + *left = 0; + return retlen; +} + +int encode_hybi(u_char const *src, size_t srclength, + char *target, size_t targsize, unsigned int opcode) +{ + unsigned long long b64_sz, len_offset = 1, payload_offset = 2, len = 0; + + if ((int)srclength <= 0) + { + return 0; + } + + b64_sz = ((srclength - 1) / 3) * 4 + 4; + + target[0] = (char)(opcode & 0x0F | 0x80); + + if (b64_sz <= 125) { + target[1] = (char) b64_sz; + payload_offset = 2; + } else if ((b64_sz > 125) && (b64_sz < 65536)) { + target[1] = (char) 126; + *(u_short*)&(target[2]) = htons(b64_sz); + payload_offset = 4; + } else { + handler_emsg("Sending frames larger than 65535 bytes not supported\n"); + return -1; + //target[1] = (char) 127; + //*(u_long*)&(target[2]) = htonl(b64_sz); + //payload_offset = 10; + } + + len = b64_ntop(src, srclength, target+payload_offset, targsize-payload_offset); + + if (len < 0) { + return len; + } + + return len + payload_offset; +} + +int decode_hybi(unsigned char *src, size_t srclength, + u_char *target, size_t targsize, + unsigned int *opcode, unsigned int *left) +{ + unsigned char *frame, *mask, *payload, save_char, cntstr[4];; + int masked = 0; + int i = 0, len, framecount = 0; + size_t remaining; + unsigned int target_offset = 0, hdr_length = 0, payload_length = 0; + + *left = srclength; + frame = src; + + //printf("Deocde new frame\n"); + while (1) { + // Need at least two bytes of the header + // Find beginning of next frame. First time hdr_length, masked and + // payload_length are zero + frame += hdr_length + 4*masked + payload_length; + //printf("frame[0..3]: 0x%x 0x%x 0x%x 0x%x (tot: %d)\n", + // (unsigned char) frame[0], + // (unsigned char) frame[1], + // (unsigned char) frame[2], + // (unsigned char) frame[3], srclength); + + if (frame > src + srclength) { + //printf("Truncated frame from client, need %d more bytes\n", frame - (src + srclength) ); + break; + } + remaining = (src + srclength) - frame; + if (remaining < 2) { + //printf("Truncated frame header from client\n"); + break; + } + framecount ++; + + *opcode = frame[0] & 0x0f; + masked = (frame[1] & 0x80) >> 7; + + if (*opcode == 0x8) { + // client sent orderly close frame + break; + } + + payload_length = frame[1] & 0x7f; + if (payload_length < 126) { + hdr_length = 2; + //frame += 2 * sizeof(char); + } else if (payload_length == 126) { + payload_length = (frame[2] << 8) + frame[3]; + hdr_length = 4; + } else { + handler_emsg("Receiving frames larger than 65535 bytes not supported\n"); + return -1; + } + if ((hdr_length + 4*masked + payload_length) > remaining) { + continue; + } + //printf(" payload_length: %u, raw remaining: %u\n", payload_length, remaining); + payload = frame + hdr_length + 4*masked; + + if (*opcode != 1 && *opcode != 2) { + handler_msg("Ignoring non-data frame, opcode 0x%x\n", *opcode); + continue; + } + + if (payload_length == 0) { + handler_msg("Ignoring empty frame\n"); + continue; + } + + if ((payload_length > 0) && (!masked)) { + handler_emsg("Received unmasked payload from client\n"); + return -1; + } + + // Terminate with a null for base64 decode + save_char = payload[payload_length]; + payload[payload_length] = '\0'; + + // unmask the data + mask = payload - 4; + for (i = 0; i < payload_length; i++) { + payload[i] ^= mask[i%4]; + } + + // base64 decode the data + len = b64_pton((const char*)payload, target+target_offset, targsize); + + // Restore the first character of the next frame + payload[payload_length] = save_char; + if (len < 0) { + handler_emsg("Base64 decode error code %d", len); + return len; + } + target_offset += len; + + //printf(" len %d, raw %s\n", len, frame); + } + + if (framecount > 1) { + snprintf(cntstr, 3, "%d", framecount); + traffic(cntstr); + } + + *left = remaining; + return target_offset; +} + + + +int parse_handshake(ws_ctx_t *ws_ctx, char *handshake) { + char *start, *end; + headers_t *headers = ws_ctx->headers; + + headers->key1[0] = '\0'; + headers->key2[0] = '\0'; + headers->key3[0] = '\0'; + + if ((strlen(handshake) < 92) || (bcmp(handshake, "GET ", 4) != 0)) { + return 0; + } + start = handshake+4; + end = strstr(start, " HTTP/1.1"); + if (!end) { return 0; } + strncpy(headers->path, start, end-start); + headers->path[end-start] = '\0'; + + start = strstr(handshake, "\r\nHost: "); + if (!start) { return 0; } + start += 8; + end = strstr(start, "\r\n"); + strncpy(headers->host, start, end-start); + headers->host[end-start] = '\0'; + + headers->origin[0] = '\0'; + start = strstr(handshake, "\r\nOrigin: "); + if (start) { + start += 10; + } else { + start = strstr(handshake, "\r\nSec-WebSocket-Origin: "); + if (!start) { return 0; } + start += 24; + } + end = strstr(start, "\r\n"); + strncpy(headers->origin, start, end-start); + headers->origin[end-start] = '\0'; + + start = strstr(handshake, "\r\nSec-WebSocket-Version: "); + if (start) { + // HyBi/RFC 6455 + start += 25; + end = strstr(start, "\r\n"); + strncpy(headers->version, start, end-start); + headers->version[end-start] = '\0'; + ws_ctx->hixie = 0; + ws_ctx->hybi = strtol(headers->version, NULL, 10); + + start = strstr(handshake, "\r\nSec-WebSocket-Key: "); + if (!start) { return 0; } + start += 21; + end = strstr(start, "\r\n"); + strncpy(headers->key1, start, end-start); + headers->key1[end-start] = '\0'; + + start = strstr(handshake, "\r\nConnection: "); + if (!start) { return 0; } + start += 14; + end = strstr(start, "\r\n"); + strncpy(headers->connection, start, end-start); + headers->connection[end-start] = '\0'; + + start = strstr(handshake, "\r\nSec-WebSocket-Protocol: "); + if (!start) { return 0; } + start += 26; + end = strstr(start, "\r\n"); + strncpy(headers->protocols, start, end-start); + headers->protocols[end-start] = '\0'; + } else { + // Hixie 75 or 76 + ws_ctx->hybi = 0; + + start = strstr(handshake, "\r\n\r\n"); + if (!start) { return 0; } + start += 4; + if (strlen(start) == 8) { + ws_ctx->hixie = 76; + strncpy(headers->key3, start, 8); + headers->key3[8] = '\0'; + + start = strstr(handshake, "\r\nSec-WebSocket-Key1: "); + if (!start) { return 0; } + start += 22; + end = strstr(start, "\r\n"); + strncpy(headers->key1, start, end-start); + headers->key1[end-start] = '\0'; + + start = strstr(handshake, "\r\nSec-WebSocket-Key2: "); + if (!start) { return 0; } + start += 22; + end = strstr(start, "\r\n"); + strncpy(headers->key2, start, end-start); + headers->key2[end-start] = '\0'; + } else { + ws_ctx->hixie = 75; + } + + } + + return 1; +} + +int parse_hixie76_key(char * key) { + unsigned long i, spaces = 0, num = 0; + for (i=0; i < strlen(key); i++) { + if (key[i] == ' ') { + spaces += 1; + } + if ((key[i] >= 48) && (key[i] <= 57)) { + num = num * 10 + (key[i] - 48); + } + } + return num / spaces; +} + +int gen_md5(headers_t *headers, char *target) { + unsigned long key1 = parse_hixie76_key(headers->key1); + unsigned long key2 = parse_hixie76_key(headers->key2); + char *key3 = headers->key3; + + MD5_CTX c; + char in[HIXIE_MD5_DIGEST_LENGTH] = { + key1 >> 24, key1 >> 16, key1 >> 8, key1, + key2 >> 24, key2 >> 16, key2 >> 8, key2, + key3[0], key3[1], key3[2], key3[3], + key3[4], key3[5], key3[6], key3[7] + }; + + MD5_Init(&c); + MD5_Update(&c, (void *)in, sizeof in); + MD5_Final((void *)target, &c); + + target[HIXIE_MD5_DIGEST_LENGTH] = '\0'; + + return 1; +} + +static void gen_sha1(headers_t *headers, char *target) { + SHA_CTX c; + unsigned char hash[SHA_DIGEST_LENGTH]; + int r; + + SHA1_Init(&c); + SHA1_Update(&c, headers->key1, strlen(headers->key1)); + SHA1_Update(&c, HYBI_GUID, 36); + SHA1_Final(hash, &c); + + r = b64_ntop(hash, sizeof hash, target, HYBI10_ACCEPTHDRLEN); + //assert(r == HYBI10_ACCEPTHDRLEN - 1); +} + + +ws_ctx_t *do_handshake(int sock) { + char handshake[4096], response[4096], sha1[29], trailer[17]; + char *scheme, *pre; + headers_t *headers; + int len, ret, i, offset; + ws_ctx_t * ws_ctx; + + // Peek, but don't read the data + len = recv(sock, handshake, 1024, MSG_PEEK); + handshake[len] = 0; + if (len == 0) { + handler_msg("ignoring empty handshake\n"); + return NULL; + } else if (bcmp(handshake, "<policy-file-request/>", 22) == 0) { + len = recv(sock, handshake, 1024, 0); + handshake[len] = 0; + handler_msg("sending flash policy response\n"); + send(sock, POLICY_RESPONSE, sizeof(POLICY_RESPONSE), 0); + return NULL; + } else if ((bcmp(handshake, "\x16", 1) == 0) || + (bcmp(handshake, "\x80", 1) == 0)) { + // SSL + if (!settings.cert) { + handler_msg("SSL connection but no cert specified\n"); + return NULL; + } else if (access(settings.cert, R_OK) != 0) { + handler_msg("SSL connection but '%s' not found\n", + settings.cert); + return NULL; + } + ws_ctx = alloc_ws_ctx(); + ws_socket_ssl(ws_ctx, sock, settings.cert, settings.key); + if (! ws_ctx) { return NULL; } + scheme = "wss"; + handler_msg("using SSL socket\n"); + } else if (settings.ssl_only) { + handler_msg("non-SSL connection disallowed\n"); + return NULL; + } else { + ws_ctx = alloc_ws_ctx(); + ws_socket(ws_ctx, sock); + if (! ws_ctx) { return NULL; } + scheme = "ws"; + handler_msg("using plain (not SSL) socket\n"); + } + offset = 0; + for (i = 0; i < 10; i++) { + len = ws_recv(ws_ctx, handshake+offset, 4096); + if (len == 0) { + handler_emsg("Client closed during handshake\n"); + return NULL; + } + offset += len; + handshake[offset] = 0; + if (strstr(handshake, "\r\n\r\n")) { + break; + } + usleep(10); + } + + //handler_msg("handshake: %s\n", handshake); + if (!parse_handshake(ws_ctx, handshake)) { + handler_emsg("Invalid WS request\n"); + return NULL; + } + + headers = ws_ctx->headers; + if (ws_ctx->hybi > 0) { + handler_msg("using protocol HyBi/IETF 6455 %d\n", ws_ctx->hybi); + gen_sha1(headers, sha1); + sprintf(response, SERVER_HANDSHAKE_HYBI, sha1, "base64"); + } else { + if (ws_ctx->hixie == 76) { + handler_msg("using protocol Hixie 76\n"); + gen_md5(headers, trailer); + pre = "Sec-"; + } else { + handler_msg("using protocol Hixie 75\n"); + trailer[0] = '\0'; + pre = ""; + } + sprintf(response, SERVER_HANDSHAKE_HIXIE, pre, headers->origin, pre, scheme, + headers->host, headers->path, pre, "base64", trailer); + } + + //handler_msg("response: %s\n", response); + ws_send(ws_ctx, response, strlen(response)); + + return ws_ctx; +} + +void signal_handler(sig) { + switch (sig) { + case SIGHUP: break; // ignore for now + case SIGPIPE: pipe_error = 1; break; // handle inline + case SIGTERM: exit(0); break; + } +} + +void daemonize(int keepfd) { + int pid, i; + + umask(0); + chdir("/"); + setgid(getgid()); + setuid(getuid()); + + /* Double fork to daemonize */ + pid = fork(); + if (pid<0) { fatal("fork error"); } + if (pid>0) { exit(0); } // parent exits + setsid(); // Obtain new process group + pid = fork(); + if (pid<0) { fatal("fork error"); } + if (pid>0) { exit(0); } // parent exits + + /* Signal handling */ + signal(SIGHUP, signal_handler); // catch HUP + signal(SIGTERM, signal_handler); // catch kill + + /* Close open files */ + for (i=getdtablesize(); i>=0; --i) { + if (i != keepfd) { + close(i); + } else if (settings.verbose) { + printf("keeping fd %d\n", keepfd); + } + } + i=open("/dev/null", O_RDWR); // Redirect stdin + dup(i); // Redirect stdout + dup(i); // Redirect stderr +} + + +void start_server() { + int lsock, csock, pid, clilen, sopt = 1, i; + struct sockaddr_in serv_addr, cli_addr; + ws_ctx_t *ws_ctx; + + + /* Initialize buffers */ + lsock = socket(AF_INET, SOCK_STREAM, 0); + if (lsock < 0) { error("ERROR creating listener socket"); } + bzero((char *) &serv_addr, sizeof(serv_addr)); + serv_addr.sin_family = AF_INET; + serv_addr.sin_port = htons(settings.listen_port); + + /* Resolve listen address */ + if (settings.listen_host && (settings.listen_host[0] != '\0')) { + if (resolve_host(&serv_addr.sin_addr, settings.listen_host) < -1) { + fatal("Could not resolve listen address"); + } + } else { + serv_addr.sin_addr.s_addr = INADDR_ANY; + } + + setsockopt(lsock, SOL_SOCKET, SO_REUSEADDR, (char *)&sopt, sizeof(sopt)); + if (bind(lsock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { + fatal("ERROR on binding listener socket"); + } + listen(lsock,100); + + signal(SIGPIPE, signal_handler); // catch pipe + + if (settings.daemon) { + daemonize(lsock); + } + + + // Reep zombies + signal(SIGCHLD, SIG_IGN); + + printf("Waiting for connections on %s:%d\n", + settings.listen_host, settings.listen_port); + + while (1) { + clilen = sizeof(cli_addr); + pipe_error = 0; + pid = 0; + csock = accept(lsock, + (struct sockaddr *) &cli_addr, + &clilen); + if (csock < 0) { + error("ERROR on accept"); + continue; + } + handler_msg("got client connection from %s\n", + inet_ntoa(cli_addr.sin_addr)); + + if (!settings.run_once) { + handler_msg("forking handler process\n"); + pid = fork(); + } + + if (pid == 0) { // handler process + ws_ctx = do_handshake(csock); + if (settings.run_once) { + if (ws_ctx == NULL) { + // Not a real WebSocket connection + continue; + } else { + // Successful connection, stop listening for new + // connections + close(lsock); + } + } + if (ws_ctx == NULL) { + handler_msg("No connection after handshake\n"); + break; // Child process exits + } + + settings.handler(ws_ctx); + if (pipe_error) { + handler_emsg("Closing due to SIGPIPE\n"); + } + break; // Child process exits + } else { // parent process + settings.handler_id += 1; + } + } + if (pid == 0) { + if (ws_ctx) { + ws_socket_free(ws_ctx); + free_ws_ctx(ws_ctx); + } else { + shutdown(csock, SHUT_RDWR); + close(csock); + } + handler_msg("handler exit\n"); + } else { + handler_msg("wsproxy exit\n"); + } + +} + diff --git a/third_party/websockify/other/websocket.h b/third_party/websockify/other/websocket.h new file mode 100644 index 00000000..7da52757 --- /dev/null +++ b/third_party/websockify/other/websocket.h @@ -0,0 +1,84 @@ +#include <openssl/ssl.h> + +#define BUFSIZE 65536 +#define DBUFSIZE (BUFSIZE * 3) / 4 - 20 + +#define SERVER_HANDSHAKE_HIXIE "HTTP/1.1 101 Web Socket Protocol Handshake\r\n\ +Upgrade: WebSocket\r\n\ +Connection: Upgrade\r\n\ +%sWebSocket-Origin: %s\r\n\ +%sWebSocket-Location: %s://%s%s\r\n\ +%sWebSocket-Protocol: %s\r\n\ +\r\n%s" + +#define SERVER_HANDSHAKE_HYBI "HTTP/1.1 101 Switching Protocols\r\n\ +Upgrade: websocket\r\n\ +Connection: Upgrade\r\n\ +Sec-WebSocket-Accept: %s\r\n\ +Sec-WebSocket-Protocol: %s\r\n\ +\r\n" + +#define HYBI_GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + +#define HYBI10_ACCEPTHDRLEN 29 + +#define HIXIE_MD5_DIGEST_LENGTH 16 + +#define POLICY_RESPONSE "<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\" /></cross-domain-policy>\n" + +typedef struct { + char path[1024+1]; + char host[1024+1]; + char origin[1024+1]; + char version[1024+1]; + char connection[1024+1]; + char protocols[1024+1]; + char key1[1024+1]; + char key2[1024+1]; + char key3[8+1]; +} headers_t; + +typedef struct { + int sockfd; + SSL_CTX *ssl_ctx; + SSL *ssl; + int hixie; + int hybi; + headers_t *headers; + char *cin_buf; + char *cout_buf; + char *tin_buf; + char *tout_buf; +} ws_ctx_t; + +typedef struct { + int verbose; + char listen_host[256]; + int listen_port; + void (*handler)(ws_ctx_t*); + int handler_id; + char *cert; + char *key; + int ssl_only; + int daemon; + int run_once; +} settings_t; + + +ssize_t ws_recv(ws_ctx_t *ctx, void *buf, size_t len); + +ssize_t ws_send(ws_ctx_t *ctx, const void *buf, size_t len); + +/* base64.c declarations */ +//int b64_ntop(u_char const *src, size_t srclength, char *target, size_t targsize); +//int b64_pton(char const *src, u_char *target, size_t targsize); + +#define gen_handler_msg(stream, ...) \ + if (! settings.daemon) { \ + fprintf(stream, " %d: ", settings.handler_id); \ + fprintf(stream, __VA_ARGS__); \ + } + +#define handler_msg(...) gen_handler_msg(stdout, __VA_ARGS__); +#define handler_emsg(...) gen_handler_msg(stderr, __VA_ARGS__); + diff --git a/third_party/websockify/other/websocket.rb b/third_party/websockify/other/websocket.rb new file mode 100644 index 00000000..6bf9e63a --- /dev/null +++ b/third_party/websockify/other/websocket.rb @@ -0,0 +1,456 @@ + +# Python WebSocket library with support for "wss://" encryption. +# Copyright 2011 Joel Martin +# Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) +# +# Supports following protocol versions: +# - http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75 +# - http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 +# - http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10 + +require 'gserver' +require 'stringio' +require 'digest/md5' +require 'digest/sha1' +require 'base64' + +class EClose < Exception +end + +class WebSocketServer < GServer + @@Buffer_size = 65536 + + # + # WebSocket constants + # + @@Server_handshake_hixie = "HTTP/1.1 101 Web Socket Protocol Handshake\r +Upgrade: WebSocket\r +Connection: Upgrade\r +%sWebSocket-Origin: %s\r +%sWebSocket-Location: %s://%s%s\r +" + + @@Server_handshake_hybi = "HTTP/1.1 101 Switching Protocols\r +Upgrade: websocket\r +Connection: Upgrade\r +Sec-WebSocket-Accept: %s\r +" + @@GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + + + def initialize(opts) + vmsg "in WebSocketServer.initialize" + port = opts['listen_port'] + host = opts['listen_host'] || GServer::DEFAULT_HOST + + super(port, host) + + @@client_id = 0 # Track client number total on class + + @verbose = opts['verbose'] + @opts = opts + end + + def serve(io) + @@client_id += 1 + + # Initialize per thread state + t = Thread.current + t[:my_client_id] = @@client_id + t[:send_parts] = [] + t[:recv_part] = nil + t[:base64] = nil + + puts "in serve, client: #{t[:client].inspect}" + + begin + t[:client] = do_handshake(io) + new_client(t[:client]) + rescue EClose => e + msg "Client closed: #{e.message}" + return + rescue Exception => e + msg "Uncaught exception: #{e.message}" + msg "Trace: #{e.backtrace}" + return + end + + msg "Client disconnected" + end + + # + # WebSocketServer logging/output functions + # + def traffic(token) + if @verbose then print token; STDOUT.flush; end + end + + def msg(msg) + puts "% 3d: %s" % [Thread.current[:my_client_id], msg] + end + + def vmsg(msg) + if @verbose then msg(msg) end + end + + # + # WebSocketServer general support routines + # + def gen_md5(h) + key1 = h['sec-websocket-key1'] + key2 = h['sec-websocket-key2'] + key3 = h['key3'] + spaces1 = key1.count(" ") + spaces2 = key2.count(" ") + num1 = key1.scan(/[0-9]/).join('').to_i / spaces1 + num2 = key2.scan(/[0-9]/).join('').to_i / spaces2 + + return Digest::MD5.digest([num1, num2, key3].pack('NNa8')) + end + + def unmask(buf, hlen, length) + pstart = hlen + 4 + mask = buf[hlen...hlen+4] + data = buf[pstart...pstart+length] + #data = data.bytes.zip(mask.bytes.cycle(length)).map { |d,m| d^m } + for i in (0...data.length) do + data[i] ^= mask[i%4] + end + return data + end + + def encode_hybi(buf, opcode, base64=false) + if base64 + buf = Base64.encode64(buf).gsub(/\n/, '') + end + + b1 = 0x80 | (opcode & 0x0f) # FIN + opcode + payload_len = buf.length + if payload_len <= 125 + header = [b1, payload_len].pack('CC') + elsif payload_len > 125 && payload_len < 65536 + header = [b1, 126, payload_len].pack('CCn') + elsif payload_len >= 65536 + header = [b1, 127, payload_len >> 32, + payload_len & 0xffffffff].pack('CCNN') + end + + return [header + buf, header.length, 0] + end + + def decode_hybi(buf, base64=false) + f = {'fin' => 0, + 'opcode' => 0, + 'hlen' => 2, + 'length' => 0, + 'payload' => nil, + 'left' => 0, + 'close_code' => nil, + 'close_reason' => nil} + + blen = buf.length + f['left'] = blen + + if blen < f['hlen'] then return f end # incomplete frame + + b1, b2 = buf.unpack('CC') + f['opcode'] = b1 & 0x0f + f['fin'] = (b1 & 0x80) >> 7 + has_mask = (b2 & 0x80) >> 7 + + f['length'] = b2 & 0x7f + + if f['length'] == 126 + f['hlen'] = 4 + if blen < f['hlen'] then return f end # incomplete frame + f['length'] = buf.unpack('xxn')[0] + elsif f['length'] == 127 + f['hlen'] = 10 + if blen < f['hlen'] then return f end # incomplete frame + top, bottom = buf.unpack('xxNN') + f['length'] = (top << 32) & bottom + end + + full_len = f['hlen'] + has_mask * 4 + f['length'] + + if blen < full_len then return f end # incomplete frame + + # number of bytes that are part of the next frame(s) + f['left'] = blen - full_len + + if has_mask > 0 + f['payload'] = unmask(buf, f['hlen'], f['length']) + else + f['payload'] = buf[f['hlen']...full_len] + end + + if base64 and [1, 2].include?(f['opcode']) + f['payload'] = Base64.decode64(f['payload']) + end + + # close frame + if f['opcode'] == 0x08 + if f['length'] >= 2 + f['close_code'] = f['payload'].unpack('n') + end + if f['length'] > 3 + f['close_reason'] = f['payload'][2...f['payload'].length] + end + end + + return f + end + + def encode_hixie(buf) + return ["\x00" + Base64.encode64(buf).gsub(/\n/, '') + "\xff", 1, 1] + end + + def decode_hixie(buf) + last = buf.index("\377") + return {'payload' => Base64.decode64(buf[1...last]), + 'hlen' => 1, + 'length' => last - 1, + 'left' => buf.length - (last + 1)} + end + + def send_frames(bufs) + t = Thread.current + if bufs.length > 0 + encbuf = "" + bufs.each do |buf| + if t[:version].start_with?("hybi") + if t[:base64] + encbuf, lenhead, lentail = encode_hybi( + buf, opcode=1, base64=true) + else + encbuf, lenhead, lentail = encode_hybi( + buf, opcode=2, base64=false) + end + else + encbuf, lenhead, lentail = encode_hixie(buf) + end + + t[:send_parts] << encbuf + end + + end + + while t[:send_parts].length > 0 + buf = t[:send_parts].shift + sent = t[:client].send(buf, 0) + + if sent == buf.length + traffic "<" + else + traffic "<." + t[:send_parts].unshift(buf[sent...buf.length]) + end + end + + return t[:send_parts].length + end + + # Receive and decode Websocket frames + # Returns: [bufs_list, closed_string] + def recv_frames() + t = Thread.current + closed = false + bufs = [] + + buf = t[:client].recv(@@Buffer_size) + + if buf.length == 0 + return bufs, "Client closed abrubtly" + end + + if t[:recv_part] + buf = t[:recv_part] + buf + t[:recv_part] = nil + end + + while buf.length > 0 + if t[:version].start_with?("hybi") + frame = decode_hybi(buf, base64=t[:base64]) + + if frame['payload'] == nil + traffic "}." + if frame['left'] > 0 + t[:recv_part] = buf[-frame['left']...buf.length] + end + break + else + if frame['opcode'] == 0x8 + closed = "Client closed, reason: %s - %s" % [ + frame['close_code'], frame['close_reason']] + break + end + end + else + if buf[0...2] == "\xff\x00": + closed = "Client sent orderly close frame" + break + elsif buf[0...2] == "\x00\xff": + buf = buf[2...buf.length] + continue # No-op frame + elsif buf.count("\xff") == 0 + # Partial frame + traffic "}." + t[:recv_part] = buf + break + end + + frame = decode_hixie(buf) + end + + #msg "Receive frame: #{frame.inspect}" + + traffic "}" + + bufs << frame['payload'] + + if frame['left'] > 0: + buf = buf[-frame['left']...buf.length] + else + buf = '' + end + end + + return bufs, closed + end + + + def send_close(code=nil, reason='') + t = Thread.current + if t[:version].start_with?("hybi") + msg = '' + if code + msg = [reason.length, code].pack("na8") + end + + buf, lenh, lent = encode_hybi(msg, opcode=0x08, base64=false) + t[:client].send(buf, 0) + elsif t[:version] == "hixie-76" + buf = "\xff\x00" + t[:client].send(buf, 0) + end + end + + def do_handshake(sock) + + t = Thread.current + stype = "" + + if !IO.select([sock], nil, nil, 3) + raise EClose, "ignoring socket not ready" + end + + handshake = sock.recv(1024, Socket::MSG_PEEK) + #msg "Handshake [#{handshake.inspect}]" + + if handshake == "" + raise(EClose, "ignoring empty handshake") + else + stype = "Plain non-SSL (ws://)" + scheme = "ws" + retsock = sock + sock.recv(1024) + end + + h = t[:headers] = {} + hlines = handshake.split("\r\n") + req_split = hlines.shift.match(/^(\w+) (\/[^\s]*) HTTP\/1\.1$/) + t[:path] = req_split[2].strip + hlines.each do |hline| + break if hline == "" + hsplit = hline.match(/^([^:]+):\s*(.+)$/) + h[hsplit[1].strip.downcase] = hsplit[2] + end + #puts "Headers: #{h.inspect}" + + unless h.has_key?('upgrade') && + h['upgrade'].downcase == 'websocket' + raise EClose, "Non-WebSocket connection" + end + + protocols = h.fetch("sec-websocket-protocol", h["websocket-protocol"]) + ver = h.fetch('sec-websocket-version', nil) + + if ver + # HyBi/IETF vesrion of the protocol + + # HyBi 07 reports version 7 + # HyBi 08 - 12 report version 8 + # HyBi 13 and up report version 13 + if ['7', '8', '13'].include?(ver) + t[:version] = "hybi-%02d" % [ver.to_i] + else + raise EClose, "Unsupported protocol version %s" % [ver] + end + + # choose binary if client supports it + if protocols.include?('binary') + t[:base64] = false + elsif protocols.include?('base64') + t[:base64] = true + else + raise EClose, "Client must support 'binary' or 'base64' sub-protocol" + end + + key = h['sec-websocket-key'] + + # Generate the hash value for the accpet header + accept = Base64.encode64( + Digest::SHA1.digest(key + @@GUID)).gsub(/\n/, '') + + response = @@Server_handshake_hybi % [accept] + + if t[:base64] + response += "Sec-WebSocket-Protocol: base64\r\n" + else + response += "Sec-WebSocket-Protocol: binary\r\n" + end + response += "\r\n" + + else + # Hixie vesrion of the protocol (75 or 76) + body = handshake.match(/\r\n\r\n(........)/) + if body + h['key3'] = body[1] + trailer = gen_md5(h) + pre = "Sec-" + t[:version] = "hixie-76" + else + trailer = "" + pre = "" + t[:version] = "hixie-75" + end + + # base64 required for Hixie since payload is only UTF-8 + t[:base64] = true + + response = @@Server_handshake_hixie % [pre, h['origin'], pre, + "ws", h['host'], t[:path]] + + if protocols && protocols.include?('base64') + response += "%sWebSocket-Protocol: base64\r\n" % [pre] + else + msg "Warning: client does not report 'base64' protocol support" + end + + response += "\r\n" + trailer + end + + msg "%s WebSocket connection" % [stype] + msg "Version %s, base64: '%s'" % [t[:version], t[:base64]] + if t[:path] then msg "Path: '%s'" % [t[:path]] end + + #puts "sending reponse #{response.inspect}" + retsock.send(response, 0) + + # Return the WebSocket socket which may be SSL wrapped + return retsock + end + +end + +# vim: sw=2 diff --git a/third_party/websockify/other/websockify.c b/third_party/websockify/other/websockify.c new file mode 100644 index 00000000..40321715 --- /dev/null +++ b/third_party/websockify/other/websockify.c @@ -0,0 +1,385 @@ +/* + * A WebSocket to TCP socket proxy with support for "wss://" encryption. + * Copyright 2010 Joel Martin + * Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) + * + * You can make a cert/key with openssl using: + * openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem + * as taken from http://docs.python.org/dev/library/ssl.html#certificates + */ +#include <stdio.h> +#include <errno.h> +#include <limits.h> +#include <getopt.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <netdb.h> +#include <sys/select.h> +#include <fcntl.h> +#include <sys/stat.h> +#include "websocket.h" + +char traffic_legend[] = "\n\ +Traffic Legend:\n\ + } - Client receive\n\ + }. - Client receive partial\n\ + { - Target receive\n\ +\n\ + > - Target send\n\ + >. - Target send partial\n\ + < - Client send\n\ + <. - Client send partial\n\ +"; + +char USAGE[] = "Usage: [options] " \ + "[source_addr:]source_port target_addr:target_port\n\n" \ + " --verbose|-v verbose messages and per frame traffic\n" \ + " --daemon|-D become a daemon (background process)\n" \ + " --cert CERT SSL certificate file\n" \ + " --key KEY SSL key file (if separate from cert)\n" \ + " --ssl-only disallow non-encrypted connections"; + +#define usage(fmt, args...) \ + fprintf(stderr, "%s\n\n", USAGE); \ + fprintf(stderr, fmt , ## args); \ + exit(1); + +char target_host[256]; +int target_port; + +extern pipe_error; +extern settings_t settings; + +void do_proxy(ws_ctx_t *ws_ctx, int target) { + fd_set rlist, wlist, elist; + struct timeval tv; + int i, maxfd, client = ws_ctx->sockfd; + unsigned int opcode, left, ret; + unsigned int tout_start, tout_end, cout_start, cout_end; + unsigned int tin_start, tin_end; + ssize_t len, bytes; + + tout_start = tout_end = cout_start = cout_end; + tin_start = tin_end = 0; + maxfd = client > target ? client+1 : target+1; + + while (1) { + tv.tv_sec = 1; + tv.tv_usec = 0; + + FD_ZERO(&rlist); + FD_ZERO(&wlist); + FD_ZERO(&elist); + + FD_SET(client, &elist); + FD_SET(target, &elist); + + if (tout_end == tout_start) { + // Nothing queued for target, so read from client + FD_SET(client, &rlist); + } else { + // Data queued for target, so write to it + FD_SET(target, &wlist); + } + if (cout_end == cout_start) { + // Nothing queued for client, so read from target + FD_SET(target, &rlist); + } else { + // Data queued for client, so write to it + FD_SET(client, &wlist); + } + + ret = select(maxfd, &rlist, &wlist, &elist, &tv); + if (pipe_error) { break; } + + if (FD_ISSET(target, &elist)) { + handler_emsg("target exception\n"); + break; + } + if (FD_ISSET(client, &elist)) { + handler_emsg("client exception\n"); + break; + } + + if (ret == -1) { + handler_emsg("select(): %s\n", strerror(errno)); + break; + } else if (ret == 0) { + //handler_emsg("select timeout\n"); + continue; + } + + if (FD_ISSET(target, &wlist)) { + len = tout_end-tout_start; + bytes = send(target, ws_ctx->tout_buf + tout_start, len, 0); + if (pipe_error) { break; } + if (bytes < 0) { + handler_emsg("target connection error: %s\n", + strerror(errno)); + break; + } + tout_start += bytes; + if (tout_start >= tout_end) { + tout_start = tout_end = 0; + traffic(">"); + } else { + traffic(">."); + } + } + + if (FD_ISSET(client, &wlist)) { + len = cout_end-cout_start; + bytes = ws_send(ws_ctx, ws_ctx->cout_buf + cout_start, len); + if (pipe_error) { break; } + if (len < 3) { + handler_emsg("len: %d, bytes: %d: %d\n", + (int) len, (int) bytes, + (int) *(ws_ctx->cout_buf + cout_start)); + } + cout_start += bytes; + if (cout_start >= cout_end) { + cout_start = cout_end = 0; + traffic("<"); + } else { + traffic("<."); + } + } + + if (FD_ISSET(target, &rlist)) { + bytes = recv(target, ws_ctx->cin_buf, DBUFSIZE , 0); + if (pipe_error) { break; } + if (bytes <= 0) { + handler_emsg("target closed connection\n"); + break; + } + cout_start = 0; + if (ws_ctx->hybi) { + cout_end = encode_hybi(ws_ctx->cin_buf, bytes, + ws_ctx->cout_buf, BUFSIZE, 1); + } else { + cout_end = encode_hixie(ws_ctx->cin_buf, bytes, + ws_ctx->cout_buf, BUFSIZE); + } + /* + printf("encoded: "); + for (i=0; i< cout_end; i++) { + printf("%u,", (unsigned char) *(ws_ctx->cout_buf+i)); + } + printf("\n"); + */ + if (cout_end < 0) { + handler_emsg("encoding error\n"); + break; + } + traffic("{"); + } + + if (FD_ISSET(client, &rlist)) { + bytes = ws_recv(ws_ctx, ws_ctx->tin_buf + tin_end, BUFSIZE-1); + if (pipe_error) { break; } + if (bytes <= 0) { + handler_emsg("client closed connection\n"); + break; + } + tin_end += bytes; + /* + printf("before decode: "); + for (i=0; i< bytes; i++) { + printf("%u,", (unsigned char) *(ws_ctx->tin_buf+i)); + } + printf("\n"); + */ + if (ws_ctx->hybi) { + len = decode_hybi(ws_ctx->tin_buf + tin_start, + tin_end-tin_start, + ws_ctx->tout_buf, BUFSIZE-1, + &opcode, &left); + } else { + len = decode_hixie(ws_ctx->tin_buf + tin_start, + tin_end-tin_start, + ws_ctx->tout_buf, BUFSIZE-1, + &opcode, &left); + } + + if (opcode == 8) { + handler_emsg("client sent orderly close frame\n"); + break; + } + + /* + printf("decoded: "); + for (i=0; i< len; i++) { + printf("%u,", (unsigned char) *(ws_ctx->tout_buf+i)); + } + printf("\n"); + */ + if (len < 0) { + handler_emsg("decoding error\n"); + break; + } + if (left) { + tin_start = tin_end - left; + //printf("partial frame from client"); + } else { + tin_start = 0; + tin_end = 0; + } + + traffic("}"); + tout_start = 0; + tout_end = len; + } + } +} + +void proxy_handler(ws_ctx_t *ws_ctx) { + int tsock = 0; + struct sockaddr_in taddr; + + handler_msg("connecting to: %s:%d\n", target_host, target_port); + + tsock = socket(AF_INET, SOCK_STREAM, 0); + if (tsock < 0) { + handler_emsg("Could not create target socket: %s\n", + strerror(errno)); + return; + } + bzero((char *) &taddr, sizeof(taddr)); + taddr.sin_family = AF_INET; + taddr.sin_port = htons(target_port); + + /* Resolve target address */ + if (resolve_host(&taddr.sin_addr, target_host) < -1) { + handler_emsg("Could not resolve target address: %s\n", + strerror(errno)); + } + + if (connect(tsock, (struct sockaddr *) &taddr, sizeof(taddr)) < 0) { + handler_emsg("Could not connect to target: %s\n", + strerror(errno)); + close(tsock); + return; + } + + if ((settings.verbose) && (! settings.daemon)) { + printf("%s", traffic_legend); + } + + do_proxy(ws_ctx, tsock); + + shutdown(tsock, SHUT_RDWR); + close(tsock); +} + +int main(int argc, char *argv[]) +{ + int fd, c, option_index = 0; + static int ssl_only = 0, daemon = 0, run_once = 0, verbose = 0; + char *found; + static struct option long_options[] = { + {"verbose", no_argument, &verbose, 'v'}, + {"ssl-only", no_argument, &ssl_only, 1 }, + {"daemon", no_argument, &daemon, 'D'}, + /* ---- */ + {"run-once", no_argument, 0, 'r'}, + {"cert", required_argument, 0, 'c'}, + {"key", required_argument, 0, 'k'}, + {0, 0, 0, 0} + }; + + settings.cert = realpath("self.pem", NULL); + if (!settings.cert) { + /* Make sure it's always set to something */ + settings.cert = "self.pem"; + } + settings.key = ""; + + while (1) { + c = getopt_long (argc, argv, "vDrc:k:", + long_options, &option_index); + + /* Detect the end */ + if (c == -1) { break; } + + switch (c) { + case 0: + break; // ignore + case 1: + break; // ignore + case 'v': + verbose = 1; + break; + case 'D': + daemon = 1; + break; + case 'r': + run_once = 1; + break; + case 'c': + settings.cert = realpath(optarg, NULL); + if (! settings.cert) { + usage("No cert file at %s\n", optarg); + } + break; + case 'k': + settings.key = realpath(optarg, NULL); + if (! settings.key) { + usage("No key file at %s\n", optarg); + } + break; + default: + usage(""); + } + } + settings.verbose = verbose; + settings.ssl_only = ssl_only; + settings.daemon = daemon; + settings.run_once = run_once; + + if ((argc-optind) != 2) { + usage("Invalid number of arguments\n"); + } + + found = strstr(argv[optind], ":"); + if (found) { + memcpy(settings.listen_host, argv[optind], found-argv[optind]); + settings.listen_port = strtol(found+1, NULL, 10); + } else { + settings.listen_host[0] = '\0'; + settings.listen_port = strtol(argv[optind], NULL, 10); + } + optind++; + if (settings.listen_port == 0) { + usage("Could not parse listen_port\n"); + } + + found = strstr(argv[optind], ":"); + if (found) { + memcpy(target_host, argv[optind], found-argv[optind]); + target_port = strtol(found+1, NULL, 10); + } else { + usage("Target argument must be host:port\n"); + } + if (target_port == 0) { + usage("Could not parse target port\n"); + } + + if (ssl_only) { + if (access(settings.cert, R_OK) != 0) { + usage("SSL only and cert file '%s' not found\n", settings.cert); + } + } else if (access(settings.cert, R_OK) != 0) { + fprintf(stderr, "Warning: '%s' not found\n", settings.cert); + } + + //printf(" verbose: %d\n", settings.verbose); + //printf(" ssl_only: %d\n", settings.ssl_only); + //printf(" daemon: %d\n", settings.daemon); + //printf(" run_once: %d\n", settings.run_once); + //printf(" cert: %s\n", settings.cert); + //printf(" key: %s\n", settings.key); + + settings.handler = proxy_handler; + start_server(); + +} diff --git a/third_party/websockify/other/websockify.clj b/third_party/websockify/other/websockify.clj new file mode 100644 index 00000000..ad1cc336 --- /dev/null +++ b/third_party/websockify/other/websockify.clj @@ -0,0 +1,233 @@ +(ns websockify + ;(:use ring.adapter.jetty) + (:require [clojure.tools.cli :as cli] + [clojure.string :as string]) + + (:import + + ;; Netty TCP Client + [java.util.concurrent Executors] + [java.net InetSocketAddress] + [org.jboss.netty.channel + Channels SimpleChannelHandler ChannelPipelineFactory] + [org.jboss.netty.buffer ChannelBuffers] + [org.jboss.netty.channel.socket.nio NioClientSocketChannelFactory] + [org.jboss.netty.bootstrap ClientBootstrap] + [org.jboss.netty.handler.codec.base64 Base64] + [org.jboss.netty.util CharsetUtil] + + ;; Jetty WebSocket Server + [org.eclipse.jetty.server Server] + [org.eclipse.jetty.server.nio BlockingChannelConnector] + [org.eclipse.jetty.servlet + ServletContextHandler ServletHolder DefaultServlet] + [org.eclipse.jetty.websocket + WebSocket WebSocket$OnTextMessage + WebSocketClientFactory WebSocketClient WebSocketServlet])) + + +;; TCP / NIO + +;; (defn tcp-channel [host port] +;; (try +;; (let [address (InetSocketAddress. host port) +;; channel (doto (SocketChannel/open) +;; (.connect address))] +;; channel) +;; (catch Exception e +;; (println (str "Failed to connect to'" host ":" port "':" e)) +;; nil))) + +;; http://docs.jboss.org/netty/3.2/guide/html/start.html#d0e51 +;; http://stackoverflow.com/questions/5453602/highly-concurrent-http-with-netty-and-nio +;; https://github.com/datskos/ring-netty-adapter/blob/master/src/ring/adapter/netty.clj + + +(defn netty-client [host port open close message] + (let [handler (proxy [SimpleChannelHandler] [] + (channelConnected [ctx e] (open ctx e)) + (channelDisconnected [ctx e] (close ctx e)) + (messageReceived [ctx e] (message ctx e)) + (exceptionCaught [ctx e] + (println "exceptionCaught:" e))) + pipeline (proxy [ChannelPipelineFactory] [] + (getPipeline [] + (doto (Channels/pipeline) + (.addLast "handler" handler)))) + bootstrap (doto (ClientBootstrap. + (NioClientSocketChannelFactory. + (Executors/newCachedThreadPool) + (Executors/newCachedThreadPool))) + (.setPipelineFactory pipeline) + (.setOption "tcpNoDelay" true) + (.setOption "keepAlive" true)) + channel-future (.connect bootstrap (InetSocketAddress. host port)) + channel (.. channel-future (awaitUninterruptibly) (getChannel))] + channel)) + + + +;; WebSockets + +;; http://wiki.eclipse.org/Jetty/Feature/WebSockets +(defn make-websocket-servlet [open close message] + (proxy [WebSocketServlet] [] + (doGet [request response] + ;;(println "doGet" request) + (.. (proxy-super getServletContext) + (getNamedDispatcher (proxy-super getServletName)) + (forward request response))) + (doWebSocketConnect [request response] + (println "doWebSocketConnect") + (reify WebSocket$OnTextMessage + (onOpen [this connection] (open this connection)) + (onClose [this code message] (close this code message)) + (onMessage [this data] (message this data)))))) + +(defn websocket-server + [port & {:keys [open close message ws-path web] + :or {open (fn [_ conn] + (println "New websocket client:" conn)) + close (fn [_ code reason] + (println "Websocket client closed:" code reason)) + message (fn [_ data] + (println "Websocket message:" data)) + + ws-path "/websocket"}}] + (let [http-servlet (doto (ServletHolder. (DefaultServlet.)) + (.setInitParameter "dirAllowed" "true") + (.setInitParameter "resourceBase" web)) + ws-servlet (ServletHolder. + (make-websocket-servlet open close message)) + context (doto (ServletContextHandler.) + (.setContextPath "/") + (.addServlet ws-servlet ws-path)) + connector (doto (BlockingChannelConnector.) + (.setPort port) + (.setMaxIdleTime Integer/MAX_VALUE)) + server (doto (Server.) + (.setHandler context) + (.addConnector connector))] + + (when web (.addServlet context http-servlet "/")) + server)) + + + +;; Websockify + +(defonce settings (atom {})) + +;; WebSocket client to TCP target mappings + +(defonce clients (atom {})) +(defonce targets (atom {})) + + +(defn target-open [ctx e] + (println "Connected to target") + #_(println "channelConnected:" e)) + +(defn target-close [ctx e] + #_(println "channelDisconnected:" e) + (println "Target closed") + (when-let [channel (get @targets (.getChannel ctx))] + (.disconnect channel))) + +(defn target-message [ctx e] + (let [channel (.getChannel ctx) + client (get @targets channel) + msg (.getMessage e) + len (.readableBytes msg) + b64 (Base64/encode msg false) + blen (.readableBytes b64)] + #_(println "received" len "bytes from target") + #_(println "target receive:" (.toString msg 0 len CharsetUtil/UTF_8)) + #_(println "sending to client:" (.toString b64 0 blen CharsetUtil/UTF_8)) + (.sendMessage client (.toString b64 0 blen CharsetUtil/UTF_8)))) + +(defn client-open [this connection] + #_(println "Got WebSocket connection:" connection) + (println "New client") + (let [target (netty-client + (:target-host @settings) + (:target-port @settings) + target-open target-close target-message)] + (swap! clients assoc this {:client connection + :target target}) + (swap! targets assoc target connection))) + +(defn client-close [this code message] + (println "WebSocket connection closed") + (when-let [target (:target (get @clients this))] + (println "Closing target") + (.close target) + (println "Target closed") + (swap! targets dissoc target)) + (swap! clients dissoc this)) + +(defn client-message [this data] + #_(println "WebSocket onMessage:" data) + (let [target (:target (get @clients this)) + cbuf (ChannelBuffers/copiedBuffer data CharsetUtil/UTF_8) + decbuf (Base64/decode cbuf) + rlen (.readableBytes decbuf)] + #_(println "Sending" rlen "bytes to target") + #_(println "Sending to target:" (.toString decbuf 0 rlen CharsetUtil/UTF_8)) + (.write target decbuf))) + +(defn start-websockify + [& {:keys [listen-port target-host target-port web] + :or {listen-port 6080 + target-host "localhost" + target-port 5900 + }}] + + (reset! clients {}) + (reset! targets {}) + + (reset! settings {:target-host target-host + :target-port target-port}) + (let [server (websocket-server listen-port + :web web + :ws-path "/websockify" + :open client-open + :close client-close + :message client-message)] + + (.start server) + + (if web + (println "Serving web requests from:" web) + (println "Not serving web requests")) + + (defn stop-websockify [] + (doseq [client (vals @clients)] + (.disconnect (:client client)) + (.close (:target client))) + (.stop server) + (reset! clients {}) + (reset! targets {}) + nil))) + +(defn -main [& args] + (let [[options args banner] + (cli/cli + args + ["-v" "--[no-]verbose" "Verbose output"] + ["--web" "Run webserver with root at given location"] + ["-h" "--help" "Show help" :default false :flag true] + )] + (when (or (:help options) + (not= 2 (count args))) + (println banner) + (System/exit 0)) + (println options) + (println args) + (let [target (second args) + [target-host target-port] (string/split target #":")] + (start-websockify :listen-port (Integer/parseInt (first args)) + :target-host target-host + :target-port (Integer/parseInt target-port) + :web (:web options)))) + nil)
\ No newline at end of file diff --git a/third_party/websockify/other/websockify.js b/third_party/websockify/other/websockify.js new file mode 100644 index 00000000..cda1aaf9 --- /dev/null +++ b/third_party/websockify/other/websockify.js @@ -0,0 +1,141 @@ +// A WebSocket to TCP socket proxy +// Copyright 2012 Joel Martin +// Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) + +// Known to work with node 0.6 +// Requires node modules: ws, base64, optimist and policyfile +// npm install ws base64 optimist policyfile + +var argv = require('optimist').argv, + net = require('net'), + http = require('http'), + url = require('url'), + path = require('path'), + fs = require('fs'), + policyfile = require('policyfile'), + + base64 = require('base64/build/Release/base64'), + Buffer = require('buffer').Buffer, + WebSocketServer = require('ws').Server, + + httpServer, wsServer, + source_host, source_port, target_host, target_port, + web_path = null; + + +// Handle new WebSocket client +new_client = function(client) { + console.log('WebSocket client connected'); + //console.log('protocol: ' + client.protocol); + + var target = net.createConnection(target_port,target_host); + target.on('begin', function() { + console.log('connected to target'); + }); + target.on('data', function(data) { + client.send(base64.encode(new Buffer(data))); + }); + target.on('end', function() { + console.log('target disconnected'); + }); + + client.on('message', function(msg) { + //console.log('got some message'); + target.write(base64.decode(msg),'binary'); + }); + client.on('close', function(code, reason) { + console.log('WebSocket client disconnected: ' + code + ' [' + reason + ']'); + }); + client.on('error', function(a) { + console.log('WebSocket client error: ' + a); + }); +}; + + +// Send an HTTP error response +http_error = function (response, code, msg) { + response.writeHead(code, {"Content-Type": "text/plain"}); + response.write(msg + "\n"); + response.end(); + return; +} + +// Process an HTTP static file request +http_request = function (request, response) { +// console.log("pathname: " + url.parse(req.url).pathname); +// res.writeHead(200, {'Content-Type': 'text/plain'}); +// res.end('okay'); + + if (! argv.web) { + return http_error(response, 403, "403 Permission Denied"); + } + + var uri = url.parse(request.url).pathname + , filename = path.join(argv.web, uri); + + fs.exists(filename, function(exists) { + if(!exists) { + return http_error(response, 404, "404 Not Found"); + } + + if (fs.statSync(filename).isDirectory()) { + filename += '/index.html'; + } + + fs.readFile(filename, "binary", function(err, file) { + if(err) { + return http_error(response, 500, err); + } + + response.writeHead(200); + response.write(file, "binary"); + response.end(); + }); + }); +}; + +// parse source and target arguments into parts +try { + source_arg = argv._[0].toString(); + target_arg = argv._[1].toString(); + + var idx; + idx = source_arg.indexOf(":"); + if (idx >= 0) { + source_host = source_arg.slice(0, idx); + source_port = parseInt(source_arg.slice(idx+1), 10); + } else { + source_host = ""; + source_port = parseInt(source_arg, 10); + } + + idx = target_arg.indexOf(":"); + if (idx < 0) { + throw("target must be host:port"); + } + target_host = target_arg.slice(0, idx); + target_port = parseInt(target_arg.slice(idx+1), 10); + + if (isNaN(source_port) || isNaN(target_port)) { + throw("illegal port"); + } +} catch(e) { + console.error("wsproxy.py [--web web_dir] [source_addr:]source_port target_addr:target_port"); + process.exit(2); +} + +console.log("WebSocket settings: "); +console.log(" - proxying from " + source_host + ":" + source_port + + " to " + target_host + ":" + target_port); +if (argv.web) { + console.log(" - Web server active. Serving: " + argv.web); +} + +httpServer = http.createServer(http_request); +httpServer.listen(source_port, function() { + wsServer = new WebSocketServer({server: httpServer}); + wsServer.on('connection', new_client); +}); + +// Attach Flash policyfile answer service +policyfile.createServer().listen(-1, httpServer); diff --git a/third_party/websockify/other/websockify.rb b/third_party/websockify/other/websockify.rb new file mode 100755 index 00000000..bdc61f16 --- /dev/null +++ b/third_party/websockify/other/websockify.rb @@ -0,0 +1,171 @@ +#!/usr/bin/env ruby + +# A WebSocket to TCP socket proxy +# Copyright 2011 Joel Martin +# Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) + +require 'socket' +$: << "other" +$: << "../other" +require 'websocket' +require 'optparse' + +# Proxy traffic to and from a WebSockets client to a normal TCP +# socket server target. All traffic to/from the client is base64 +# encoded/decoded to allow binary data to be sent/received to/from +# the target. +class WebSocketProxy < WebSocketServer + + @@Traffic_legend = " +Traffic Legend: + } - Client receive + }. - Client receive partial + { - Target receive + + > - Target send + >. - Target send partial + < - Client send + <. - Client send partial +" + + + def initialize(opts) + vmsg "in WebSocketProxy.initialize" + + super(opts) + + @target_host = opts["target_host"] + @target_port = opts["target_port"] + end + + # Echo back whatever is received + def new_client(client) + + msg "connecting to: %s:%s" % [@target_host, @target_port] + tsock = TCPSocket.open(@target_host, @target_port) + + if @verbose then puts @@Traffic_legend end + + begin + do_proxy(client, tsock) + rescue + tsock.shutdown(Socket::SHUT_RDWR) + tsock.close + raise + end + end + + # Proxy client WebSocket to normal target socket. + def do_proxy(client, target) + cqueue = [] + c_pend = 0 + tqueue = [] + rlist = [client, target] + + loop do + wlist = [] + + if tqueue.length > 0 + wlist << target + end + if cqueue.length > 0 || c_pend > 0 + wlist << client + end + + ins, outs, excepts = IO.select(rlist, wlist, nil, 0.001) + if excepts && excepts.length > 0 + raise Exception, "Socket exception" + end + + # Send queued client data to the target + if outs && outs.include?(target) + dat = tqueue.shift + sent = target.send(dat, 0) + if sent == dat.length + traffic ">" + else + tqueue.unshift(dat[sent...dat.length]) + traffic ".>" + end + end + + # Receive target data and queue for the client + if ins && ins.include?(target) + buf = target.recv(@@Buffer_size) + if buf.length == 0: + raise EClose, "Target closed" + end + + cqueue << buf + traffic "{" + end + + # Encode and send queued data to the client + if outs && outs.include?(client) + c_pend = send_frames(cqueue) + cqueue = [] + end + + # Receive client data, decode it, and send it back + if ins && ins.include?(client) + frames, closed = recv_frames + tqueue += frames + + if closed + send_close + raise EClose, closed + end + end + + end # loop + end +end + +# Parse parameters +opts = {} +parser = OptionParser.new do |o| + o.on('--verbose', '-v') { |b| opts['verbose'] = b } + o.parse! +end + +if ARGV.length < 2: + puts "Too few arguments" + exit 2 +end + +# Parse host:port and convert ports to numbers +if ARGV[0].count(":") > 0 + opts['listen_host'], _, opts['listen_port'] = ARGV[0].rpartition(':') +else + opts['listen_host'], opts['listen_port'] = nil, ARGV[0] +end + +begin + opts['listen_port'] = opts['listen_port'].to_i +rescue + puts "Error parsing listen port" + exit 2 +end + +if ARGV[1].count(":") > 0 + opts['target_host'], _, opts['target_port'] = ARGV[1].rpartition(':') +else + puts "Error parsing target" + exit 2 +end + +begin + opts['target_port'] = opts['target_port'].to_i +rescue + puts "Error parsing target port" + exit 2 +end + +puts "Starting server on #{opts['listen_host']}:#{opts['listen_port']}" +server = WebSocketProxy.new(opts) +server.start(100) +server.join + +puts "Server has been terminated" + +# vim: sw=2 diff --git a/third_party/websockify/other/wswrap b/third_party/websockify/other/wswrap new file mode 100755 index 00000000..da7a7304 --- /dev/null +++ b/third_party/websockify/other/wswrap @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + +usage() { + echo "Usage: $(basename $0) PORT CMDLINE" + echo + echo " PORT Port to wrap with WebSockets support" + echo " CMDLINE Command line to wrap" + exit 2 +} + +# Parameter defaults +mydir=$(readlink -f $(dirname ${0})) + +# Process parameters +#while [ "${1}" != "${1#-}" ]; do +# param=$1; shift +#done + +export WSWRAP_PORT="${1}"; shift + +LD_PRELOAD=${mydir}/wswrapper.so "${@}" + diff --git a/third_party/websockify/rebind b/third_party/websockify/rebind new file mode 100755 index 00000000..2289aaa4 --- /dev/null +++ b/third_party/websockify/rebind @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +usage() { + echo "Usage: $(basename $0) OLD_PORT NEW_PORT COMMAND_LINE" + echo + echo "Launch COMMAND_LINE, but intercept system calls to bind" + echo "to OLD_PORT and instead bind them to localhost:NEW_PORT" + exit 2 +} + +# Parameter defaults +mydir=$(readlink -f $(dirname ${0})) + +export REBIND_PORT_OLD="${1}"; shift +export REBIND_PORT_NEW="${1}"; shift + +LD_PRELOAD=${mydir}/rebind.so "${@}" + diff --git a/third_party/websockify/rebind.c b/third_party/websockify/rebind.c new file mode 100644 index 00000000..d7b004d6 --- /dev/null +++ b/third_party/websockify/rebind.c @@ -0,0 +1,94 @@ +/* + * rebind: Intercept bind calls and bind to a different port + * Copyright 2010 Joel Martin + * Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) + * + * Overload (LD_PRELOAD) bind system call. If REBIND_PORT_OLD and + * REBIND_PORT_NEW environment variables are set then bind on the new + * port (of localhost) instead of the old port. + * + * This allows a proxy (such as wsproxy) to run on the old port and translate + * traffic to/from the new port. + * + * Usage: + * LD_PRELOAD=./rebind.so \ + * REBIND_PORT_OLD=23 \ + * REBIND_PORT_NEW=2023 \ + * program + */ + +//#define DO_DEBUG 1 + +#include <stdio.h> +#include <stdlib.h> + +#define __USE_GNU 1 // Pull in RTLD_NEXT +#include <dlfcn.h> + +#include <string.h> +#include <netinet/in.h> + + +#if defined(DO_DEBUG) +#define DEBUG(...) \ + fprintf(stderr, "rebind: "); \ + fprintf(stderr, __VA_ARGS__); +#else +#define DEBUG(...) +#endif + + +int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) +{ + static void * (*func)(); + int do_move = 0; + struct sockaddr_in * addr_in = (struct sockaddr_in *)addr; + struct sockaddr_in addr_tmp; + socklen_t addrlen_tmp; + char * PORT_OLD, * PORT_NEW, * end1, * end2; + int ret, oldport, newport, askport = htons(addr_in->sin_port); + uint32_t askaddr = htons(addr_in->sin_addr.s_addr); + if (!func) func = (void *(*)()) dlsym(RTLD_NEXT, "bind"); + + DEBUG(">> bind(%d, _, %d), askaddr %d, askport %d\n", + sockfd, addrlen, askaddr, askport); + + /* Determine if we should move this socket */ + if (addr_in->sin_family == AF_INET) { + // TODO: support IPv6 + PORT_OLD = getenv("REBIND_OLD_PORT"); + PORT_NEW = getenv("REBIND_NEW_PORT"); + if (PORT_OLD && (*PORT_OLD != '\0') && + PORT_NEW && (*PORT_NEW != '\0')) { + oldport = strtol(PORT_OLD, &end1, 10); + newport = strtol(PORT_NEW, &end2, 10); + if (oldport && (*end1 == '\0') && + newport && (*end2 == '\0') && + (oldport == askport)) { + do_move = 1; + } + } + } + + if (! do_move) { + /* Just pass everything right through to the real bind */ + ret = (long) func(sockfd, addr, addrlen); + DEBUG("<< bind(%d, _, %d) ret %d\n", sockfd, addrlen, ret); + return ret; + } + + DEBUG("binding fd %d on localhost:%d instead of 0x%x:%d\n", + sockfd, newport, ntohl(addr_in->sin_addr.s_addr), oldport); + + /* Use a temporary location for the new address information */ + addrlen_tmp = sizeof(addr_tmp); + memcpy(&addr_tmp, addr, addrlen_tmp); + + /* Bind to other port on the loopback instead */ + addr_tmp.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + addr_tmp.sin_port = htons(newport); + ret = (long) func(sockfd, &addr_tmp, addrlen_tmp); + + DEBUG("<< bind(%d, _, %d) ret %d\n", sockfd, addrlen, ret); + return ret; +} diff --git a/third_party/websockify/run b/third_party/websockify/run new file mode 100755 index 00000000..54db9b8d --- /dev/null +++ b/third_party/websockify/run @@ -0,0 +1,5 @@ +#!/usr/bin/python + +import websockify + +websockify.websocketproxy.websockify_init() diff --git a/third_party/websockify/setup.py b/third_party/websockify/setup.py new file mode 100644 index 00000000..947f0a52 --- /dev/null +++ b/third_party/websockify/setup.py @@ -0,0 +1,30 @@ +from setuptools import setup, find_packages + +version = '0.1.0' +name = 'websockify' +long_description = open("README.md").read() + "\n" + \ + open("CHANGES.txt").read() + "\n" + +setup(name=name, + version=version, + description="Websockify.", + long_description=long_description, + classifiers=[ + "Programming Language :: Python", + ], + keywords='noVNC websockify', + license='LGPLv3', + url="https://github.com/kanaka/websockify", + author="Joel Martin", + author_email="github@martintribe.org", + + packages=['websockify'], + include_package_data=True, + install_requires=['numpy'], + zip_safe=False, + entry_points={ + 'console_scripts': [ + 'websockify = websockify.websocketproxy:websockify_init', + ] + }, + ) diff --git a/third_party/websockify/tests/b64_vs_utf8.py b/third_party/websockify/tests/b64_vs_utf8.py new file mode 100755 index 00000000..9af7b621 --- /dev/null +++ b/third_party/websockify/tests/b64_vs_utf8.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python + +from base64 import b64encode, b64decode +from codecs import (utf_8_encode, utf_8_decode, + latin_1_encode, latin_1_decode) +import random, time + +buf_len = 10000 +iterations = 10000 + +print "Generating random input buffer" +r = random.Random() +buf = "".join([chr(r.randint(0, 255)) for i in range(buf_len)]) + +tests = {'UTF8 encode': lambda: utf_8_encode(unicode(buf, 'latin-1'))[0], + 'B64 encode': lambda: b64encode(buf)} +utf8_buf = tests['UTF8 encode']() +b64_buf = tests['B64 encode']() +tests.update({'UTF8 decode': lambda: latin_1_encode(utf_8_decode(utf8_buf)[0])[0], + 'B64 decode': lambda: b64decode(b64_buf)}) + +print "Running tests" +for test in 'UTF8 encode', 'B64 encode', 'UTF8 decode', 'B64 decode': + start = time.time() + for i in range(iterations): + res_buf = tests[test]() + print "%s took %s seconds (result size %s)" % ( + test, (time.time() - start), len(res_buf)) + diff --git a/third_party/websockify/tests/base64.html b/third_party/websockify/tests/base64.html new file mode 100644 index 00000000..24ad80b5 --- /dev/null +++ b/third_party/websockify/tests/base64.html @@ -0,0 +1,91 @@ +<!DOCTYPE html> +<html xmlns="http://www.w3.org/1999/xhtml"> + <head> + <title>Native Base64 Tests</title> + <script src="include/util.js"></script> + <script src="include/webutil.js"></script> + <script src="include/base64.js"></script> + </head> + <body> + <h1>Native Base64 Tests</h1> + + <br> + Messages:<br> + <textarea id="debug" style="font-size: 9px;" cols=80 rows=25></textarea> + + <br> + </body> + +<script> + function debug(str) { + console.log(str); + cell = $D('debug'); + cell.innerHTML += str + "\n"; + cell.scrollTop = cell.scrollHeight; + } + + function assertRun(code, result) { + try { + var actual = eval(code); + } catch (exc) { + debug("FAIL: '" + code + "' threw an exception"); + fail += 1; + return false; + } + if (actual !== result) { + debug("FAIL: '" + code + "' returned '" + actual + "', expected '" + result + "'"); + fail += 1; + return false; + } + debug("PASS: '" + code + "' returned expected '" + result +"'"); + pass += 1; + return true; + } + + function Base64_decode(data) { + var arr = Base64.decode (data); + return arr.map(function (num) { + return String.fromCharCode(num); } ).join(''); + + } + + window.onload = function() { + var str; + debug('onload'); + fail = 0; + pass = 0; + assertRun('window.btoa("hello world")', 'aGVsbG8gd29ybGQ='); + assertRun('window.btoa("a")', 'YQ=='); + assertRun('window.btoa("ab")', 'YWI='); + assertRun('window.btoa("abc")', 'YWJj'); + assertRun('window.btoa("abcd")', 'YWJjZA=='); + assertRun('window.btoa("abcde")', 'YWJjZGU='); + assertRun('window.btoa("abcdef")', 'YWJjZGVm'); + assertRun('window.btoa("abcdefg")', 'YWJjZGVmZw=='); + assertRun('window.btoa("abcdefgh")', 'YWJjZGVmZ2g='); + + assertRun('window.atob("aGVsbG8gd29ybGQ=")', 'hello world'); + assertRun('Base64_decode("aGVsbG8gd29ybGQ=")', 'hello world'); + assertRun('window.atob("YQ==")', 'a'); + assertRun('Base64_decode("YQ==")', 'a'); + assertRun('window.atob("YWI=")', 'ab'); + assertRun('Base64_decode("YWI=")', 'ab'); + assertRun('window.atob("YWJj")', 'abc'); + assertRun('Base64_decode("YWJj")', 'abc'); + assertRun('window.atob("YWJjZA==")', 'abcd'); + assertRun('Base64_decode("YWJjZA==")', 'abcd'); + assertRun('window.atob("YWJjZGU=")', 'abcde'); + assertRun('Base64_decode("YWJjZGU=")', 'abcde'); + assertRun('window.atob("YWJjZGVm")', 'abcdef'); + assertRun('Base64_decode("YWJjZGVm")', 'abcdef'); + + assertRun('typeof window.btoa', 'function'); + assertRun('window.btoa("")', ''); + assertRun('window.btoa(null)', ''); + assertRun('window.atob(window.btoa(window))', window.toString()); // "[object DOMWindow]" + assertRun('window.btoa("\\u0080\\u0081")', 'gIE='); + + debug("Tests failed: " + fail); + debug("Tests passed: " + pass); + } +</script> diff --git a/third_party/websockify/tests/base64.js b/third_party/websockify/tests/base64.js new file mode 100644 index 00000000..6ade00a3 --- /dev/null +++ b/third_party/websockify/tests/base64.js @@ -0,0 +1,12 @@ +// The following results in 'hello [MANGLED]' +// +// Filed as https://github.com/ry/node/issues/issue/402 + +var sys = require("sys"), + buf = new Buffer(1024), len, + str1 = "aGVsbG8g", // 'hello ' + str2 = "d29ybGQ=", // 'world' + +len = buf.write(str1, 0, 'base64'); +len += buf.write(str2, len, 'base64'); +sys.log("decoded result: " + buf.toString('binary', 0, len)); diff --git a/third_party/websockify/tests/echo.html b/third_party/websockify/tests/echo.html new file mode 100644 index 00000000..cc8b642f --- /dev/null +++ b/third_party/websockify/tests/echo.html @@ -0,0 +1,148 @@ +<html> + + <head> + <title>WebSockets Echo Test</title> + <script src="include/util.js"></script> + <script src="include/webutil.js"></script> + <script src="include/base64.js"></script> + <script src="include/websock.js"></script> + <!-- Uncomment to activate firebug lite --> + <!-- + <script type='text/javascript' + src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script> + --> + + + </head> + + <body> + + Host: <input id='host' style='width:100'> + Port: <input id='port' style='width:50'> + Encrypt: <input id='encrypt' type='checkbox'> + <input id='connectButton' type='button' value='Start' style='width:100px' + onclick="connect();"> + + + <br> + Log:<br> + <textarea id="messages" style="font-size: 9;" cols=80 rows=25></textarea> + </body> + + + <script> + var ws, host = null, port = null, + msg_cnt = 0, send_cnt = 1, echoDelay = 500, + echo_ref; + + function message(str) { + console.log(str); + cell = $D('messages'); + cell.innerHTML += msg_cnt + ": " + str + "\n"; + cell.scrollTop = cell.scrollHeight; + msg_cnt++; + } + + Array.prototype.pushStr = function (str) { + var n = str.length; + for (var i=0; i < n; i++) { + this.push(str.charCodeAt(i)); + } + } + + function send_msg() { + var str = "Message #" + send_cnt; + ws.send_string(str); + message("Sent message: '" + str + "'"); + send_cnt++; + } + + function update_stats() { + $D('sent').innerHTML = sent; + $D('received').innerHTML = received; + $D('errors').innerHTML = errors; + } + + function connect() { + var host = $D('host').value, + port = $D('port').value, + scheme = "ws://", uri; + + console.log(">> connect"); + if ((!host) || (!port)) { + console.log("must set host and port"); + return; + } + + if (ws) { + ws.close(); + } + + if ($D('encrypt').checked) { + scheme = "wss://"; + } + uri = scheme + host + ":" + port; + message("connecting to " + uri); + + ws = new Websock(); + ws.open(uri); + + ws.on('message', function(e) { + //console.log(">> WebSockets.onmessage"); + var str = ws.rQshiftStr(); + + message("Received message '" + str + "'"); + //console.log("<< WebSockets.onmessage"); + }); + ws.on('open', function(e) { + console.log(">> WebSockets.onopen"); + echo_ref = setInterval(send_msg, echoDelay); + console.log("<< WebSockets.onopen"); + }); + ws.on('close', function(e) { + console.log(">> WebSockets.onclose"); + if (echo_ref) { + clearInterval(echo_ref); + echo_ref = null; + } + console.log("<< WebSockets.onclose"); + }); + ws.on('error', function(e) { + console.log(">> WebSockets.onerror"); + if (echo_ref) { + clearInterval(echo_ref); + echo_ref = null; + } + console.log("<< WebSockets.onerror"); + }); + + $D('connectButton').value = "Stop"; + $D('connectButton').onclick = disconnect; + console.log("<< connect"); + } + + function disconnect() { + console.log(">> disconnect"); + if (ws) { + ws.close(); + } + + if (echo_ref) { + clearInterval(echo_ref); + } + + $D('connectButton').value = "Start"; + $D('connectButton').onclick = connect; + console.log("<< disconnect"); + } + + + window.onload = function() { + console.log("onload"); + var url = document.location.href; + $D('host').value = (url.match(/host=([^&#]*)/) || ['',window.location.hostname])[1]; + $D('port').value = (url.match(/port=([^&#]*)/) || ['',window.location.port])[1]; + } + </script> + +</html> diff --git a/third_party/websockify/tests/echo.py b/third_party/websockify/tests/echo.py new file mode 100755 index 00000000..878c31ae --- /dev/null +++ b/third_party/websockify/tests/echo.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python + +''' +A WebSocket server that echos back whatever it receives from the client. +Copyright 2010 Joel Martin +Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) + +You can make a cert/key with openssl using: +openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem +as taken from http://docs.python.org/dev/library/ssl.html#certificates +''' + +import os, sys, select, optparse +sys.path.insert(0,os.path.dirname(__file__) + "/../") +from websocket import WebSocketServer + +class WebSocketEcho(WebSocketServer): + """ + WebSockets server that echos back whatever is received from the + client. """ + buffer_size = 8096 + + def new_client(self): + """ + Echo back whatever is received. + """ + + cqueue = [] + c_pend = 0 + cpartial = "" + rlist = [self.client] + + while True: + wlist = [] + + if cqueue or c_pend: wlist.append(self.client) + ins, outs, excepts = select.select(rlist, wlist, [], 1) + if excepts: raise Exception("Socket exception") + + if self.client in outs: + # Send queued target data to the client + c_pend = self.send_frames(cqueue) + cqueue = [] + + if self.client in ins: + # Receive client data, decode it, and send it back + frames, closed = self.recv_frames() + cqueue.extend(frames) + + if closed: + self.send_close() + raise self.EClose(closed) + +if __name__ == '__main__': + parser = optparse.OptionParser(usage="%prog [options] listen_port") + parser.add_option("--verbose", "-v", action="store_true", + help="verbose messages and per frame traffic") + parser.add_option("--cert", default="self.pem", + help="SSL certificate file") + parser.add_option("--key", default=None, + help="SSL key file (if separate from cert)") + parser.add_option("--ssl-only", action="store_true", + help="disallow non-encrypted connections") + (opts, args) = parser.parse_args() + + try: + if len(args) != 1: raise + opts.listen_port = int(args[0]) + except: + parser.error("Invalid arguments") + + opts.web = "." + server = WebSocketEcho(**opts.__dict__) + server.start_server() + diff --git a/third_party/websockify/tests/echo.rb b/third_party/websockify/tests/echo.rb new file mode 100755 index 00000000..ea34db5d --- /dev/null +++ b/third_party/websockify/tests/echo.rb @@ -0,0 +1,62 @@ +#!/usr/bin/env ruby + +# A WebSocket server that echos back whatever it receives from the client. +# Copyright 2011 Joel Martin +# Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) + +require 'socket' +$: << "other" +$: << "../other" +require 'websocket' + +class WebSocketEcho < WebSocketServer + + # Echo back whatever is received + def new_client(client) + + cqueue = [] + c_pend = 0 + rlist = [client] + + loop do + wlist = [] + + if cqueue.length > 0 or c_pend + wlist << client + end + + ins, outs, excepts = IO.select(rlist, wlist, nil, 1) + if excepts.length > 0 + raise Exception, "Socket exception" + end + + if outs.include?(client) + # Send queued data to the client + c_pend = send_frames(cqueue) + cqueue = [] + end + + if ins.include?(client) + # Receive client data, decode it, and send it back + frames, closed = recv_frames + cqueue += frames + + if closed + raise EClose, closed + end + end + + end # loop + end +end + +port = ARGV[0].to_i +puts "Starting server on port #{port}" + +server = WebSocketEcho.new('listen_port' => port, 'verbose' => true) +server.start +server.join + +puts "Server has been terminated" + +# vim: sw=2 diff --git a/third_party/websockify/tests/include b/third_party/websockify/tests/include new file mode 120000 index 00000000..f5030fe8 --- /dev/null +++ b/third_party/websockify/tests/include @@ -0,0 +1 @@ +../include
\ No newline at end of file diff --git a/third_party/websockify/tests/latency.html b/third_party/websockify/tests/latency.html new file mode 100644 index 00000000..74538a48 --- /dev/null +++ b/third_party/websockify/tests/latency.html @@ -0,0 +1,290 @@ +<html> + + <head> + <title>WebSockets Latency Test</title> + <script src="include/base64.js"></script> + <script src="include/util.js"></script> + <script src="include/webutil.js"></script> + <script src="include/websock.js"></script> + <!-- Uncomment to activate firebug lite --> + <!-- + <script type='text/javascript' + src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script> + --> + + + </head> + + <body> + + Host: <input id='host' style='width:100'> + Port: <input id='port' style='width:50'> + Encrypt: <input id='encrypt' type='checkbox'> + <br> + Payload Size: <input id='payload_size' style='width:50'> + Send Delay (ms): <input id='sendDelay' style='width:50' value="10"> + <input id='connectButton' type='button' value='Start' style='width:100px' + onclick="connect();"> + + <br><br> + <table border=1> + <tr> + <th align="right">Packets sent:</th> + <td align="right"><div id='sent'></div></td> + </tr><tr> + <th align="right">Packets Received:</th> + <td align="right"><div id='received'></div></td> + </tr><tr> + <th align="right">Average Latency:</th> + <td align="right"><div id='laverage'></div></td> + </tr><tr> + <th align="right">40 Frame Running Average Latency:</th> + <td align="right"><div id='lrunning'></div></td> + </tr><tr> + <th align="right">Minimum Latency:</th> + <td align="right"><div id='lmin'></div></td> + </tr><tr> + <th align="right">Maximum Latency:</th> + <td align="right"><div id='lmax'></div></td> + </tr> + </table> + + <br> + Messages:<br> + <textarea id="messages" style="font-size: 9;" cols=80 rows=10></textarea> + </body> + + + <script> + + var host = null, port = null, sendDelay = 0, actualSendDelay, + ws = null, send_ref = null, + sent, received, latencies, ltotal, laverage, lrunning, lmin, lmax, + run_length = 40, + payload_size = 2000, payload, + msg_cnt = 0, recv_seq = 0, send_seq = 0; + + Array.prototype.pushStr = function (str) { + var n = str.length; + for (var i=0; i < n; i++) { + this.push(str.charCodeAt(i)); + } + } + + + function message(str) { + console.log(str); + cell = $D('messages'); + msg_cnt++; + cell.innerHTML += msg_cnt + ": " + str + "\n"; + cell.scrollTop = cell.scrollHeight; + } + + + function add (x,y) { + return parseInt(x,10)+parseInt(y,10); + } + + function recvMsg(data) { + //console.log(">> check_respond"); + var i, now, arr, first, last, arr, latency; + + now = (new Date()).getTime(); // Early as possible + + arr = ws.rQshiftBytes(ws.rQlen()); + first = String.fromCharCode(arr.shift()); + last = String.fromCharCode(arr.pop()); + + if (first != "^") { + message("Error: packet missing start char '^'"); + disconnect(); + return; + } + if (last != "$") { + message("Error: packet missing end char '$'"); + disconnect(); + return; + } + arr = arr.map(function(num) { + return String.fromCharCode(num); + } ).join('').split(':'); + seq = arr[0]; + timestamp = parseInt(arr[1],10); + rpayload = arr[2]; + + if (seq != recv_seq) { + message("Error: expected seq " + recv_seq + " but got " + seq); + disconnect(); + return; + } + recv_seq++; + if (payload !== rpayload) { + message("Payload corrupt"); + disconnect(); + return; + } + + received++; + + latency = now - timestamp; + latencies.push(latency); + if (latencies.length > run_length) { + latencies.shift(); + } + ltotal += latency; + laverage = ltotal / received; + lrunning = 0; + for (var i=0; i < latencies.length; i++) { + lrunning += latencies[i]; + } + lrunning = lrunning / latencies.length; + + if (latency < lmin) { + lmin = latency; + } + if (latency > lmax) { + lmax = latency; + } + + showStats(); + //console.log("<< check_respond"); + } + + function sendMsg() { + var arr = []; + if (! ws.flush() ) { + message("WebSocket not ready, backing off"); + actualSendDelay = actualSendDelay * 2; + send_ref = setTimeout(sendMsg, actualSendDelay); + return false; + } else { + // Scale the delay down to the requested minimum + if (actualSendDelay > sendDelay) { + message("WebSocket ready, increasing presure"); + actualSendDelay = Math.max(actualSendDelay / 2, sendDelay); + } + } + + timestamp = (new Date()).getTime(); + arr.pushStr("^" + send_seq + ":" + timestamp + ":" + payload + "$"); + send_seq ++; + ws.send(arr); + sent++; + + showStats(); + send_ref = setTimeout(sendMsg, actualSendDelay); + } + + function showStats() { + $D('sent').innerHTML = sent; + $D('received').innerHTML = received; + $D('laverage').innerHTML = laverage.toFixed(2); + $D('lrunning').innerHTML = lrunning.toFixed(2); + $D('lmin').innerHTML = lmin.toFixed(2); + $D('lmax').innerHTML = lmax.toFixed(2); + } + + function init_ws() { + console.log(">> init_ws"); + var scheme = "ws://"; + if ($D('encrypt').checked) { + scheme = "wss://"; + } + var uri = scheme + host + ":" + port; + console.log("connecting to " + uri); + ws = new Websock(); + ws.maxBufferedAmount = 5000; + ws.open(uri); + + ws.on('message', function() { + recvMsg(); + }); + ws.on('open', function() { + send_ref = setTimeout(sendMsg, sendDelay); + }); + ws.on('close', function(e) { + disconnect(); + }); + ws.on('error', function(e) { + message("Websock error: " + e); + disconnect(); + }); + + console.log("<< init_ws"); + } + + function connect() { + console.log(">> connect"); + host = $D('host').value; + port = $D('port').value; + payload_size = parseInt($D('payload_size').value, 10); + sendDelay = parseInt($D('sendDelay').value, 10); + + if ((!host) || (!port)) { + console.log("must set host and port"); + return; + } + + if (ws) { + ws.close(); + } + init_ws(); + + // Populate payload data + var numlist = [] + for (var i=0; i < payload_size; i++) { + numlist.push( Math.floor(Math.random()*10) ); + } + payload = numlist.join(''); + + // Initialize stats + sent = 0; + received = 0; + latencies = []; + ltotal = 0; + laverage = 0; + lrunning = 0; + lmin = 999999999; + lmax = 0; + actualSendDelay = sendDelay; + + $D('connectButton').value = "Stop"; + $D('connectButton').onclick = disconnect; + console.log("<< connect"); + } + + function disconnect() { + console.log(">> disconnect"); + if (ws) { + ws.close(); + } + + if (send_ref) { + clearInterval(send_ref); + send_ref = null; + } + showStats(); // Final numbers + recv_seq = 0; + send_seq = 0; + + $D('connectButton').value = "Start"; + $D('connectButton').onclick = connect; + console.log("<< disconnect"); + } + + + window.onload = function() { + console.log("onload"); + if (Websock_native) { + message("Using native WebSockets"); + } else { + message("initializing web-socket-js flash bridge"); + } + var url = document.location.href; + $D('host').value = (url.match(/host=([^&#]*)/) || ['',window.location.hostname])[1]; + $D('port').value = (url.match(/port=([^&#]*)/) || ['',window.location.port])[1]; + $D('payload_size').value = payload_size; + } + </script> + +</html> diff --git a/third_party/websockify/tests/latency.py b/third_party/websockify/tests/latency.py new file mode 120000 index 00000000..3ae4d964 --- /dev/null +++ b/third_party/websockify/tests/latency.py @@ -0,0 +1 @@ +echo.py
\ No newline at end of file diff --git a/third_party/websockify/tests/load.html b/third_party/websockify/tests/load.html new file mode 100644 index 00000000..af165dca --- /dev/null +++ b/third_party/websockify/tests/load.html @@ -0,0 +1,250 @@ +<html> + + <head> + <title>WebSockets Load Test</title> + <script src="include/util.js"></script> + <script src="include/webutil.js"></script> + <script src="include/base64.js"></script> + <script src="include/websock.js"></script> + <!-- Uncomment to activate firebug lite --> + <!-- + <script type='text/javascript' + src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script> + --> + + + </head> + + <body> + + Host: <input id='host' style='width:100'> + Port: <input id='port' style='width:50'> + Encrypt: <input id='encrypt' type='checkbox'> + Send Delay (ms): <input id='sendDelay' style='width:50' value="100"> + <input id='connectButton' type='button' value='Start' style='width:100px' + onclick="connect();"> + + <br><br> + <table border=1> + <tr> + <th align="right">Packets sent:</th> + <td align="right"><div id='sent'>0</div></td> + </tr><tr> + <th align="right">Good Packets Received:</th> + <td align="right"><div id='received'>0</div></td> + </tr><tr> + <th align="right">Errors (Bad Packets Received:)</th> + <td align="right"><div id='errors'>0</div></td> + </tr> + </table> + + <br> + Errors:<br> + <textarea id="error" style="font-size: 9;" cols=80 rows=25></textarea> + </body> + + + <script> + + function error(str) { + console.error(str); + cell = $D('error'); + cell.innerHTML += errors + ": " + str + "\n"; + cell.scrollTop = cell.scrollHeight; + } + + var host = null, port = null, sendDelay = 0; + var ws = null, update_ref = null, send_ref = null; + var sent = 0, received = 0, errors = 0; + var max_send = 2000; + var recv_seq = 0, send_seq = 0; + + Array.prototype.pushStr = function (str) { + var n = str.length; + for (var i=0; i < n; i++) { + this.push(str.charCodeAt(i)); + } + } + + + + function add (x,y) { + return parseInt(x,10)+parseInt(y,10); + } + + function check_respond(data) { + //console.log(">> check_respond"); + var first, last, str, length, chksum, nums, arr; + first = String.fromCharCode(data.shift()); + last = String.fromCharCode(data.pop()); + + if (first != "^") { + errors++; + error("Packet missing start char '^'"); + return; + } + if (last != "$") { + errors++; + error("Packet missing end char '$'"); + return; + } + arr = data.map(function(num) { + return String.fromCharCode(num); + } ).join('').split(':'); + seq = arr[0]; + length = arr[1]; + chksum = arr[2]; + nums = arr[3]; + + //console.log(" length:" + length + " chksum:" + chksum + " nums:" + nums); + if (seq != recv_seq) { + errors++; + error("Expected seq " + recv_seq + " but got " + seq); + recv_seq = parseInt(seq,10) + 1; // Back on track + return; + } + recv_seq++; + if (nums.length != length) { + errors++; + error("Expected length " + length + " but got " + nums.length); + return; + } + //real_chksum = nums.reduce(add); + real_chksum = 0; + for (var i=0; i < nums.length; i++) { + real_chksum += parseInt(nums.charAt(i), 10); + } + if (real_chksum != chksum) { + errors++ + error("Expected chksum " + chksum + " but real chksum is " + real_chksum); + return; + } + received++; + //console.log(" Packet checks out: length:" + length + " chksum:" + chksum); + //console.log("<< check_respond"); + } + + function send() { + var length = Math.floor(Math.random()*(max_send-9)) + 10; // 10 - max_send + var numlist = [], arr = []; + for (var i=0; i < length; i++) { + numlist.push( Math.floor(Math.random()*10) ); + } + //chksum = numlist.reduce(add); + chksum = 0; + for (var i=0; i < numlist.length; i++) { + chksum += parseInt(numlist[i], 10); + } + var nums = numlist.join(''); + arr.pushStr("^" + send_seq + ":" + length + ":" + chksum + ":" + nums + "$") + send_seq ++; + ws.send(arr); + sent++; + } + + function update_stats() { + $D('sent').innerHTML = sent; + $D('received').innerHTML = received; + $D('errors').innerHTML = errors; + } + + function init_ws() { + console.log(">> init_ws"); + var scheme = "ws://"; + if ($D('encrypt').checked) { + scheme = "wss://"; + } + var uri = scheme + host + ":" + port; + console.log("connecting to " + uri); + ws = new Websock(); + ws.open(uri); + + ws.on('message', function() { + //console.log(">> WebSockets.onmessage"); + arr = ws.rQshiftBytes(ws.rQlen()); + check_respond(arr); + //console.log("<< WebSockets.onmessage"); + }); + ws.on('open', function() { + console.log(">> WebSockets.onopen"); + send_ref = setInterval(send, sendDelay); + console.log("<< WebSockets.onopen"); + }); + ws.on('close', function(e) { + console.log(">> WebSockets.onclose"); + clearInterval(send_ref); + console.log("<< WebSockets.onclose"); + }); + ws.on('error', function(e) { + console.log(">> WebSockets.onerror"); + console.log(" " + e); + console.log("<< WebSockets.onerror"); + }); + + console.log("<< init_ws"); + } + + function connect() { + console.log(">> connect"); + host = $D('host').value; + port = $D('port').value; + sendDelay = parseInt($D('sendDelay').value, 10); + if ((!host) || (!port)) { + console.log("must set host and port"); + return; + } + + if (ws) { + ws.close(); + } + init_ws(); + update_ref = setInterval(update_stats, 1); + + $D('connectButton').value = "Stop"; + $D('connectButton').onclick = disconnect; + console.log("<< connect"); + } + + function disconnect() { + console.log(">> disconnect"); + if (ws) { + ws.close(); + } + + clearInterval(update_ref); + update_stats(); // Final numbers + recv_seq = 0; + send_seq = 0; + + $D('connectButton').value = "Start"; + $D('connectButton').onclick = connect; + console.log("<< disconnect"); + } + + + /* If no builtin websockets then load web_socket.js */ + if (window.WebSocket) { + VNC_native_ws = true; + } else { + VNC_native_ws = false; + console.log("Loading web-socket-js flash bridge"); + var extra = "<script src='include/web-socket-js/swfobject.js'><\/script>"; + extra += "<script src='include/web-socket-js/FABridge.js'><\/script>"; + extra += "<script src='include/web-socket-js/web_socket.js'><\/script>"; + document.write(extra); + } + + window.onload = function() { + console.log("onload"); + if (!VNC_native_ws) { + console.log("initializing web-socket-js flash bridge"); + WebSocket.__swfLocation = "include/web-socket-js/WebSocketMain.swf"; + WebSocket.__initialize(); + } + var url = document.location.href; + $D('host').value = (url.match(/host=([^&#]*)/) || ['',''])[1]; + $D('port').value = (url.match(/port=([^&#]*)/) || ['',''])[1]; + } + </script> + +</html> diff --git a/third_party/websockify/tests/load.py b/third_party/websockify/tests/load.py new file mode 100755 index 00000000..0501f7da --- /dev/null +++ b/third_party/websockify/tests/load.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python + +''' +WebSocket server-side load test program. Sends and receives traffic +that has a random payload (length and content) that is checksummed and +given a sequence number. Any errors are reported and counted. +''' + +import sys, os, select, random, time, optparse +sys.path.insert(0,os.path.dirname(__file__) + "/../") +from websocket import WebSocketServer + +class WebSocketLoad(WebSocketServer): + + buffer_size = 65536 + + max_packet_size = 10000 + recv_cnt = 0 + send_cnt = 0 + + def __init__(self, *args, **kwargs): + self.errors = 0 + self.delay = kwargs.pop('delay') + + print "Prepopulating random array" + self.rand_array = [] + for i in range(0, self.max_packet_size): + self.rand_array.append(random.randint(0, 9)) + + WebSocketServer.__init__(self, *args, **kwargs) + + def new_client(self): + self.send_cnt = 0 + self.recv_cnt = 0 + + try: + self.responder(self.client) + except: + print "accumulated errors:", self.errors + self.errors = 0 + raise + + def responder(self, client): + c_pend = 0 + cqueue = [] + cpartial = "" + socks = [client] + last_send = time.time() * 1000 + + while True: + ins, outs, excepts = select.select(socks, socks, socks, 1) + if excepts: raise Exception("Socket exception") + + if client in ins: + frames, closed = self.recv_frames() + + err = self.check(frames) + if err: + self.errors = self.errors + 1 + print err + + if closed: + self.send_close() + raise self.EClose(closed) + + now = time.time() * 1000 + if client in outs: + if c_pend: + last_send = now + c_pend = self.send_frames() + elif now > (last_send + self.delay): + last_send = now + c_pend = self.send_frames([self.generate()]) + + def generate(self): + length = random.randint(10, self.max_packet_size) + numlist = self.rand_array[self.max_packet_size-length:] + # Error in length + #numlist.append(5) + chksum = sum(numlist) + # Error in checksum + #numlist[0] = 5 + nums = "".join( [str(n) for n in numlist] ) + data = "^%d:%d:%d:%s$" % (self.send_cnt, length, chksum, nums) + self.send_cnt += 1 + + return data + + + def check(self, frames): + + err = "" + for data in frames: + if data.count('$') > 1: + raise Exception("Multiple parts within single packet") + if len(data) == 0: + self.traffic("_") + continue + + if data[0] != "^": + err += "buf did not start with '^'\n" + continue + + try: + cnt, length, chksum, nums = data[1:-1].split(':') + cnt = int(cnt) + length = int(length) + chksum = int(chksum) + except: + print "\n<BOF>" + repr(data) + "<EOF>" + err += "Invalid data format\n" + continue + + if self.recv_cnt != cnt: + err += "Expected count %d but got %d\n" % (self.recv_cnt, cnt) + self.recv_cnt = cnt + 1 + continue + + self.recv_cnt += 1 + + if len(nums) != length: + err += "Expected length %d but got %d\n" % (length, len(nums)) + continue + + inv = nums.translate(None, "0123456789") + if inv: + err += "Invalid characters found: %s\n" % inv + continue + + real_chksum = 0 + for num in nums: + real_chksum += int(num) + + if real_chksum != chksum: + err += "Expected checksum %d but real chksum is %d\n" % (chksum, real_chksum) + return err + + +if __name__ == '__main__': + parser = optparse.OptionParser(usage="%prog [options] listen_port") + parser.add_option("--verbose", "-v", action="store_true", + help="verbose messages and per frame traffic") + parser.add_option("--cert", default="self.pem", + help="SSL certificate file") + parser.add_option("--key", default=None, + help="SSL key file (if separate from cert)") + parser.add_option("--ssl-only", action="store_true", + help="disallow non-encrypted connections") + (opts, args) = parser.parse_args() + + try: + if len(args) != 1: raise + opts.listen_port = int(args[0]) + + if len(args) not in [1,2]: raise + opts.listen_port = int(args[0]) + if len(args) == 2: + opts.delay = int(args[1]) + else: + opts.delay = 10 + except: + parser.error("Invalid arguments") + + opts.web = "." + server = WebSocketLoad(**opts.__dict__) + server.start_server() + diff --git a/third_party/websockify/tests/plain_echo.html b/third_party/websockify/tests/plain_echo.html new file mode 100644 index 00000000..12926fb9 --- /dev/null +++ b/third_party/websockify/tests/plain_echo.html @@ -0,0 +1,168 @@ +<html> + + <head> + <title>WebSockets Echo Test</title> + <script src="include/util.js"></script> + <script src="include/webutil.js"></script> + <!-- Uncomment to activate firebug lite --> + <!-- + <script type='text/javascript' + src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script> + --> + + + </head> + + <body> + + Host: <input id='host' style='width:100'> + Port: <input id='port' style='width:50'> + Encrypt: <input id='encrypt' type='checkbox'> + <input id='connectButton' type='button' value='Start' style='width:100px' + onclick="connect();"> + + + <br> + Log:<br> + <textarea id="messages" style="font-size: 9;" cols=80 rows=25></textarea> + </body> + + + <script> + var ws, host = null, port = null, + msg_cnt = 0, send_cnt = 1, echoDelay = 500, + echo_ref; + + function message(str) { + console.log(str); + cell = $D('messages'); + cell.innerHTML += msg_cnt + ": " + str + "\n"; + cell.scrollTop = cell.scrollHeight; + msg_cnt++; + } + + Array.prototype.pushStr = function (str) { + var n = str.length; + for (var i=0; i < n; i++) { + this.push(str.charCodeAt(i)); + } + } + + function send_msg() { + if (ws.bufferedAmount > 0) { + console.log("Delaying send"); + return; + } + var str = "Message #" + send_cnt, arr = []; + ws.send(str); + message("Sent message: '" + str + "'"); + send_cnt++; + } + + function update_stats() { + $D('sent').innerHTML = sent; + $D('received').innerHTML = received; + $D('errors').innerHTML = errors; + } + + function init_ws() { + console.log(">> init_ws"); + console.log("<< init_ws"); + } + + function connect() { + var host = $D('host').value, + port = $D('port').value, + scheme = "ws://", uri; + + console.log(">> connect"); + if ((!host) || (!port)) { + console.log("must set host and port"); + return; + } + + if (ws) { + ws.close(); + } + + if ($D('encrypt').checked) { + scheme = "wss://"; + } + uri = scheme + host + ":" + port; + message("connecting to " + uri); + ws = new WebSocket(uri, "base64"); + + ws.onmessage = function(e) { + //console.log(">> WebSockets.onmessage"); + message("Received message '" + e.data + "'"); + //console.log("<< WebSockets.onmessage"); + }; + ws.onopen = function(e) { + console.log(">> WebSockets.onopen"); + echo_ref = setInterval(send_msg, echoDelay); + console.log("<< WebSockets.onopen"); + }; + ws.onclose = function(e) { + console.log(">> WebSockets.onclose"); + if (echo_ref) { + clearInterval(echo_ref); + echo_ref = null; + } + console.log("<< WebSockets.onclose"); + }; + ws.onerror = function(e) { + console.log(">> WebSockets.onerror"); + if (echo_ref) { + clearInterval(echo_ref); + echo_ref = null; + } + console.log("<< WebSockets.onerror"); + }; + + $D('connectButton').value = "Stop"; + $D('connectButton').onclick = disconnect; + console.log("<< connect"); + } + + function disconnect() { + console.log(">> disconnect"); + if (ws) { + ws.close(); + } + + if (echo_ref) { + clearInterval(echo_ref); + } + + $D('connectButton').value = "Start"; + $D('connectButton').onclick = connect; + console.log("<< disconnect"); + } + + + /* If no builtin websockets then load web_socket.js */ + if (window.WebSocket) { + VNC_native_ws = true; + } else { + VNC_native_ws = false; + console.log("Loading web-socket-js flash bridge"); + var extra = "<script src='include/web-socket-js/swfobject.js'><\/script>"; + extra += "<script src='include/web-socket-js/FABridge.js'><\/script>"; + extra += "<script src='include/web-socket-js/web_socket.js'><\/script>"; + document.write(extra); + } + + window.onload = function() { + console.log("onload"); + if (!VNC_native_ws) { + console.log("initializing web-socket-js flash bridge"); + WebSocket.__swfLocation = "include/web-socket-js/WebSocketMain.swf"; + WebSocket.__initialize(); + } + var url = document.location.href; + $D('host').value = (url.match(/host=([^&#]*)/) || ['',''])[1]; + $D('port').value = (url.match(/port=([^&#]*)/) || ['',''])[1]; + } + </script> + +</html> diff --git a/third_party/websockify/tests/simple.html b/third_party/websockify/tests/simple.html new file mode 100644 index 00000000..18fb2004 --- /dev/null +++ b/third_party/websockify/tests/simple.html @@ -0,0 +1,68 @@ +<html> + + <head> + <title>Websock Simple Client</title> + <script src="include/util.js"></script> + <script src="include/base64.js"></script> + <script src="include/websock.js"></script> + </head> + + <body> + WebSocket/websockify URI: <input id='target'> + <input id='connectButton' type='button' value='Connect' + onclick="connect();"> + <br> <br> + <input id='sendText'> + <input id='sendButton' type='button' value='Send' disabled + onclick="send();"> + <br> <br> + Log:<br><textarea id="messages" cols=80 rows=25></textarea> + </body> + + + <script> + var $D = function(id) { return document.getElementById(id); }, + ws = null, msgs = $D('messages'); + + function msg(str) { + msgs.innerHTML += str + "\n"; + msgs.scrollTop = msgs.scrollHeight; + } + + function connect() { + var uri = $D('target').value; + ws = new Websock() + msg("connecting to: " + uri); + ws.open(uri); + ws.on('open', function () { + msg("Connected"); + }); + ws.on('message', function () { + msg("Received: " + ws.rQshiftStr()); + }); + ws.on('close', function () { + disconnect(); + msg("Disconnected"); + }); + + $D('connectButton').value = "Disconnect"; + $D('connectButton').onclick = disconnect; + $D('sendButton').disabled = false; + } + + function disconnect() { + if (ws) { ws.close(); } + ws = null; + + $D('connectButton').value = "Connect"; + $D('connectButton').onclick = connect; + $D('sendButton').disabled = true; + } + + function send() { + msg("Sending: " + $D('sendText').value); + ws.send_string($D('sendText').value); + }; + </script> + +</html> diff --git a/third_party/websockify/tests/utf8-list.py b/third_party/websockify/tests/utf8-list.py new file mode 100755 index 00000000..5a36da09 --- /dev/null +++ b/third_party/websockify/tests/utf8-list.py @@ -0,0 +1,22 @@ +#!/usr/bin/python + +''' +Display UTF-8 encoding for 0-255.''' + +import sys, os, socket, ssl, time, traceback +from select import select + +sys.path.insert(0,os.path.dirname(__file__) + "/../") +from websocket import WebSocketServer + +if __name__ == '__main__': + print "val: hixie | hybi_base64 | hybi_binary" + for c in range(0, 256): + hixie = WebSocketServer.encode_hixie(chr(c)) + hybi_base64 = WebSocketServer.encode_hybi(chr(c), opcode=1, + base64=True) + hybi_binary = WebSocketServer.encode_hybi(chr(c), opcode=2, + base64=False) + print "%d: %s | %s | %s" % (c, repr(hixie), repr(hybi_base64), + repr(hybi_binary)) + diff --git a/third_party/websockify/websockify.py b/third_party/websockify/websockify.py new file mode 120000 index 00000000..e5224d53 --- /dev/null +++ b/third_party/websockify/websockify.py @@ -0,0 +1 @@ +run
\ No newline at end of file diff --git a/third_party/websockify/websockify/__init__.py b/third_party/websockify/websockify/__init__.py new file mode 100644 index 00000000..e8f2eaf3 --- /dev/null +++ b/third_party/websockify/websockify/__init__.py @@ -0,0 +1,2 @@ +from websocket import * +from websocketproxy import * diff --git a/third_party/websockify/websockify/websocket.py b/third_party/websockify/websockify/websocket.py new file mode 100644 index 00000000..4c0cacc9 --- /dev/null +++ b/third_party/websockify/websockify/websocket.py @@ -0,0 +1,965 @@ +#!/usr/bin/env python + +''' +Python WebSocket library with support for "wss://" encryption. +Copyright 2011 Joel Martin +Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) + +Supports following protocol versions: + - http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75 + - http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 + - http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10 + +You can make a cert/key with openssl using: +openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem +as taken from http://docs.python.org/dev/library/ssl.html#certificates + +''' + +import os, sys, time, errno, signal, socket, traceback, select +import array, struct +from base64 import b64encode, b64decode + +# Imports that vary by python version + +# python 3.0 differences +if sys.hexversion > 0x3000000: + b2s = lambda buf: buf.decode('latin_1') + s2b = lambda s: s.encode('latin_1') + s2a = lambda s: s +else: + b2s = lambda buf: buf # No-op + s2b = lambda s: s # No-op + s2a = lambda s: [ord(c) for c in s] +try: from io import StringIO +except: from cStringIO import StringIO +try: from http.server import SimpleHTTPRequestHandler +except: from SimpleHTTPServer import SimpleHTTPRequestHandler + +# python 2.6 differences +try: from hashlib import md5, sha1 +except: from md5 import md5; from sha import sha as sha1 + +# python 2.5 differences +try: + from struct import pack, unpack_from +except: + from struct import pack + def unpack_from(fmt, buf, offset=0): + slice = buffer(buf, offset, struct.calcsize(fmt)) + return struct.unpack(fmt, slice) + +# Degraded functionality if these imports are missing +for mod, sup in [('numpy', 'HyBi protocol'), ('ssl', 'TLS/SSL/wss'), + ('multiprocessing', 'Multi-Processing'), + ('resource', 'daemonizing')]: + try: + globals()[mod] = __import__(mod) + except ImportError: + globals()[mod] = None + print("WARNING: no '%s' module, %s is slower or disabled" % ( + mod, sup)) +if multiprocessing and sys.platform == 'win32': + # make sockets pickle-able/inheritable + import multiprocessing.reduction + + +class WebSocketServer(object): + """ + WebSockets server class. + Must be sub-classed with new_client method definition. + """ + + buffer_size = 65536 + + + server_handshake_hixie = """HTTP/1.1 101 Web Socket Protocol Handshake\r +Upgrade: WebSocket\r +Connection: Upgrade\r +%sWebSocket-Origin: %s\r +%sWebSocket-Location: %s://%s%s\r +""" + + server_handshake_hybi = """HTTP/1.1 101 Switching Protocols\r +Upgrade: websocket\r +Connection: Upgrade\r +Sec-WebSocket-Accept: %s\r +""" + + GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + + policy_response = """<cross-domain-policy><allow-access-from domain="*" to-ports="*" /></cross-domain-policy>\n""" + + # An exception before the WebSocket connection was established + class EClose(Exception): + pass + + # An exception while the WebSocket client was connected + class CClose(Exception): + pass + + def __init__(self, listen_host='', listen_port=None, source_is_ipv6=False, + verbose=False, cert='', key='', ssl_only=None, + daemon=False, record='', web='', + run_once=False, timeout=0, idle_timeout=0): + + # settings + self.verbose = verbose + self.listen_host = listen_host + self.listen_port = listen_port + self.prefer_ipv6 = source_is_ipv6 + self.ssl_only = ssl_only + self.daemon = daemon + self.run_once = run_once + self.timeout = timeout + self.idle_timeout = idle_timeout + + self.launch_time = time.time() + self.ws_connection = False + self.handler_id = 1 + + # Make paths settings absolute + self.cert = os.path.abspath(cert) + self.key = self.web = self.record = '' + if key: + self.key = os.path.abspath(key) + if web: + self.web = os.path.abspath(web) + if record: + self.record = os.path.abspath(record) + + if self.web: + os.chdir(self.web) + + # Sanity checks + if not ssl and self.ssl_only: + raise Exception("No 'ssl' module and SSL-only specified") + if self.daemon and not resource: + raise Exception("Module 'resource' required to daemonize") + + # Show configuration + print("WebSocket server settings:") + print(" - Listen on %s:%s" % ( + self.listen_host, self.listen_port)) + print(" - Flash security policy server") + if self.web: + print(" - Web server. Web root: %s" % self.web) + if ssl: + if os.path.exists(self.cert): + print(" - SSL/TLS support") + if self.ssl_only: + print(" - Deny non-SSL/TLS connections") + else: + print(" - No SSL/TLS support (no cert file)") + else: + print(" - No SSL/TLS support (no 'ssl' module)") + if self.daemon: + print(" - Backgrounding (daemon)") + if self.record: + print(" - Recording to '%s.*'" % self.record) + + # + # WebSocketServer static methods + # + + @staticmethod + def socket(host, port=None, connect=False, prefer_ipv6=False, unix_socket=None, use_ssl=False): + """ Resolve a host (and optional port) to an IPv4 or IPv6 + address. Create a socket. Bind to it if listen is set, + otherwise connect to it. Return the socket. + """ + flags = 0 + if host == '': + host = None + if connect and not (port or unix_socket): + raise Exception("Connect mode requires a port") + if use_ssl and not ssl: + raise Exception("SSL socket requested but Python SSL module not loaded."); + if not connect and use_ssl: + raise Exception("SSL only supported in connect mode (for now)") + if not connect: + flags = flags | socket.AI_PASSIVE + + if not unix_socket: + addrs = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM, + socket.IPPROTO_TCP, flags) + if not addrs: + raise Exception("Could not resolve host '%s'" % host) + addrs.sort(key=lambda x: x[0]) + if prefer_ipv6: + addrs.reverse() + sock = socket.socket(addrs[0][0], addrs[0][1]) + if connect: + sock.connect(addrs[0][4]) + if use_ssl: + sock = ssl.wrap_socket(sock) + else: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.bind(addrs[0][4]) + sock.listen(100) + else: + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.connect(unix_socket) + + return sock + + @staticmethod + def daemonize(keepfd=None, chdir='/'): + os.umask(0) + if chdir: + os.chdir(chdir) + else: + os.chdir('/') + os.setgid(os.getgid()) # relinquish elevations + os.setuid(os.getuid()) # relinquish elevations + + # Double fork to daemonize + if os.fork() > 0: os._exit(0) # Parent exits + os.setsid() # Obtain new process group + if os.fork() > 0: os._exit(0) # Parent exits + + # Signal handling + def terminate(a,b): os._exit(0) + signal.signal(signal.SIGTERM, terminate) + signal.signal(signal.SIGINT, signal.SIG_IGN) + + # Close open files + maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1] + if maxfd == resource.RLIM_INFINITY: maxfd = 256 + for fd in reversed(range(maxfd)): + try: + if fd != keepfd: + os.close(fd) + except OSError: + _, exc, _ = sys.exc_info() + if exc.errno != errno.EBADF: raise + + # Redirect I/O to /dev/null + os.dup2(os.open(os.devnull, os.O_RDWR), sys.stdin.fileno()) + os.dup2(os.open(os.devnull, os.O_RDWR), sys.stdout.fileno()) + os.dup2(os.open(os.devnull, os.O_RDWR), sys.stderr.fileno()) + + @staticmethod + def unmask(buf, f): + pstart = f['hlen'] + 4 + pend = pstart + f['length'] + if numpy: + b = c = s2b('') + if f['length'] >= 4: + mask = numpy.frombuffer(buf, dtype=numpy.dtype('<u4'), + offset=f['hlen'], count=1) + data = numpy.frombuffer(buf, dtype=numpy.dtype('<u4'), + offset=pstart, count=int(f['length'] / 4)) + #b = numpy.bitwise_xor(data, mask).data + b = numpy.bitwise_xor(data, mask).tostring() + + if f['length'] % 4: + #print("Partial unmask") + mask = numpy.frombuffer(buf, dtype=numpy.dtype('B'), + offset=f['hlen'], count=(f['length'] % 4)) + data = numpy.frombuffer(buf, dtype=numpy.dtype('B'), + offset=pend - (f['length'] % 4), + count=(f['length'] % 4)) + c = numpy.bitwise_xor(data, mask).tostring() + return b + c + else: + # Slower fallback + data = array.array('B') + mask = s2a(f['mask']) + data.fromstring(buf[pstart:pend]) + for i in range(len(data)): + data[i] ^= mask[i % 4] + return data.tostring() + + @staticmethod + def encode_hybi(buf, opcode, base64=False): + """ Encode a HyBi style WebSocket frame. + Optional opcode: + 0x0 - continuation + 0x1 - text frame (base64 encode buf) + 0x2 - binary frame (use raw buf) + 0x8 - connection close + 0x9 - ping + 0xA - pong + """ + if base64: + buf = b64encode(buf) + + b1 = 0x80 | (opcode & 0x0f) # FIN + opcode + payload_len = len(buf) + if payload_len <= 125: + header = pack('>BB', b1, payload_len) + elif payload_len > 125 and payload_len < 65536: + header = pack('>BBH', b1, 126, payload_len) + elif payload_len >= 65536: + header = pack('>BBQ', b1, 127, payload_len) + + #print("Encoded: %s" % repr(header + buf)) + + return header + buf, len(header), 0 + + @staticmethod + def decode_hybi(buf, base64=False): + """ Decode HyBi style WebSocket packets. + Returns: + {'fin' : 0_or_1, + 'opcode' : number, + 'mask' : 32_bit_number, + 'hlen' : header_bytes_number, + 'length' : payload_bytes_number, + 'payload' : decoded_buffer, + 'left' : bytes_left_number, + 'close_code' : number, + 'close_reason' : string} + """ + + f = {'fin' : 0, + 'opcode' : 0, + 'mask' : 0, + 'hlen' : 2, + 'length' : 0, + 'payload' : None, + 'left' : 0, + 'close_code' : 1000, + 'close_reason' : ''} + + blen = len(buf) + f['left'] = blen + + if blen < f['hlen']: + return f # Incomplete frame header + + b1, b2 = unpack_from(">BB", buf) + f['opcode'] = b1 & 0x0f + f['fin'] = (b1 & 0x80) >> 7 + has_mask = (b2 & 0x80) >> 7 + + f['length'] = b2 & 0x7f + + if f['length'] == 126: + f['hlen'] = 4 + if blen < f['hlen']: + return f # Incomplete frame header + (f['length'],) = unpack_from('>xxH', buf) + elif f['length'] == 127: + f['hlen'] = 10 + if blen < f['hlen']: + return f # Incomplete frame header + (f['length'],) = unpack_from('>xxQ', buf) + + full_len = f['hlen'] + has_mask * 4 + f['length'] + + if blen < full_len: # Incomplete frame + return f # Incomplete frame header + + # Number of bytes that are part of the next frame(s) + f['left'] = blen - full_len + + # Process 1 frame + if has_mask: + # unmask payload + f['mask'] = buf[f['hlen']:f['hlen']+4] + f['payload'] = WebSocketServer.unmask(buf, f) + else: + print("Unmasked frame: %s" % repr(buf)) + f['payload'] = buf[(f['hlen'] + has_mask * 4):full_len] + + if base64 and f['opcode'] in [1, 2]: + try: + f['payload'] = b64decode(f['payload']) + except: + print("Exception while b64decoding buffer: %s" % + repr(buf)) + raise + + if f['opcode'] == 0x08: + if f['length'] >= 2: + f['close_code'] = unpack_from(">H", f['payload'])[0] + if f['length'] > 3: + f['close_reason'] = f['payload'][2:] + + return f + + @staticmethod + def encode_hixie(buf): + return s2b("\x00" + b2s(b64encode(buf)) + "\xff"), 1, 1 + + @staticmethod + def decode_hixie(buf): + end = buf.find(s2b('\xff')) + return {'payload': b64decode(buf[1:end]), + 'hlen': 1, + 'length': end - 1, + 'left': len(buf) - (end + 1)} + + + @staticmethod + def gen_md5(keys): + """ Generate hash value for WebSockets hixie-76. """ + key1 = keys['Sec-WebSocket-Key1'] + key2 = keys['Sec-WebSocket-Key2'] + key3 = keys['key3'] + spaces1 = key1.count(" ") + spaces2 = key2.count(" ") + num1 = int("".join([c for c in key1 if c.isdigit()])) / spaces1 + num2 = int("".join([c for c in key2 if c.isdigit()])) / spaces2 + + return b2s(md5(pack('>II8s', + int(num1), int(num2), key3)).digest()) + + # + # WebSocketServer logging/output functions + # + + def traffic(self, token="."): + """ Show traffic flow in verbose mode. """ + if self.verbose and not self.daemon: + sys.stdout.write(token) + sys.stdout.flush() + + def msg(self, msg): + """ Output message with handler_id prefix. """ + if not self.daemon: + print("% 3d: %s" % (self.handler_id, msg)) + + def vmsg(self, msg): + """ Same as msg() but only if verbose. """ + if self.verbose: + self.msg(msg) + + # + # Main WebSocketServer methods + # + def send_frames(self, bufs=None): + """ Encode and send WebSocket frames. Any frames already + queued will be sent first. If buf is not set then only queued + frames will be sent. Returns the number of pending frames that + could not be fully sent. If returned pending frames is greater + than 0, then the caller should call again when the socket is + ready. """ + + tdelta = int(time.time()*1000) - self.start_time + + if bufs: + for buf in bufs: + if self.version.startswith("hybi"): + if self.base64: + encbuf, lenhead, lentail = self.encode_hybi( + buf, opcode=1, base64=True) + else: + encbuf, lenhead, lentail = self.encode_hybi( + buf, opcode=2, base64=False) + + else: + encbuf, lenhead, lentail = self.encode_hixie(buf) + + if self.rec: + self.rec.write("%s,\n" % + repr("{%s{" % tdelta + + encbuf[lenhead:-lentail])) + + self.send_parts.append(encbuf) + + while self.send_parts: + # Send pending frames + buf = self.send_parts.pop(0) + sent = self.client.send(buf) + + if sent == len(buf): + self.traffic("<") + else: + self.traffic("<.") + self.send_parts.insert(0, buf[sent:]) + break + + return len(self.send_parts) + + def recv_frames(self): + """ Receive and decode WebSocket frames. + + Returns: + (bufs_list, closed_string) + """ + + closed = False + bufs = [] + tdelta = int(time.time()*1000) - self.start_time + + buf = self.client.recv(self.buffer_size) + if len(buf) == 0: + closed = {'code': 1000, 'reason': "Client closed abruptly"} + return bufs, closed + + if self.recv_part: + # Add partially received frames to current read buffer + buf = self.recv_part + buf + self.recv_part = None + + while buf: + if self.version.startswith("hybi"): + + frame = self.decode_hybi(buf, base64=self.base64) + #print("Received buf: %s, frame: %s" % (repr(buf), frame)) + + if frame['payload'] == None: + # Incomplete/partial frame + self.traffic("}.") + if frame['left'] > 0: + self.recv_part = buf[-frame['left']:] + break + else: + if frame['opcode'] == 0x8: # connection close + closed = {'code': frame['close_code'], + 'reason': frame['close_reason']} + break + + else: + if buf[0:2] == s2b('\xff\x00'): + closed = {'code': 1000, + 'reason': "Client sent orderly close frame"} + break + + elif buf[0:2] == s2b('\x00\xff'): + buf = buf[2:] + continue # No-op + + elif buf.count(s2b('\xff')) == 0: + # Partial frame + self.traffic("}.") + self.recv_part = buf + break + + frame = self.decode_hixie(buf) + + self.traffic("}") + + if self.rec: + start = frame['hlen'] + end = frame['hlen'] + frame['length'] + self.rec.write("%s,\n" % + repr("}%s}" % tdelta + buf[start:end])) + + + bufs.append(frame['payload']) + + if frame['left']: + buf = buf[-frame['left']:] + else: + buf = '' + + return bufs, closed + + def send_close(self, code=1000, reason=''): + """ Send a WebSocket orderly close frame. """ + + if self.version.startswith("hybi"): + msg = pack(">H%ds" % len(reason), code, reason) + + buf, h, t = self.encode_hybi(msg, opcode=0x08, base64=False) + self.client.send(buf) + + elif self.version == "hixie-76": + buf = s2b('\xff\x00') + self.client.send(buf) + + # No orderly close for 75 + + def do_websocket_handshake(self, headers, path): + h = self.headers = headers + self.path = path + + prot = 'WebSocket-Protocol' + protocols = h.get('Sec-'+prot, h.get(prot, '')).split(',') + + ver = h.get('Sec-WebSocket-Version') + if ver: + # HyBi/IETF version of the protocol + + # HyBi-07 report version 7 + # HyBi-08 - HyBi-12 report version 8 + # HyBi-13 reports version 13 + if ver in ['7', '8', '13']: + self.version = "hybi-%02d" % int(ver) + else: + raise self.EClose('Unsupported protocol version %s' % ver) + + key = h['Sec-WebSocket-Key'] + + # Choose binary if client supports it + if 'binary' in protocols: + self.base64 = False + elif 'base64' in protocols: + self.base64 = True + else: + raise self.EClose("Client must support 'binary' or 'base64' protocol") + + # Generate the hash value for the accept header + accept = b64encode(sha1(s2b(key + self.GUID)).digest()) + + response = self.server_handshake_hybi % b2s(accept) + if self.base64: + response += "Sec-WebSocket-Protocol: base64\r\n" + else: + response += "Sec-WebSocket-Protocol: binary\r\n" + response += "\r\n" + + else: + # Hixie version of the protocol (75 or 76) + + if h.get('key3'): + trailer = self.gen_md5(h) + pre = "Sec-" + self.version = "hixie-76" + else: + trailer = "" + pre = "" + self.version = "hixie-75" + + # We only support base64 in Hixie era + self.base64 = True + + response = self.server_handshake_hixie % (pre, + h['Origin'], pre, self.scheme, h['Host'], path) + + if 'base64' in protocols: + response += "%sWebSocket-Protocol: base64\r\n" % pre + else: + self.msg("Warning: client does not report 'base64' protocol support") + response += "\r\n" + trailer + + return response + + + def do_handshake(self, sock, address): + """ + do_handshake does the following: + - Peek at the first few bytes from the socket. + - If the connection is Flash policy request then answer it, + close the socket and return. + - If the connection is an HTTPS/SSL/TLS connection then SSL + wrap the socket. + - Read from the (possibly wrapped) socket. + - If we have received a HTTP GET request and the webserver + functionality is enabled, answer it, close the socket and + return. + - Assume we have a WebSockets connection, parse the client + handshake data. + - Send a WebSockets handshake server response. + - Return the socket for this WebSocket client. + """ + stype = "" + ready = select.select([sock], [], [], 3)[0] + + + if not ready: + raise self.EClose("ignoring socket not ready") + # Peek, but do not read the data so that we have a opportunity + # to SSL wrap the socket first + handshake = sock.recv(1024, socket.MSG_PEEK) + #self.msg("Handshake [%s]" % handshake) + + if handshake == "": + raise self.EClose("ignoring empty handshake") + + elif handshake.startswith(s2b("<policy-file-request/>")): + # Answer Flash policy request + handshake = sock.recv(1024) + sock.send(s2b(self.policy_response)) + raise self.EClose("Sending flash policy response") + + elif handshake[0] in ("\x16", "\x80", 22, 128): + # SSL wrap the connection + if not ssl: + raise self.EClose("SSL connection but no 'ssl' module") + if not os.path.exists(self.cert): + raise self.EClose("SSL connection but '%s' not found" + % self.cert) + retsock = None + try: + retsock = ssl.wrap_socket( + sock, + server_side=True, + certfile=self.cert, + keyfile=self.key) + except ssl.SSLError: + _, x, _ = sys.exc_info() + if x.args[0] == ssl.SSL_ERROR_EOF: + if len(x.args) > 1: + raise self.EClose(x.args[1]) + else: + raise self.EClose("Got SSL_ERROR_EOF") + else: + raise + + self.scheme = "wss" + stype = "SSL/TLS (wss://)" + + elif self.ssl_only: + raise self.EClose("non-SSL connection received but disallowed") + + else: + retsock = sock + self.scheme = "ws" + stype = "Plain non-SSL (ws://)" + + wsh = WSRequestHandler(retsock, address, not self.web) + if wsh.last_code == 101: + # Continue on to handle WebSocket upgrade + pass + elif wsh.last_code == 405: + raise self.EClose("Normal web request received but disallowed") + elif wsh.last_code < 200 or wsh.last_code >= 300: + raise self.EClose(wsh.last_message) + elif self.verbose: + raise self.EClose(wsh.last_message) + else: + raise self.EClose("") + + response = self.do_websocket_handshake(wsh.headers, wsh.path) + + self.msg("%s: %s WebSocket connection" % (address[0], stype)) + self.msg("%s: Version %s, base64: '%s'" % (address[0], + self.version, self.base64)) + if self.path != '/': + self.msg("%s: Path: '%s'" % (address[0], self.path)) + + + # Send server WebSockets handshake response + #self.msg("sending response [%s]" % response) + retsock.send(s2b(response)) + + # Return the WebSockets socket which may be SSL wrapped + return retsock + + + # + # Events that can/should be overridden in sub-classes + # + def started(self): + """ Called after WebSockets startup """ + self.vmsg("WebSockets server started") + + def poll(self): + """ Run periodically while waiting for connections. """ + #self.vmsg("Running poll()") + pass + + def fallback_SIGCHLD(self, sig, stack): + # Reap zombies when using os.fork() (python 2.4) + self.vmsg("Got SIGCHLD, reaping zombies") + try: + result = os.waitpid(-1, os.WNOHANG) + while result[0]: + self.vmsg("Reaped child process %s" % result[0]) + result = os.waitpid(-1, os.WNOHANG) + except (OSError): + pass + + def do_SIGINT(self, sig, stack): + self.msg("Got SIGINT, exiting") + sys.exit(0) + + def top_new_client(self, startsock, address): + """ Do something with a WebSockets client connection. """ + # Initialize per client settings + self.send_parts = [] + self.recv_part = None + self.base64 = False + self.rec = None + self.start_time = int(time.time()*1000) + + # handler process + try: + try: + self.client = self.do_handshake(startsock, address) + + if self.record: + # Record raw frame data as JavaScript array + fname = "%s.%s" % (self.record, + self.handler_id) + self.msg("opening record file: %s" % fname) + self.rec = open(fname, 'w+') + self.rec.write("var VNC_frame_data = [\n") + + self.ws_connection = True + self.new_client() + except self.CClose: + # Close the client + _, exc, _ = sys.exc_info() + if self.client: + self.send_close(exc.args[0], exc.args[1]) + except self.EClose: + _, exc, _ = sys.exc_info() + # Connection was not a WebSockets connection + if exc.args[0]: + self.msg("%s: %s" % (address[0], exc.args[0])) + except Exception: + _, exc, _ = sys.exc_info() + self.msg("handler exception: %s" % str(exc)) + if self.verbose: + self.msg(traceback.format_exc()) + finally: + if self.rec: + self.rec.write("'EOF']\n") + self.rec.close() + + if self.client and self.client != startsock: + # Close the SSL wrapped socket + # Original socket closed by caller + self.client.close() + + def new_client(self): + """ Do something with a WebSockets client connection. """ + raise("WebSocketServer.new_client() must be overloaded") + + def start_server(self): + """ + Daemonize if requested. Listen for for connections. Run + do_handshake() method for each connection. If the connection + is a WebSockets client then call new_client() method (which must + be overridden) for each new client connection. + """ + lsock = self.socket(self.listen_host, self.listen_port, False, self.prefer_ipv6) + + if self.daemon: + self.daemonize(keepfd=lsock.fileno(), chdir=self.web) + + self.started() # Some things need to happen after daemonizing + + # Allow override of SIGINT + signal.signal(signal.SIGINT, self.do_SIGINT) + if not multiprocessing: + # os.fork() (python 2.4) child reaper + signal.signal(signal.SIGCHLD, self.fallback_SIGCHLD) + + last_active_time = self.launch_time + while True: + try: + try: + self.client = None + startsock = None + pid = err = 0 + child_count = 0 + + if multiprocessing and self.idle_timeout: + child_count = len(multiprocessing.active_children()) + + time_elapsed = time.time() - self.launch_time + if self.timeout and time_elapsed > self.timeout: + self.msg('listener exit due to --timeout %s' + % self.timeout) + break + + if self.idle_timeout: + idle_time = 0 + if child_count == 0: + idle_time = time.time() - last_active_time + else: + idle_time = 0 + last_active_time = time.time() + + if idle_time > self.idle_timeout and child_count == 0: + self.msg('listener exit due to --idle-timeout %s' + % self.idle_timeout) + break + + try: + self.poll() + + ready = select.select([lsock], [], [], 1)[0] + if lsock in ready: + startsock, address = lsock.accept() + else: + continue + except Exception: + _, exc, _ = sys.exc_info() + if hasattr(exc, 'errno'): + err = exc.errno + elif hasattr(exc, 'args'): + err = exc.args[0] + else: + err = exc[0] + if err == errno.EINTR: + self.vmsg("Ignoring interrupted syscall") + continue + else: + raise + + if self.run_once: + # Run in same process if run_once + self.top_new_client(startsock, address) + if self.ws_connection : + self.msg('%s: exiting due to --run-once' + % address[0]) + break + elif multiprocessing: + self.vmsg('%s: new handler Process' % address[0]) + p = multiprocessing.Process( + target=self.top_new_client, + args=(startsock, address)) + p.start() + # child will not return + else: + # python 2.4 + self.vmsg('%s: forking handler' % address[0]) + pid = os.fork() + if pid == 0: + # child handler process + self.top_new_client(startsock, address) + break # child process exits + + # parent process + self.handler_id += 1 + + except KeyboardInterrupt: + _, exc, _ = sys.exc_info() + print("In KeyboardInterrupt") + pass + except SystemExit: + _, exc, _ = sys.exc_info() + print("In SystemExit") + break + except Exception: + _, exc, _ = sys.exc_info() + self.msg("handler exception: %s" % str(exc)) + if self.verbose: + self.msg(traceback.format_exc()) + + finally: + if startsock: + startsock.close() + + +# HTTP handler with WebSocket upgrade support +class WSRequestHandler(SimpleHTTPRequestHandler): + def __init__(self, req, addr, only_upgrade=False): + self.only_upgrade = only_upgrade # only allow upgrades + SimpleHTTPRequestHandler.__init__(self, req, addr, object()) + + def do_GET(self): + if (self.headers.get('upgrade') and + self.headers.get('upgrade').lower() == 'websocket'): + + if (self.headers.get('sec-websocket-key1') or + self.headers.get('websocket-key1')): + # For Hixie-76 read out the key hash + self.headers.__setitem__('key3', self.rfile.read(8)) + + # Just indicate that an WebSocket upgrade is needed + self.last_code = 101 + self.last_message = "101 Switching Protocols" + elif self.only_upgrade: + # Normal web request responses are disabled + self.last_code = 405 + self.last_message = "405 Method Not Allowed" + else: + SimpleHTTPRequestHandler.do_GET(self) + + def send_response(self, code, message=None): + # Save the status code + self.last_code = code + SimpleHTTPRequestHandler.send_response(self, code, message) + + def log_message(self, f, *args): + # Save instead of printing + self.last_message = f % args diff --git a/third_party/websockify/websockify/websocketproxy.py b/third_party/websockify/websockify/websocketproxy.py new file mode 100755 index 00000000..8bd67ec4 --- /dev/null +++ b/third_party/websockify/websockify/websocketproxy.py @@ -0,0 +1,390 @@ +#!/usr/bin/env python + +''' +A WebSocket to TCP socket proxy with support for "wss://" encryption. +Copyright 2011 Joel Martin +Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) + +You can make a cert/key with openssl using: +openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem +as taken from http://docs.python.org/dev/library/ssl.html#certificates + +''' + +import signal, socket, optparse, time, os, sys, subprocess +from select import select +import websocket +try: from urllib.parse import parse_qs, urlparse +except: from urlparse import parse_qs, urlparse + +class WebSocketProxy(websocket.WebSocketServer): + """ + Proxy traffic to and from a WebSockets client to a normal TCP + socket server target. All traffic to/from the client is base64 + encoded/decoded to allow binary data to be sent/received to/from + the target. + """ + + buffer_size = 65536 + + traffic_legend = """ +Traffic Legend: + } - Client receive + }. - Client receive partial + { - Target receive + + > - Target send + >. - Target send partial + < - Client send + <. - Client send partial +""" + + def __init__(self, *args, **kwargs): + # Save off proxy specific options + self.target_host = kwargs.pop('target_host', None) + self.target_port = kwargs.pop('target_port', None) + self.wrap_cmd = kwargs.pop('wrap_cmd', None) + self.wrap_mode = kwargs.pop('wrap_mode', None) + self.unix_target = kwargs.pop('unix_target', None) + self.ssl_target = kwargs.pop('ssl_target', None) + self.target_cfg = kwargs.pop('target_cfg', None) + # Last 3 timestamps command was run + self.wrap_times = [0, 0, 0] + + if self.wrap_cmd: + rebinder_path = ['./', os.path.dirname(sys.argv[0])] + self.rebinder = None + + for rdir in rebinder_path: + rpath = os.path.join(rdir, "rebind.so") + if os.path.exists(rpath): + self.rebinder = rpath + break + + if not self.rebinder: + raise Exception("rebind.so not found, perhaps you need to run make") + self.rebinder = os.path.abspath(self.rebinder) + + self.target_host = "127.0.0.1" # Loopback + # Find a free high port + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.bind(('', 0)) + self.target_port = sock.getsockname()[1] + sock.close() + + os.environ.update({ + "LD_PRELOAD": self.rebinder, + "REBIND_OLD_PORT": str(kwargs['listen_port']), + "REBIND_NEW_PORT": str(self.target_port)}) + + if self.target_cfg: + self.target_cfg = os.path.abspath(self.target_cfg) + + websocket.WebSocketServer.__init__(self, *args, **kwargs) + + def run_wrap_cmd(self): + print("Starting '%s'" % " ".join(self.wrap_cmd)) + self.wrap_times.append(time.time()) + self.wrap_times.pop(0) + self.cmd = subprocess.Popen( + self.wrap_cmd, env=os.environ, preexec_fn=_subprocess_setup) + self.spawn_message = True + + def started(self): + """ + Called after Websockets server startup (i.e. after daemonize) + """ + # Need to call wrapped command after daemonization so we can + # know when the wrapped command exits + if self.wrap_cmd: + dst_string = "'%s' (port %s)" % (" ".join(self.wrap_cmd), self.target_port) + elif self.unix_target: + dst_string = self.unix_target + else: + dst_string = "%s:%s" % (self.target_host, self.target_port) + + if self.target_cfg: + msg = " - proxying from %s:%s to targets in %s" % ( + self.listen_host, self.listen_port, self.target_cfg) + else: + msg = " - proxying from %s:%s to %s" % ( + self.listen_host, self.listen_port, dst_string) + + if self.ssl_target: + msg += " (using SSL)" + + print(msg + "\n") + + if self.wrap_cmd: + self.run_wrap_cmd() + + def poll(self): + # If we are wrapping a command, check it's status + + if self.wrap_cmd and self.cmd: + ret = self.cmd.poll() + if ret != None: + self.vmsg("Wrapped command exited (or daemon). Returned %s" % ret) + self.cmd = None + + if self.wrap_cmd and self.cmd == None: + # Response to wrapped command being gone + if self.wrap_mode == "ignore": + pass + elif self.wrap_mode == "exit": + sys.exit(ret) + elif self.wrap_mode == "respawn": + now = time.time() + avg = sum(self.wrap_times)/len(self.wrap_times) + if (now - avg) < 10: + # 3 times in the last 10 seconds + if self.spawn_message: + print("Command respawning too fast") + self.spawn_message = False + else: + self.run_wrap_cmd() + + # + # Routines above this point are run in the master listener + # process. + # + + # + # Routines below this point are connection handler routines and + # will be run in a separate forked process for each connection. + # + + def new_client(self): + """ + Called after a new WebSocket connection has been established. + """ + # Checks if we receive a token, and look + # for a valid target for it then + if self.target_cfg: + (self.target_host, self.target_port) = self.get_target(self.target_cfg, self.path) + + # Connect to the target + if self.wrap_cmd: + msg = "connecting to command: '%s' (port %s)" % (" ".join(self.wrap_cmd), self.target_port) + elif self.unix_target: + msg = "connecting to unix socket: %s" % self.unix_target + else: + msg = "connecting to: %s:%s" % ( + self.target_host, self.target_port) + + if self.ssl_target: + msg += " (using SSL)" + self.msg(msg) + + tsock = self.socket(self.target_host, self.target_port, + connect=True, use_ssl=self.ssl_target, unix_socket=self.unix_target) + + if self.verbose and not self.daemon: + print(self.traffic_legend) + + # Start proxying + try: + self.do_proxy(tsock) + except: + if tsock: + tsock.shutdown(socket.SHUT_RDWR) + tsock.close() + self.vmsg("%s:%s: Closed target" %( + self.target_host, self.target_port)) + raise + + def get_target(self, target_cfg, path): + """ + Parses the path, extracts a token, and looks for a valid + target for that token in the configuration file(s). Sets + target_host and target_port if successful + """ + # The files in targets contain the lines + # in the form of token: host:port + + # Extract the token parameter from url + args = parse_qs(urlparse(path)[4]) # 4 is the query from url + + if not len(args['token']): + raise self.EClose("Token not present") + + token = args['token'][0].rstrip('\n') + + # target_cfg can be a single config file or directory of + # config files + if os.path.isdir(target_cfg): + cfg_files = [os.path.join(target_cfg, f) + for f in os.listdir(target_cfg)] + else: + cfg_files = [target_cfg] + + targets = {} + for f in cfg_files: + for line in [l.strip() for l in file(f).readlines()]: + if line and not line.startswith('#'): + ttoken, target = line.split(': ') + targets[ttoken] = target.strip() + + self.vmsg("Target config: %s" % repr(targets)) + + if targets.has_key(token): + return targets[token].split(':') + else: + raise self.EClose("Token '%s' not found" % token) + + def do_proxy(self, target): + """ + Proxy client WebSocket to normal target socket. + """ + cqueue = [] + c_pend = 0 + tqueue = [] + rlist = [self.client, target] + + while True: + wlist = [] + + if tqueue: wlist.append(target) + if cqueue or c_pend: wlist.append(self.client) + ins, outs, excepts = select(rlist, wlist, [], 1) + if excepts: raise Exception("Socket exception") + + if target in outs: + # Send queued client data to the target + dat = tqueue.pop(0) + sent = target.send(dat) + if sent == len(dat): + self.traffic(">") + else: + # requeue the remaining data + tqueue.insert(0, dat[sent:]) + self.traffic(".>") + + + if target in ins: + # Receive target data, encode it and queue for client + buf = target.recv(self.buffer_size) + if len(buf) == 0: + self.vmsg("%s:%s: Target closed connection" %( + self.target_host, self.target_port)) + raise self.CClose(1000, "Target closed") + + cqueue.append(buf) + self.traffic("{") + + + if self.client in outs: + # Send queued target data to the client + c_pend = self.send_frames(cqueue) + + cqueue = [] + + + if self.client in ins: + # Receive client data, decode it, and queue for target + bufs, closed = self.recv_frames() + tqueue.extend(bufs) + + if closed: + # TODO: What about blocking on client socket? + self.vmsg("%s:%s: Client closed connection" %( + self.target_host, self.target_port)) + raise self.CClose(closed['code'], closed['reason']) + + +def _subprocess_setup(): + # Python installs a SIGPIPE handler by default. This is usually not what + # non-Python successfulbprocesses expect. + signal.signal(signal.SIGPIPE, signal.SIG_DFL) + + +def websockify_init(): + usage = "\n %prog [options]" + usage += " [source_addr:]source_port [target_addr:target_port]" + usage += "\n %prog [options]" + usage += " [source_addr:]source_port -- WRAP_COMMAND_LINE" + parser = optparse.OptionParser(usage=usage) + parser.add_option("--verbose", "-v", action="store_true", + help="verbose messages and per frame traffic") + parser.add_option("--record", + help="record sessions to FILE.[session_number]", metavar="FILE") + parser.add_option("--daemon", "-D", + dest="daemon", action="store_true", + help="become a daemon (background process)") + parser.add_option("--run-once", action="store_true", + help="handle a single WebSocket connection and exit") + parser.add_option("--timeout", type=int, default=0, + help="after TIMEOUT seconds exit when not connected") + parser.add_option("--idle-timeout", type=int, default=0, + help="server exits after TIMEOUT seconds if there are no " + "active connections") + parser.add_option("--cert", default="self.pem", + help="SSL certificate file") + parser.add_option("--key", default=None, + help="SSL key file (if separate from cert)") + parser.add_option("--ssl-only", action="store_true", + help="disallow non-encrypted client connections") + parser.add_option("--ssl-target", action="store_true", + help="connect to SSL target as SSL client") + parser.add_option("--unix-target", + help="connect to unix socket target", metavar="FILE") + parser.add_option("--web", default=None, metavar="DIR", + help="run webserver on same port. Serve files from DIR.") + parser.add_option("--wrap-mode", default="exit", metavar="MODE", + choices=["exit", "ignore", "respawn"], + help="action to take when the wrapped program exits " + "or daemonizes: exit (default), ignore, respawn") + parser.add_option("--prefer-ipv6", "-6", + action="store_true", dest="source_is_ipv6", + help="prefer IPv6 when resolving source_addr") + parser.add_option("--target-config", metavar="FILE", + dest="target_cfg", + help="Configuration file containing valid targets " + "in the form 'token: host:port' or, alternatively, a " + "directory containing configuration files of this form") + (opts, args) = parser.parse_args() + + # Sanity checks + if len(args) < 2 and not (opts.target_cfg or opts.unix_target): + parser.error("Too few arguments") + if sys.argv.count('--'): + opts.wrap_cmd = args[1:] + else: + opts.wrap_cmd = None + if len(args) > 2: + parser.error("Too many arguments") + + if not websocket.ssl and opts.ssl_target: + parser.error("SSL target requested and Python SSL module not loaded."); + + if opts.ssl_only and not os.path.exists(opts.cert): + parser.error("SSL only and %s not found" % opts.cert) + + # Parse host:port and convert ports to numbers + if args[0].count(':') > 0: + opts.listen_host, opts.listen_port = args[0].rsplit(':', 1) + opts.listen_host = opts.listen_host.strip('[]') + else: + opts.listen_host, opts.listen_port = '', args[0] + + try: opts.listen_port = int(opts.listen_port) + except: parser.error("Error parsing listen port") + + if opts.wrap_cmd or opts.unix_target or opts.target_cfg: + opts.target_host = None + opts.target_port = None + else: + if args[1].count(':') > 0: + opts.target_host, opts.target_port = args[1].rsplit(':', 1) + opts.target_host = opts.target_host.strip('[]') + else: + parser.error("Error parsing target") + try: opts.target_port = int(opts.target_port) + except: parser.error("Error parsing target port") + + # Create and start the WebSockets proxy + server = WebSocketProxy(**opts.__dict__) + server.start_server() + +if __name__ == '__main__': + websockify_init() diff --git a/third_party/websockify/wsirc.html b/third_party/websockify/wsirc.html new file mode 100644 index 00000000..656cbc5e --- /dev/null +++ b/third_party/websockify/wsirc.html @@ -0,0 +1,99 @@ +<html> + + <head> + <title>IRC Client using WebSockets</title> + <script src="include/base64.js"></script> + <script src="include/websock.js"></script> + <script src="include/util.js"></script> + <script src="include/webutil.js"></script> + <script src="include/keysym.js"></script> + <script src="include/VT100.js"></script> + <script src="include/wsirc.js"></script> + <!-- Uncomment to activate firebug lite --> + <!-- + <script type='text/javascript' + src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script> + --> + + + </head> + + <body> + + Host: <input id='host' style='width:100'> + Port: <input id='port' style='width:50'> + Encrypt: <input id='encrypt' type='checkbox'> + <input id='connectButton' type='button' value='Connect' style='width:100px'> + <br> + Nick: <input id='nick' style='width:120'> + <br> + Channel: #<input id='channel' style='width:70'> + + <br><br> + + <div><pre id="irc"></pre></div> + > + <input id="msg" type="text" size=80 onkeypress="sendMsg();"> + + <script> + var irc; + + function sendMsg() { + if (event.keyCode === 13) { + var msg = $D('msg').value; + $D('msg').value = ""; + + Util.Debug("calling sendMsg('" + msg + "')"); + irc.sendMsg(msg); + } + } + + function connect() { + var ret; + ret = irc.connect($D('host').value, + $D('port').value, + $D('encrypt').checked, + $D('nick').value, + $D('channel').value); + if (! ret) { return false; } + $D('connectButton').disabled = true; + $D('connectButton').value = "Connecting"; + } + + function disconnect() { + $D('connectButton').disabled = true; + $D('connectButton').value = "Disconnecting"; + irc.disconnect(); + } + + function connected() { + $D('msg').disabled = false; + $D('connectButton').disabled = false; + $D('connectButton').value = "Disconnect"; + $D('connectButton').onclick = disconnect; + } + + function disconnected() { + $D('msg').disabled = true; + $D('connectButton').disabled = false; + $D('connectButton').value = "Connect"; + $D('connectButton').onclick = connect; + } + + window.onload = function() { + console.log("onload"); + var url = document.location.href; + $D('host').value = (url.match(/host=([^&#]*)/) || ['',''])[1]; + $D('port').value = (url.match(/port=([^&#]*)/) || ['',''])[1]; + $D('nick').value = (url.match(/nick=([^&#]*)/) || ['',''])[1]; + $D('channel').value = (url.match(/channel=([^&#]*)/) || ['',''])[1]; + + disconnected(); + + irc = IRC('irc', connected, disconnected); + } + </script> + + </body> + +</html> diff --git a/third_party/websockify/wstelnet.html b/third_party/websockify/wstelnet.html new file mode 100644 index 00000000..5a6ad91a --- /dev/null +++ b/third_party/websockify/wstelnet.html @@ -0,0 +1,74 @@ +<html> + + <head> + <title>Telnet client using WebSockets</title> + <script src="include/base64.js"></script> + <script src="include/util.js"></script> + <script src="include/websock.js"></script> + <script src="include/webutil.js"></script> + <script src="include/keysym.js"></script> + <script src="include/VT100.js"></script> + <script src="include/wstelnet.js"></script> + <!-- Uncomment to activate firebug lite --> + <!-- + <script type='text/javascript' + src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script> + --> + + + </head> + + <body> + + Host: <input id='host' style='width:100'> + Port: <input id='port' style='width:50'> + Encrypt: <input id='encrypt' type='checkbox'> + <input id='connectButton' type='button' value='Connect' style='width:100px' + onclick="connect();"> + + <br><br> + + <pre id="terminal"></pre> + + <script> + var telnet; + + function connect() { + telnet.connect($D('host').value, + $D('port').value, + $D('encrypt').checked); + $D('connectButton').disabled = true; + $D('connectButton').value = "Connecting"; + } + + function disconnect() { + $D('connectButton').disabled = true; + $D('connectButton').value = "Disconnecting"; + telnet.disconnect(); + } + + function connected() { + $D('connectButton').disabled = false; + $D('connectButton').value = "Disconnect"; + $D('connectButton').onclick = disconnect; + } + + function disconnected() { + $D('connectButton').disabled = false; + $D('connectButton').value = "Connect"; + $D('connectButton').onclick = connect; + } + + window.onload = function() { + console.log("onload"); + var url = document.location.href; + $D('host').value = (url.match(/host=([^&#]*)/) || ['',''])[1]; + $D('port').value = (url.match(/port=([^&#]*)/) || ['',''])[1]; + + telnet = Telnet('terminal', connected, disconnected); + } + </script> + + </body> + +</html> |