pax_global_header00006660000000000000000000000064125326371570014525gustar00rootroot0000000000000052 comment=8d7cbd4dd50cf34150b971b695d65f5ec2aa2b65 websockify-0.6.1+dfsg1/000077500000000000000000000000001253263715700146765ustar00rootroot00000000000000websockify-0.6.1+dfsg1/.gitignore000066400000000000000000000001761253263715700166720ustar00rootroot00000000000000*.pyc *.o *.so other/.lein-deps-sum other/classes other/lib other/node_modules .project .pydevproject target.cfg target.cfg.d websockify-0.6.1+dfsg1/.gitmodules000066400000000000000000000002051253263715700170500ustar00rootroot00000000000000[submodule "include/web-socket-js-project"] path = include/web-socket-js-project url = https://github.com/gimite/web-socket-js.git websockify-0.6.1+dfsg1/CHANGES.txt000066400000000000000000000032721253263715700165130ustar00rootroot00000000000000Changes ======= 0.6.1 - May 11, 2015 -------------------- * **PATCH RELEASE**: Fixes a bug causing file_only to not be passed properly 0.6.0 - Feb 18, 2014 -------------------- * **NOTE** : 0.6.0 will break existing code that sub-classes WebsocketProxy * Refactor to use standard SocketServer RequestHandler design * Fix zombie process bug on certain systems when using multiprocessing * Add better unit tests * Log information via python `logging` module 0.5.1 - Jun 27, 2013 -------------------- * use upstream einaros/ws (>=0.4.27) with websockify.js * file_only and no_parent security options for WSRequestHandler * Update build of web-socket-js (c0855c6cae) * add include/web-socket-js-project submodule to gimite/web-socket-js for DSFG compliance. * drop Hixie protocol support 0.4.1 - Mar 12, 2013 -------------------- * ***NOTE*** : 0.5.0 will drop Hixie protocol support * add include/ directory and remove some dev files from source distribution. 0.4.0 - Mar 12, 2013 -------------------- * ***NOTE*** : 0.5.0 will drop Hixie protocol support * use Buffer base64 support in Node.js implementation 0.3.0 - Jan 15, 2013 -------------------- * refactor into modules: websocket, websocketproxy * switch to web-socket-js that uses IETF 6455 * change to MPL 2.0 license for include/*.js * fix session recording 0.2.1 - Oct 15, 2012 -------------------- * re-released with updated version number 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. websockify-0.6.1+dfsg1/LICENSE.txt000066400000000000000000000011441253263715700165210ustar00rootroot00000000000000websockify is licensed under the LGPL version 3 (see docs/LICENSE.GPL-3 and docs/LICENSE.LGPL-3) with the following exceptions: include/websock.js : MPL 2.0 include/base64.js : MPL 2.0 include/des.js : Various BSD style licenses include/web-socket-js/ : New BSD license (3-clause). 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 websockify-0.6.1+dfsg1/MANIFEST.in000066400000000000000000000000701253263715700164310ustar00rootroot00000000000000include CHANGES.txt README.md LICENSE.txt graft include websockify-0.6.1+dfsg1/Makefile000066400000000000000000000002311253263715700163320ustar00rootroot00000000000000TARGETS=rebind.so CFLAGS += -fPIC all: $(TARGETS) rebind.so: rebind.o $(CC) $(LDFLAGS) $^ -shared -fPIC -ldl -o $@ clean: rm -f rebind.o rebind.so websockify-0.6.1+dfsg1/README.md000066400000000000000000000154421253263715700161630ustar00rootroot00000000000000## 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. ### News/help/contact Notable commits, announcements and news are posted to @noVNC If you are a websockify developer/integrator/user (or want to be) please join the noVNC/websockify discussion group Bugs and feature requests can be submitted via [github issues](https://github.com/kanaka/websockify/issues). If you want to show appreciation for websockify you could donate to a great non-profits such as: [Compassion International](http://www.compassion.com/), [SIL](http://www.sil.org), [Habitat for Humanity](http://www.habitat.org), [Electronic Frontier Foundation](https://www.eff.org/), [Against Malaria Foundation](http://www.againstmalaria.com/), [Nothing But Nets](http://www.nothingbutnets.net/), etc. Please tweet @noVNC if you do. ### WebSockets binary data Starting with websockify 0.5.0, only the HyBi / IETF 6455 WebSocket protocol is supported. Websockify negotiates whether to base64 encode traffic to and from the client via the subprotocol header (Sec-WebSocket-Protocol). The valid subprotocol values are 'binary' and 'base64' and if the client sends both then the server (the python implementation) will prefer 'binary'. The 'binary' subprotocol indicates that the data will be sent raw using binary WebSocket frames. Some HyBi clients (such as the Flash fallback and older Chrome and iOS versions) do not support binary data which is why the negotiation is necessary. ### 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. `./run 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): `./run 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 ./run 2023 --wrap-mode=respawn -- telnetd -debug 2023` The `wstelnet.html` page demonstrates a simple WebSockets based telnet client (use 'localhost' and '2023' for the host and port respectively). ### 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` * At the top level of the websockify repostory, download, build and symlink the ssl module: `wget --no-check-certificate 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` websockify-0.6.1+dfsg1/Windows/000077500000000000000000000000001253263715700163305ustar00rootroot00000000000000websockify-0.6.1+dfsg1/Windows/Windows Service Readme.txt000066400000000000000000000035061253263715700232660ustar00rootroot00000000000000----------------------------------- 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/websockify/wiki/Compiling-Websockify-as-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". websockify-0.6.1+dfsg1/Windows/noVNC Websocket Service Project/000077500000000000000000000000001253263715700241725ustar00rootroot00000000000000websockify-0.6.1+dfsg1/Windows/noVNC Websocket Service Project/Program.cs000066400000000000000000000007671253263715700261420ustar00rootroot00000000000000using System; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using System.Text; namespace MELT_Command_Websocket { static class Program { /// /// The main entry point for the application. /// static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service1() }; ServiceBase.Run(ServicesToRun); } } } websockify-0.6.1+dfsg1/Windows/noVNC Websocket Service Project/ProjectInstaller.Designer.cs000066400000000000000000000044531253263715700315520ustar00rootroot00000000000000namespace MELT_Command_Websocket { partial class ProjectInstaller { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// 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; } }websockify-0.6.1+dfsg1/Windows/noVNC Websocket Service Project/ProjectInstaller.cs000066400000000000000000000006311253263715700300050ustar00rootroot00000000000000using 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(); } } } websockify-0.6.1+dfsg1/Windows/noVNC Websocket Service Project/ProjectInstaller.resx000066400000000000000000000142201253263715700303600ustar00rootroot00000000000000 text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17, 56 196, 17 False websockify-0.6.1+dfsg1/Windows/noVNC Websocket Service Project/Properties/000077500000000000000000000000001253263715700263265ustar00rootroot00000000000000websockify-0.6.1+dfsg1/Windows/noVNC Websocket Service Project/Properties/AssemblyInfo.cs000066400000000000000000000026361253263715700312570ustar00rootroot00000000000000using 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")] websockify-0.6.1+dfsg1/Windows/noVNC Websocket Service Project/Service1.Designer.cs000066400000000000000000000020701253263715700277400ustar00rootroot00000000000000namespace MELT_Command_Websocket { partial class Service1 { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { components = new System.ComponentModel.Container(); this.ServiceName = "Service1"; } #endregion } } websockify-0.6.1+dfsg1/Windows/noVNC Websocket Service Project/Service1.cs000066400000000000000000000022221253263715700262000ustar00rootroot00000000000000using 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(); } } } websockify-0.6.1+dfsg1/Windows/noVNC Websocket Service Project/noVNC Websocket.csproj000066400000000000000000000057411253263715700303150ustar00rootroot00000000000000 Debug x86 8.0.30703 2.0 {6B86AE7B-6BBD-4E74-8802-5995E8B6D27D} WinExe Properties noVNC_Websocket_Service noVNC Websocket Service v3.5 512 x86 true full false bin\Debug\ DEBUG;TRACE prompt 4 x86 pdbonly true bin\Release\ TRACE prompt 4 Component ProjectInstaller.cs Component Service1.cs ProjectInstaller.cs websockify-0.6.1+dfsg1/Windows/noVNC Websocket Service Project/noVNC Websocket.sln000066400000000000000000000015231253263715700276030ustar00rootroot00000000000000 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 websockify-0.6.1+dfsg1/docs/000077500000000000000000000000001253263715700156265ustar00rootroot00000000000000websockify-0.6.1+dfsg1/docs/LICENSE.GPL-3000066400000000000000000000773301253263715700174260ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. 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 websockify-0.6.1+dfsg1/docs/LICENSE.LGPL-3000066400000000000000000000167431253263715700175430ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. 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. websockify-0.6.1+dfsg1/docs/LICENSE.MPL-2.0000066400000000000000000000405261253263715700175660ustar00rootroot00000000000000Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. websockify-0.6.1+dfsg1/docs/TODO000066400000000000000000000002661253263715700163220ustar00rootroot00000000000000- Go implementation - Rust implementation - Add sub-protocol support to upstream einaros/ws module and use that instead of the patched module. - wstelnet: support CSI L and CSI M websockify-0.6.1+dfsg1/docs/flash_policy.txt000066400000000000000000000003051253263715700210410ustar00rootroot00000000000000Manual setup: DATA="echo \'\'" /usr/bin/socat -T 1 TCP-L:843,reuseaddr,fork,crlf SYSTEM:"$DATA" websockify-0.6.1+dfsg1/docs/latency_results.txt000066400000000000000000000101211253263715700216020ustar00rootroot00000000000000This 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 websockify-0.6.1+dfsg1/docs/notes000066400000000000000000000016561253263715700167110ustar00rootroot00000000000000Some 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 Building release tarball: - not really necessary since tagged revision can be downloaded from github as tarballs git archive --format=tar --prefix=websockify-${WVER}/ v${WVER} > websockify-${WVER}.tar gzip websockify-${WVER}.tar websockify-0.6.1+dfsg1/docs/release.txt000066400000000000000000000006711253263715700200130ustar00rootroot00000000000000- Update setup.py, CHANGES.txt and other/package.json 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} - Register with pypi.python.org (once): python setup.py register - Upload the source distribution to pypi python setup.py sdist upload - Register with npmjs.org (once) - Upload websockify.js npmjs.org package npm publish other/js websockify-0.6.1+dfsg1/docs/websockify.1000066400000000000000000000133151253263715700200600ustar00rootroot00000000000000.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/ websockify-0.6.1+dfsg1/include/000077500000000000000000000000001253263715700163215ustar00rootroot00000000000000websockify-0.6.1+dfsg1/include/VT100.js000066400000000000000000000533271253263715700174430ustar00rootroot00000000000000// 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 // // 2007-08-12 - refresh(): // - factor out colour code to html_colours_() // - fix handling of A_REVERSE | A_DIM // - simplify initial
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
...
  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 ... 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 //
...
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 = ""; end_tag = "" + end_tag; } if (n_at.mode & VT100.A_STANDOUT) n_at.mode |= VT100.A_BOLD; pair = this.html_colours_(n_at); start_tag += ''; stuff += start_tag; end_tag = "" + 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 = "" + stuff + "\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 [{COUNT}A this.move(this.row_ - Math.max(1, this.csi_parms_[0]), this.col_); break; case 'B': // Cursor Down [{COUNT}B this.move(this.row_ + Math.max(1, this.csi_parms_[0]), this.col_); break; case 'C': // Cursor Forward [{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 [{COUNT}D this.move(this.row_, this.col_ - Math.max(1, this.csi_parms_[0])); break; case 'f': case 'H': // Cursor Home [{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[? // Expect a number - the reset type this.csi_parms_ = [ch]; this.esc_state_ = 6; break; case 6: // Reset mode handling, saw [?1 // Expect a letter - the mode target, example: // [?1l : cursor key mode = cursor // [?1h : save current screen, create new empty // screen and position at 0,0 // [?5l : White on blk // XXX: Ignored for now. //dump("Saw reset mode: [?" + 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"); } websockify-0.6.1+dfsg1/include/base64.js000066400000000000000000000076601253263715700177540ustar00rootroot00000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // From: http://hg.mozilla.org/mozilla-central/raw-file/ec10630b1a54/js/src/devtools/jint/sunspider/string-base64.js /*jslint white: false, bitwise: false, plusplus: false */ /*global console */ var Base64 = { /* Convert data (an array of integers) to a Base64 string. */ toBase64Table : 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''), base64Pad : '=', encode: function (data) { "use strict"; var result = ''; var toBase64Table = Base64.toBase64Table; var base64Pad = Base64.base64Pad; var length = data.length; var i; // Convert every three bytes to 4 ascii characters. /* BEGIN LOOP */ for (i = 0; i < (length - 2); i += 3) { result += toBase64Table[data[i] >> 2]; result += toBase64Table[((data[i] & 0x03) << 4) + (data[i+1] >> 4)]; result += toBase64Table[((data[i+1] & 0x0f) << 2) + (data[i+2] >> 6)]; result += toBase64Table[data[i+2] & 0x3f]; } /* END LOOP */ // Convert the remaining 1 or 2 bytes, pad out to 4 characters. if (length%3) { i = length - (length%3); result += toBase64Table[data[i] >> 2]; if ((length%3) === 2) { result += toBase64Table[((data[i] & 0x03) << 4) + (data[i+1] >> 4)]; result += toBase64Table[(data[i+1] & 0x0f) << 2]; result += base64Pad; } else { result += toBase64Table[(data[i] & 0x03) << 4]; result += base64Pad + base64Pad; } } 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 toBinaryTable = Base64.toBinaryTable; var base64Pad = Base64.base64Pad; var result, result_length, idx, i, c, padding; var leftbits = 0; // number of bits decoded, but yet to be appended var leftdata = 0; // bits decoded, but yet to be appended var 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. /* BEGIN LOOP */ for (idx = 0, i = offset; i < data.length; i++) { c = toBinaryTable[data.charCodeAt(i) & 0x7f]; padding = (data.charAt(i) === base64Pad); // 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; } } /* END LOOP */ // 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 */ websockify-0.6.1+dfsg1/include/keysym.js000066400000000000000000000111711253263715700202010ustar00rootroot00000000000000/* * 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; } websockify-0.6.1+dfsg1/include/util.js000066400000000000000000000300431253263715700176340ustar00rootroot00000000000000/* * from noVNC: HTML5 VNC client * Copyright (C) 2012 Joel Martin * Licensed under MPL 2.0 (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; }; } // // requestAnimationFrame shim with setTimeout fallback // window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback){ window.setTimeout(callback, 1000 / 60); }; })(); /* * ------------------------------------------------------ * 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 === 'str') { val = String(val); } 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 */ // Dynamically load scripts without using document.write() // Reference: http://unixpapa.com/js/dyna.html // // Handles the case where load_scripts is invoked from a script that // itself is loaded via load_scripts. Once all scripts are loaded the // window.onscriptsloaded handler is called (if set). Util.get_include_uri = function() { return (typeof INCLUDE_URI !== "undefined") ? INCLUDE_URI : "include/"; } Util._loading_scripts = []; Util._pending_scripts = []; Util.load_scripts = function(files) { var head = document.getElementsByTagName('head')[0], script, ls = Util._loading_scripts, ps = Util._pending_scripts; for (var f=0; f 0 && (ls[0].readyState === 'loaded' || ls[0].readyState === 'complete')) { // For IE, append the script to trigger execution var s = ls.shift(); //console.log("loaded script: " + s.src); head.appendChild(s); } if (!this.readyState || (Util.Engine.presto && this.readyState === 'loaded') || this.readyState === 'complete') { if (ps.indexOf(this) >= 0) { this.onload = this.onreadystatechange = null; //console.log("completed script: " + this.src); ps.splice(ps.indexOf(this), 1); // Call window.onscriptsload after last script loads if (ps.length === 0 && window.onscriptsload) { window.onscriptsload(); } } } }; // In-order script execution tricks if (Util.Engine.trident) { // For IE wait until readyState is 'loaded' before // appending it which will trigger execution // http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order ls.push(script); } else { // For webkit and firefox set async=false and append now // https://developer.mozilla.org/en-US/docs/HTML/Element/script script.async = false; head.appendChild(script); } ps.push(script); } } // 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}; }()); websockify-0.6.1+dfsg1/include/web-socket-js-project/000077500000000000000000000000001253263715700224425ustar00rootroot00000000000000websockify-0.6.1+dfsg1/include/web-socket-js/000077500000000000000000000000001253263715700207765ustar00rootroot00000000000000websockify-0.6.1+dfsg1/include/web-socket-js/README.txt000066400000000000000000000135231253263715700225000ustar00rootroot00000000000000* 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. websockify-0.6.1+dfsg1/include/web-socket-js/swfobject.js000077500000000000000000000617301253263715700233340ustar00rootroot00000000000000/*! SWFObject v2.2 is released under the MIT License */ var swfobject = function() { var UNDEF = "undefined", OBJECT = "object", SHOCKWAVE_FLASH = "Shockwave Flash", SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash", FLASH_MIME_TYPE = "application/x-shockwave-flash", EXPRESS_INSTALL_ID = "SWFObjectExprInst", ON_READY_STATE_CHANGE = "onreadystatechange", win = window, doc = document, nav = navigator, plugin = false, domLoadFnArr = [main], regObjArr = [], objIdArr = [], listenersArr = [], storedAltContent, storedAltContentId, storedCallbackFn, storedCallbackObj, isDomLoaded = false, isExpressInstallActive = false, dynamicStylesheet, dynamicStylesheetMedia, autoHideShow = true, /* Centralized function for browser feature detection - User agent string detection is only used when no good alternative is possible - Is executed directly for optimal performance */ ua = function() { var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF, u = nav.userAgent.toLowerCase(), p = nav.platform.toLowerCase(), windows = p ? /win/.test(p) : /win/.test(u), mac = p ? /mac/.test(p) : /mac/.test(u), webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html playerVersion = [0,0,0], d = null; if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) { d = nav.plugins[SHOCKWAVE_FLASH].description; if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+ plugin = true; ie = false; // cascaded feature detection for Internet Explorer d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1"); playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10); playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10); playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0; } } else if (typeof win.ActiveXObject != UNDEF) { try { var a = new ActiveXObject(SHOCKWAVE_FLASH_AX); if (a) { // a will return null when ActiveX is disabled d = a.GetVariable("$version"); if (d) { ie = true; // cascaded feature detection for Internet Explorer d = d.split(" ")[1].split(","); playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } } catch(e) {} } return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac }; }(), /* Cross-browser onDomLoad - Will fire an event as soon as the DOM of a web page is loaded - Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/ - Regular onload serves as fallback */ onDomLoad = function() { if (!ua.w3) { return; } if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically callDomLoadFunctions(); } if (!isDomLoaded) { if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false); } if (ua.ie && ua.win) { doc.attachEvent(ON_READY_STATE_CHANGE, function() { if (doc.readyState == "complete") { doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee); callDomLoadFunctions(); } }); if (win == top) { // if not inside an iframe (function(){ if (isDomLoaded) { return; } try { doc.documentElement.doScroll("left"); } catch(e) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } } if (ua.wk) { (function(){ if (isDomLoaded) { return; } if (!/loaded|complete/.test(doc.readyState)) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } addLoadEvent(callDomLoadFunctions); } }(); function callDomLoadFunctions() { if (isDomLoaded) { return; } try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span")); t.parentNode.removeChild(t); } catch (e) { return; } isDomLoaded = true; var dl = domLoadFnArr.length; for (var i = 0; i < dl; i++) { domLoadFnArr[i](); } } function addDomLoadEvent(fn) { if (isDomLoaded) { fn(); } else { domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+ } } /* Cross-browser onload - Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/ - Will fire an event as soon as a web page including all of its assets are loaded */ function addLoadEvent(fn) { if (typeof win.addEventListener != UNDEF) { win.addEventListener("load", fn, false); } else if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("load", fn, false); } else if (typeof win.attachEvent != UNDEF) { addListener(win, "onload", fn); } else if (typeof win.onload == "function") { var fnOld = win.onload; win.onload = function() { fnOld(); fn(); }; } else { win.onload = fn; } } /* Main function - Will preferably execute onDomLoad, otherwise onload (as a fallback) */ function main() { if (plugin) { testPlayerVersion(); } else { matchVersions(); } } /* Detect the Flash Player version for non-Internet Explorer browsers - Detecting the plug-in version via the object element is more precise than using the plugins collection item's description: a. Both release and build numbers can be detected b. Avoid wrong descriptions by corrupt installers provided by Adobe c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports - Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available */ function testPlayerVersion() { var b = doc.getElementsByTagName("body")[0]; var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); var t = b.appendChild(o); if (t) { var counter = 0; (function(){ if (typeof t.GetVariable != UNDEF) { var d = t.GetVariable("$version"); if (d) { d = d.split(" ")[1].split(","); ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } else if (counter < 10) { counter++; setTimeout(arguments.callee, 10); return; } b.removeChild(o); t = null; matchVersions(); })(); } else { matchVersions(); } } /* Perform Flash Player and SWF version matching; static publishing only */ function matchVersions() { var rl = regObjArr.length; if (rl > 0) { for (var i = 0; i < rl; i++) { // for each registered object element var id = regObjArr[i].id; var cb = regObjArr[i].callbackFn; var cbObj = {success:false, id:id}; if (ua.pv[0] > 0) { var obj = getElementById(id); if (obj) { if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match! setVisibility(id, true); if (cb) { cbObj.success = true; cbObj.ref = getObjectById(id); cb(cbObj); } } else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported var att = {}; att.data = regObjArr[i].expressInstall; att.width = obj.getAttribute("width") || "0"; att.height = obj.getAttribute("height") || "0"; if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); } if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); } // parse HTML object param element's name-value pairs var par = {}; var p = obj.getElementsByTagName("param"); var pl = p.length; for (var j = 0; j < pl; j++) { if (p[j].getAttribute("name").toLowerCase() != "movie") { par[p[j].getAttribute("name")] = p[j].getAttribute("value"); } } showExpressInstall(att, par, id, cb); } else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF displayAltContent(obj); if (cb) { cb(cbObj); } } } } else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content) setVisibility(id, true); if (cb) { var o = getObjectById(id); // test whether there is an HTML object element or not if (o && typeof o.SetVariable != UNDEF) { cbObj.success = true; cbObj.ref = o; } cb(cbObj); } } } } } function getObjectById(objectIdStr) { var r = null; var o = getElementById(objectIdStr); if (o && o.nodeName == "OBJECT") { if (typeof o.SetVariable != UNDEF) { r = o; } else { var n = o.getElementsByTagName(OBJECT)[0]; if (n) { r = n; } } } return r; } /* Requirements for Adobe Express Install - only one instance can be active at a time - fp 6.0.65 or higher - Win/Mac OS only - no Webkit engines older than version 312 */ function canExpressInstall() { return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312); } /* Show the Adobe Express Install dialog - Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75 */ function showExpressInstall(att, par, replaceElemIdStr, callbackFn) { isExpressInstallActive = true; storedCallbackFn = callbackFn || null; storedCallbackObj = {success:false, id:replaceElemIdStr}; var obj = getElementById(replaceElemIdStr); if (obj) { if (obj.nodeName == "OBJECT") { // static publishing storedAltContent = abstractAltContent(obj); storedAltContentId = null; } else { // dynamic publishing storedAltContent = obj; storedAltContentId = replaceElemIdStr; } att.id = EXPRESS_INSTALL_ID; if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; } if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; } doc.title = doc.title.slice(0, 47) + " - Flash Player Installation"; var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn", fv = "MMredirectURL=" + win.location.toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title; if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + fv; } else { par.flashvars = fv; } // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work if (ua.ie && ua.win && obj.readyState != 4) { var newObj = createElement("div"); replaceElemIdStr += "SWFObjectNew"; newObj.setAttribute("id", replaceElemIdStr); obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } createSWF(att, par, replaceElemIdStr); } } /* Functions to abstract and display alternative content */ function displayAltContent(obj) { if (ua.ie && ua.win && obj.readyState != 4) { // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work var el = createElement("div"); obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content el.parentNode.replaceChild(abstractAltContent(obj), el); obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.replaceChild(abstractAltContent(obj), obj); } } function abstractAltContent(obj) { var ac = createElement("div"); if (ua.win && ua.ie) { ac.innerHTML = obj.innerHTML; } else { var nestedObj = obj.getElementsByTagName(OBJECT)[0]; if (nestedObj) { var c = nestedObj.childNodes; if (c) { var cl = c.length; for (var i = 0; i < cl; i++) { if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) { ac.appendChild(c[i].cloneNode(true)); } } } } } return ac; } /* Cross-browser dynamic SWF creation */ function createSWF(attObj, parObj, id) { var r, el = getElementById(id); if (ua.wk && ua.wk < 312) { return r; } if (el) { if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content attObj.id = id; } if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML var att = ""; for (var i in attObj) { if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries if (i.toLowerCase() == "data") { parObj.movie = attObj[i]; } else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword att += ' class="' + attObj[i] + '"'; } else if (i.toLowerCase() != "classid") { att += ' ' + i + '="' + attObj[i] + '"'; } } } var par = ""; for (var j in parObj) { if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries par += ''; } } el.outerHTML = '' + par + ''; objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only) r = getElementById(attObj.id); } else { // well-behaving browsers var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); for (var m in attObj) { if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword o.setAttribute("class", attObj[m]); } else if (m.toLowerCase() != "classid") { // filter out IE specific attribute o.setAttribute(m, attObj[m]); } } } for (var n in parObj) { if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element createObjParam(o, n, parObj[n]); } } el.parentNode.replaceChild(o, el); r = o; } } return r; } function createObjParam(el, pName, pValue) { var p = createElement("param"); p.setAttribute("name", pName); p.setAttribute("value", pValue); el.appendChild(p); } /* Cross-browser SWF removal - Especially needed to safely and completely remove a SWF in Internet Explorer */ function removeSWF(id) { var obj = getElementById(id); if (obj && obj.nodeName == "OBJECT") { if (ua.ie && ua.win) { obj.style.display = "none"; (function(){ if (obj.readyState == 4) { removeObjectInIE(id); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.removeChild(obj); } } } function removeObjectInIE(id) { var obj = getElementById(id); if (obj) { for (var i in obj) { if (typeof obj[i] == "function") { obj[i] = null; } } obj.parentNode.removeChild(obj); } } /* Functions to optimize JavaScript compression */ function getElementById(id) { var el = null; try { el = doc.getElementById(id); } catch (e) {} return el; } function createElement(el) { return doc.createElement(el); } /* Updated attachEvent function for Internet Explorer - Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks */ function addListener(target, eventType, fn) { target.attachEvent(eventType, fn); listenersArr[listenersArr.length] = [target, eventType, fn]; } /* Flash Player and SWF content version matching */ function hasPlayerVersion(rv) { var pv = ua.pv, v = rv.split("."); v[0] = parseInt(v[0], 10); v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0" v[2] = parseInt(v[2], 10) || 0; return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false; } /* Cross-browser dynamic CSS creation - Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php */ function createCSS(sel, decl, media, newStyle) { if (ua.ie && ua.mac) { return; } var h = doc.getElementsByTagName("head")[0]; if (!h) { return; } // to also support badly authored HTML pages that lack a head element var m = (media && typeof media == "string") ? media : "screen"; if (newStyle) { dynamicStylesheet = null; dynamicStylesheetMedia = null; } if (!dynamicStylesheet || dynamicStylesheetMedia != m) { // create dynamic stylesheet + get a global reference to it var s = createElement("style"); s.setAttribute("type", "text/css"); s.setAttribute("media", m); dynamicStylesheet = h.appendChild(s); if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) { dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1]; } dynamicStylesheetMedia = m; } // add style rule if (ua.ie && ua.win) { if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) { dynamicStylesheet.addRule(sel, decl); } } else { if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) { dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}")); } } } function setVisibility(id, isVisible) { if (!autoHideShow) { return; } var v = isVisible ? "visible" : "hidden"; if (isDomLoaded && getElementById(id)) { getElementById(id).style.visibility = v; } else { createCSS("#" + id, "visibility:" + v); } } /* Filter to avoid XSS attacks */ function urlEncodeIfNecessary(s) { var regex = /[\\\"<>\.;]/; var hasBadChars = regex.exec(s) != null; return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s; } /* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only) */ var cleanup = function() { if (ua.ie && ua.win) { window.attachEvent("onunload", function() { // remove listeners to avoid memory leaks var ll = listenersArr.length; for (var i = 0; i < ll; i++) { listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]); } // cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect var il = objIdArr.length; for (var j = 0; j < il; j++) { removeSWF(objIdArr[j]); } // cleanup library's main closures to avoid memory leaks for (var k in ua) { ua[k] = null; } ua = null; for (var l in swfobject) { swfobject[l] = null; } swfobject = null; }); } }(); return { /* Public API - Reference: http://code.google.com/p/swfobject/wiki/documentation */ registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) { if (ua.w3 && objectIdStr && swfVersionStr) { var regObj = {}; regObj.id = objectIdStr; regObj.swfVersion = swfVersionStr; regObj.expressInstall = xiSwfUrlStr; regObj.callbackFn = callbackFn; regObjArr[regObjArr.length] = regObj; setVisibility(objectIdStr, false); } else if (callbackFn) { callbackFn({success:false, id:objectIdStr}); } }, getObjectById: function(objectIdStr) { if (ua.w3) { return getObjectById(objectIdStr); } }, embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) { var callbackObj = {success:false, id:replaceElemIdStr}; if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) { setVisibility(replaceElemIdStr, false); addDomLoadEvent(function() { widthStr += ""; // auto-convert to string heightStr += ""; var att = {}; if (attObj && typeof attObj === OBJECT) { for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs att[i] = attObj[i]; } } att.data = swfUrlStr; att.width = widthStr; att.height = heightStr; var par = {}; if (parObj && typeof parObj === OBJECT) { for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs par[j] = parObj[j]; } } if (flashvarsObj && typeof flashvarsObj === OBJECT) { for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + k + "=" + flashvarsObj[k]; } else { par.flashvars = k + "=" + flashvarsObj[k]; } } } if (hasPlayerVersion(swfVersionStr)) { // create SWF var obj = createSWF(att, par, replaceElemIdStr); if (att.id == replaceElemIdStr) { setVisibility(replaceElemIdStr, true); } callbackObj.success = true; callbackObj.ref = obj; } else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install att.data = xiSwfUrlStr; showExpressInstall(att, par, replaceElemIdStr, callbackFn); return; } else { // show alternative content setVisibility(replaceElemIdStr, true); } if (callbackFn) { callbackFn(callbackObj); } }); } else if (callbackFn) { callbackFn(callbackObj); } }, switchOffAutoHideShow: function() { autoHideShow = false; }, ua: ua, getFlashPlayerVersion: function() { return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] }; }, hasFlashPlayerVersion: hasPlayerVersion, createSWF: function(attObj, parObj, replaceElemIdStr) { if (ua.w3) { return createSWF(attObj, parObj, replaceElemIdStr); } else { return undefined; } }, showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) { if (ua.w3 && canExpressInstall()) { showExpressInstall(att, par, replaceElemIdStr, callbackFn); } }, removeSWF: function(objElemIdStr) { if (ua.w3) { removeSWF(objElemIdStr); } }, createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) { if (ua.w3) { createCSS(selStr, declStr, mediaStr, newStyleBoolean); } }, addDomLoadEvent: addDomLoadEvent, addLoadEvent: addLoadEvent, getQueryParamValue: function(param) { var q = doc.location.search || doc.location.hash; if (q) { if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark if (param == null) { return urlEncodeIfNecessary(q); } var pairs = q.split("&"); for (var i = 0; i < pairs.length; i++) { if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) { return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1))); } } } return ""; }, // For internal usage only expressInstallCallback: function() { if (isExpressInstallActive) { var obj = getElementById(EXPRESS_INSTALL_ID); if (obj && storedAltContent) { obj.parentNode.replaceChild(storedAltContent, obj); if (storedAltContentId) { setVisibility(storedAltContentId, true); if (ua.ie && ua.win) { storedAltContent.style.display = "block"; } } if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); } } isExpressInstallActive = false; } } }; }(); websockify-0.6.1+dfsg1/include/web-socket-js/web_socket.js000077500000000000000000000313571253263715700234750ustar00rootroot00000000000000// Copyright: Hiroshi Ichikawa // 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 DOM 2 EventTarget Interface} * * @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 DOM 2 EventTarget Interface} * * @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 DOM 2 EventTarget Interface} * * @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(); }); } })(); websockify-0.6.1+dfsg1/include/websock.js000066400000000000000000000261541253263715700203240ustar00rootroot00000000000000/* * Websock: high-performance binary WebSockets * Copyright (C) 2012 Joel Martin * Licensed under MPL 2.0 (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 () { window.WEB_SOCKET_SWF_LOCATION = Util.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(); } Util.load_scripts(["web-socket-js/swfobject.js", "web-socket-js/web_socket.js"]); }()); } 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 var u8 = new Uint8Array(data); for (var i = 0; i < u8.length; i++) { rQ.push(u8[i]); } } 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); if (protocols.indexOf('binary') >= 0) { websocket.binaryType = 'arraybuffer'; } } 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); } 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, data_mode) { test_mode = true; mode = data_mode; 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(); } websockify-0.6.1+dfsg1/include/webutil.js000066400000000000000000000135321253263715700203360ustar00rootroot00000000000000/* * from noVNC: HTML5 VNC client * Copyright (C) 2012 Joel Martin * Licensed under MPL 2.0 (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(level) { if (typeof level !== "undefined") { Util._log_level = level; } else { Util._log_level = (document.location.href.match( /logging=([A-Za-z0-9\._\-]*)/) || ['', Util._log_level])[1]; } Util.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 + '=([^&#]*)'), match = document.location.href.match(re); if (typeof defVal === 'undefined') { defVal = null; } if (match) { return decodeURIComponent(match[1]); } else { return defVal; } }; /* * 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); }; /* * Setting handling. */ WebUtil.initSettings = function(callback) { var callbackArgs = Array.prototype.slice.call(arguments, 1); if (window.chrome && window.chrome.storage) { window.chrome.storage.sync.get(function (cfg) { WebUtil.settings = cfg; console.log(WebUtil.settings); if (callback) { callback.apply(this, callbackArgs); } }); } else { // No-op if (callback) { callback.apply(this, callbackArgs); } } }; // No days means only for this browser session WebUtil.writeSetting = function(name, value) { if (window.chrome && window.chrome.storage) { //console.log("writeSetting:", name, value); if (WebUtil.settings[name] !== value) { WebUtil.settings[name] = value; window.chrome.storage.sync.set(WebUtil.settings); } } else { localStorage.setItem(name, value); } }; WebUtil.readSetting = function(name, defaultValue) { var value; if (window.chrome && window.chrome.storage) { value = WebUtil.settings[name]; } else { value = localStorage.getItem(name); } if (typeof value === "undefined") { value = null; } if (value === null && typeof defaultValue !== undefined) { return defaultValue; } else { return value; } }; WebUtil.eraseSetting = function(name) { if (window.chrome && window.chrome.storage) { window.chrome.storage.sync.remove(name); delete WebUtil.settings[name]; } else { localStorage.removeItem(name); } }; /* * 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; }; websockify-0.6.1+dfsg1/include/wsirc.js000066400000000000000000000120621253263715700200070ustar00rootroot00000000000000/* * 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() websockify-0.6.1+dfsg1/include/wstelnet.js000066400000000000000000000224501253263715700205270ustar00rootroot00000000000000/* * 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() websockify-0.6.1+dfsg1/other/000077500000000000000000000000001253263715700160175ustar00rootroot00000000000000websockify-0.6.1+dfsg1/other/Makefile000066400000000000000000000003711253263715700174600ustar00rootroot00000000000000TARGETS=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 websockify-0.6.1+dfsg1/other/README.md000066400000000000000000000025731253263715700173050ustar00rootroot00000000000000This 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. websockify-0.6.1+dfsg1/other/js/000077500000000000000000000000001253263715700164335ustar00rootroot00000000000000websockify-0.6.1+dfsg1/other/js/README.md000066400000000000000000000003231253263715700177100ustar00rootroot00000000000000A JavaScript implementation of the websockify WebSocket-to-TCP bridge/proxy. Copyright (C) 2013 - Joel Martin (github.com/kanaka) Licensed under LGPL-3. See http://github.com/kanaka/websockify for more info. websockify-0.6.1+dfsg1/other/js/package.json000066400000000000000000000010731253263715700207220ustar00rootroot00000000000000{ "author": "Joel Martin (http://github.com/kanaka)", "name": "websockify", "description": "websockify is a WebSocket-to-TCP proxy/bridge", "license": "LGPL-3", "version": "0.6.1", "repository": { "type": "git", "url": "git://github.com/kanaka/websockify.git" }, "files": ["../../docs/LICENSE.LGPL-3"], "bin": { "websockify": "./websockify.js" }, "engines": { "node": ">=0.8.9" }, "dependencies": { "ws": ">=0.4.27", "base64": "latest", "optimist": "latest", "policyfile": "latest" } } websockify-0.6.1+dfsg1/other/js/websockify.js000077500000000000000000000132271253263715700211460ustar00rootroot00000000000000#!/usr/bin/env node // 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.8.9 // Requires node modules: ws, optimist and policyfile // npm install ws optimist policyfile var argv = require('optimist').argv, net = require('net'), http = require('http'), https = require('https'), url = require('url'), path = require('path'), fs = require('fs'), policyfile = require('policyfile'), Buffer = require('buffer').Buffer, WebSocketServer = require('ws').Server, webServer, wsServer, source_host, source_port, target_host, target_port, web_path = null; // Handle new WebSocket client new_client = function(client) { var clientAddr = client._socket.remoteAddress, log; console.log(client.upgradeReq.url); log = function (msg) { console.log(' ' + clientAddr + ': '+ msg); }; log('WebSocket connection'); log('Version ' + client.protocolVersion + ', subprotocol: ' + client.protocol); var target = net.createConnection(target_port,target_host, function() { log('connected to target'); }); target.on('data', function(data) { //log("sending message: " + data); try { if (client.protocol === 'base64') { client.send(new Buffer(data).toString('base64')); } else { client.send(data,{binary: true}); } } catch(e) { log("Client closed, cleaning up target"); target.end(); } }); target.on('end', function() { log('target disconnected'); client.close(); }); target.on('error', function() { log('target connection error'); target.end(); client.close(); }); client.on('message', function(msg) { //log('got message: ' + msg); if (client.protocol === 'base64') { target.write(new Buffer(msg, 'base64')); } else { target.write(msg,'binary'); } }); client.on('close', function(code, reason) { log('WebSocket client disconnected: ' + code + ' [' + reason + ']'); target.end(); }); client.on('error', function(a) { log('WebSocket client error: ' + a); target.end(); }); }; // 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(); }); }); }; // Select 'binary' or 'base64' subprotocol, preferring 'binary' selectProtocol = function(protocols, callback) { if (protocols.indexOf('binary') >= 0) { callback(true, 'binary'); } else if (protocols.indexOf('base64') >= 0) { callback(true, 'base64'); } else { console.log("Client must support 'binary' or 'base64' protocol"); callback(false); } } // 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("websockify.js [--web web_dir] [--cert cert.pem [--key key.pem]] [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); } if (argv.cert) { argv.key = argv.key || argv.cert; var cert = fs.readFileSync(argv.cert), key = fs.readFileSync(argv.key); console.log(" - Running in encrypted HTTPS (wss://) mode using: " + argv.cert + ", " + argv.key); webServer = https.createServer({cert: cert, key: key}, http_request); } else { console.log(" - Running in unencrypted HTTP (ws://) mode"); webServer = http.createServer(http_request); } webServer.listen(source_port, function() { wsServer = new WebSocketServer({server: webServer, handleProtocols: selectProtocol}); wsServer.on('connection', new_client); }); // Attach Flash policyfile answer service policyfile.createServer().listen(-1, webServer); websockify-0.6.1+dfsg1/other/launch.sh000077500000000000000000000062031253263715700176310ustar00rootroot00000000000000#!/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" echo " --web WEB Path to web files (e.g. vnc.html)" echo " Default: ./" exit 2 } NAME="$(basename $0)" HERE="$(cd "$(dirname "$0")" && pwd)" PORT="6080" VNC_DEST="localhost:5900" CERT="" WEB="" 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 ;; --web) WEB="${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 [ -n "${WEB}" ]; then if [ ! -e "${WEB}/vnc.html" ]; then die "Could not find ${WEB}/vnc.html" fi elif [ -e "$(pwd)/vnc.html" ]; then WEB=$(pwd) elif [ -e "${HERE}/../vnc.html" ]; then WEB=${HERE}/../ elif [ -e "${HERE}/vnc.html" ]; then WEB=${HERE} elif [ -e "${HERE}/../share/novnc/vnc.html" ]; then WEB=${HERE}/../share/novnc/ 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}/websockify --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 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} websockify-0.6.1+dfsg1/other/project.clj000066400000000000000000000011741253263715700201620ustar00rootroot00000000000000(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 ) websockify-0.6.1+dfsg1/other/websocket.c000066400000000000000000000543621253263715700201630ustar00rootroot00000000000000/* * 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 #include #include #include #include #include #include #include #include #include #include // daemonizing #include // daemonizing #include #include #include /* base64 encode/decode */ #include /* md5 hash */ #include /* 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, "", 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("websockify exit\n"); } } websockify-0.6.1+dfsg1/other/websocket.h000066400000000000000000000040671253263715700201650ustar00rootroot00000000000000#include #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 "\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__); websockify-0.6.1+dfsg1/other/websocket.rb000066400000000000000000000303421253263715700203340ustar00rootroot00000000000000 # 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 'openssl' require 'stringio' require 'digest/md5' require 'digest/sha1' require 'base64' unless OpenSSL::SSL::SSLSocket.instance_methods.index("read_nonblock") module OpenSSL module SSL class SSLSocket alias :read_nonblock :readpartial end end end end 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) msg opts.inspect if opts['server_cert'] msg "creating ssl context" @sslContext = OpenSSL::SSL::SSLContext.new @sslContext.cert = OpenSSL::X509::Certificate.new(File.open(opts['server_cert'])) @sslContext.key = OpenSSL::PKey::RSA.new(File.open(opts['server_key'])) @sslContext.ca_file = opts['server_cert'] @sslContext.verify_mode = OpenSSL::SSL::VERIFY_NONE @sslContext.verify_depth = 0 end @@client_id = 0 # Track client number total on class @verbose = opts['verbose'] @opts = opts end def serve(io) @@client_id += 1 msg self.inspect if @sslContext msg "Enabling SSL context" ssl = OpenSSL::SSL::SSLSocket.new(io, @sslContext) #ssl.sync_close = true #ssl.sync = true msg "SSL accepting" ssl.accept io = ssl # replace the unencrypted handle with the encrypted one end msg "initializing thread" # 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[:my_client_id].inspect}" begin t[:client] = do_handshake(io) new_websocket_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(m) printf("% 3d: %s\n", Thread.current[:my_client_id] || 0, m) end def vmsg(m) if @verbose then msg(m) 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].each_byte.map{|b|b} data = buf[pstart...pstart+length] #data = data.bytes.zip(mask.bytes.cycle(length)).map { |d,m| d^m } i=-1 data = data.each_byte.map{|b| i+=1; (b ^ mask[i % 4]).chr}.join("") 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].write(buf) 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].read_nonblock(@@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].write(buf) elsif t[:version] == "hixie-76" buf = "\xff\x00" t[:client].write(buf) 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 = "" msg "About to read from sock [#{sock.inspect}]" handshake = sock.read_nonblock(1024) msg "Handshake [#{handshake.inspect}]" if handshake == nil or handshake == "" raise(EClose, "ignoring empty handshake") else stype = "Plain non-SSL (ws://)" scheme = "ws" if sock.class == OpenSSL::SSL::SSLSocket stype = "SSL (wss://)" scheme = "wss" end retsock = sock 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.write(response) # Return the WebSocket socket which may be SSL wrapped return retsock end end # vim: sw=2 websockify-0.6.1+dfsg1/other/websockify.c000066400000000000000000000270701253263715700203360ustar00rootroot00000000000000/* * 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 #include #include #include #include #include #include #include #include #include #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(); } websockify-0.6.1+dfsg1/other/websockify.clj000066400000000000000000000200771253263715700206640ustar00rootroot00000000000000(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)websockify-0.6.1+dfsg1/other/websockify.rb000077500000000000000000000071631253263715700205230ustar00rootroot00000000000000#!/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_websocket_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 websockify-0.6.1+dfsg1/other/wswrap000077500000000000000000000006471253263715700172770ustar00rootroot00000000000000#!/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 "${@}" websockify-0.6.1+dfsg1/rebind000077500000000000000000000006501253263715700160700ustar00rootroot00000000000000#!/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 "${@}" websockify-0.6.1+dfsg1/rebind.c000066400000000000000000000055071253263715700163140ustar00rootroot00000000000000/* * 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 bridge/proxy (such as websockify) 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 #include #define __USE_GNU 1 // Pull in RTLD_NEXT #include #include #include #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; } websockify-0.6.1+dfsg1/run000077500000000000000000000001221253263715700154230ustar00rootroot00000000000000#!/usr/bin/python import websockify websockify.websocketproxy.websockify_init() websockify-0.6.1+dfsg1/setup.py000066400000000000000000000023371253263715700164150ustar00rootroot00000000000000from setuptools import setup, find_packages version = '0.6.1' 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", ], data_files=[('share/websockify/include', ['include/util.js', 'include/base64.js', 'include/websock.js']), ('share/websockify/include/web-socket-js', ['include/web-socket-js/WebSocketMain.swf', 'include/web-socket-js/swfobject.js', 'include/web-socket-js/web_socket.js'])], 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', ] }, ) websockify-0.6.1+dfsg1/tests/000077500000000000000000000000001253263715700160405ustar00rootroot00000000000000websockify-0.6.1+dfsg1/tests/b64_vs_utf8.py000077500000000000000000000017011253263715700204650ustar00rootroot00000000000000#!/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)) websockify-0.6.1+dfsg1/tests/base64.html000066400000000000000000000061121253263715700200120ustar00rootroot00000000000000 Native Base64 Tests

Native Base64 Tests


Messages:

websockify-0.6.1+dfsg1/tests/base64.js000066400000000000000000000005661253263715700174710ustar00rootroot00000000000000// 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)); websockify-0.6.1+dfsg1/tests/echo.html000066400000000000000000000105551253263715700176520ustar00rootroot00000000000000 WebSockets Echo Test Host:   Port:   Encrypt:    
Log:
websockify-0.6.1+dfsg1/tests/echo.py000077500000000000000000000046031253263715700173360ustar00rootroot00000000000000#!/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, logging sys.path.insert(0,os.path.join(os.path.dirname(__file__), "..")) from websockify.websocket import WebSocketServer, WebSocketRequestHandler class WebSocketEcho(WebSocketRequestHandler): """ WebSockets server that echos back whatever is received from the client. """ buffer_size = 8096 def new_websocket_client(self): """ Echo back whatever is received. """ cqueue = [] c_pend = 0 cpartial = "" rlist = [self.request] while True: wlist = [] if cqueue or c_pend: wlist.append(self.request) ins, outs, excepts = select.select(rlist, wlist, [], 1) if excepts: raise Exception("Socket exception") if self.request in outs: # Send queued target data to the client c_pend = self.send_frames(cqueue) cqueue = [] if self.request in ins: # Receive client data, decode it, and send it back frames, closed = self.recv_frames() cqueue.extend(frames) if closed: self.send_close() 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") logging.basicConfig(level=logging.INFO) opts.web = "." server = WebSocketServer(WebSocketEcho, **opts.__dict__) server.start_server() websockify-0.6.1+dfsg1/tests/echo.rb000077500000000000000000000026271253263715700173150ustar00rootroot00000000000000#!/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_websocket_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 || 8080 puts "Starting server on port #{port}" server_cert = nil server_key = nil if ARGV.length > 2 server_cert = ARGV[1] server_key = ARGV[2] end server = WebSocketEcho.new('listen_port' => port, 'verbose' => true, 'server_cert' => server_cert, 'server_key' => server_key) server.start server.join puts "Server has been terminated" # vim: sw=2 websockify-0.6.1+dfsg1/tests/include000077700000000000000000000000001253263715700211622../includeustar00rootroot00000000000000websockify-0.6.1+dfsg1/tests/latency.html000066400000000000000000000221101253263715700203610ustar00rootroot00000000000000 WebSockets Latency Test Host:   Port:   Encrypt:
Payload Size:   Send Delay (ms):    

Packets sent:
Packets Received:
Average Latency:
40 Frame Running Average Latency:
Minimum Latency:
Maximum Latency:

Messages:
websockify-0.6.1+dfsg1/tests/latency.py000077700000000000000000000000001253263715700213342echo.pyustar00rootroot00000000000000websockify-0.6.1+dfsg1/tests/load.html000066400000000000000000000204351253263715700176510ustar00rootroot00000000000000 WebSockets Load Test Host:   Port:   Encrypt:   Send Delay (ms):    

Packets sent:
0
Good Packets Received:
0
Errors (Bad Packets Received:)
0

Errors:
websockify-0.6.1+dfsg1/tests/load.py000077500000000000000000000120101253263715700173260ustar00rootroot00000000000000#!/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, logging sys.path.insert(0,os.path.join(os.path.dirname(__file__), "..")) from websockify.websocket import WebSocketServer, WebSocketRequestHandler class WebSocketLoadServer(WebSocketServer): recv_cnt = 0 send_cnt = 0 def __init__(self, *args, **kwargs): self.delay = kwargs.pop('delay') WebSocketServer.__init__(self, *args, **kwargs) class WebSocketLoad(WebSocketRequestHandler): max_packet_size = 10000 def new_websocket_client(self): print "Prepopulating random array" self.rand_array = [] for i in range(0, self.max_packet_size): self.rand_array.append(random.randint(0, 9)) self.errors = 0 self.send_cnt = 0 self.recv_cnt = 0 try: self.responder(self.request) 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() now = time.time() * 1000 if client in outs: if c_pend: last_send = now c_pend = self.send_frames() elif now > (last_send + self.server.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" + repr(data) + "" 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") logging.basicConfig(level=logging.INFO) opts.web = "." server = WebSocketLoadServer(WebSocketLoad, **opts.__dict__) server.start_server() websockify-0.6.1+dfsg1/tests/plain_echo.html000066400000000000000000000122541253263715700210330ustar00rootroot00000000000000 WebSockets Echo Test Host:   Port:   Encrypt:    
Log:
websockify-0.6.1+dfsg1/tests/simple.html000066400000000000000000000037071253263715700202260ustar00rootroot00000000000000 Websock Simple Client WebSocket/websockify URI:  

   

Log:
websockify-0.6.1+dfsg1/tests/test_websocket.py000066400000000000000000000236071253263715700214470ustar00rootroot00000000000000# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright(c)2013 NTT corp. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Unit tests for websocket """ import errno import os import logging import select import shutil import socket import ssl import stubout import sys import tempfile import unittest from ssl import SSLError from websockify import websocket as websocket from SimpleHTTPServer import SimpleHTTPRequestHandler class MockConnection(object): def __init__(self, path): self.path = path def makefile(self, mode='r', bufsize=-1): return open(self.path, mode, bufsize) class WebSocketTestCase(unittest.TestCase): def _init_logger(self, tmpdir): name = 'websocket-unittest' logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) logger.propagate = True filename = "%s.log" % (name) handler = logging.FileHandler(filename) handler.setFormatter(logging.Formatter("%(message)s")) logger.addHandler(handler) def setUp(self): """Called automatically before each test.""" super(WebSocketTestCase, self).setUp() self.stubs = stubout.StubOutForTesting() # Temporary dir for test data self.tmpdir = tempfile.mkdtemp() # Put log somewhere persistent self._init_logger('./') # Mock this out cause it screws tests up self.stubs.Set(os, 'chdir', lambda *args, **kwargs: None) self.server = self._get_websockserver(daemon=True, ssl_only=False) self.soc = self.server.socket('localhost') def tearDown(self): """Called automatically after each test.""" self.stubs.UnsetAll() shutil.rmtree(self.tmpdir) super(WebSocketTestCase, self).tearDown() def _get_websockserver(self, **kwargs): return websocket.WebSocketServer(listen_host='localhost', listen_port=80, key=self.tmpdir, web=self.tmpdir, record=self.tmpdir, **kwargs) def _mock_os_open_oserror(self, file, flags): raise OSError('') def _mock_os_close_oserror(self, fd): raise OSError('') def _mock_os_close_oserror_EBADF(self, fd): raise OSError(errno.EBADF, '') def _mock_socket(self, *args, **kwargs): return self.soc def _mock_select(self, rlist, wlist, xlist, timeout=None): return '_mock_select' def _mock_select_exception(self, rlist, wlist, xlist, timeout=None): raise Exception def _mock_select_keyboardinterrupt(self, rlist, wlist, xlist, timeout=None): raise KeyboardInterrupt def _mock_select_systemexit(self, rlist, wlist, xlist, timeout=None): sys.exit() def test_daemonize_error(self): soc = self._get_websockserver(daemon=True, ssl_only=1, idle_timeout=1) self.stubs.Set(os, 'fork', lambda *args: None) self.stubs.Set(os, 'setsid', lambda *args: None) self.stubs.Set(os, 'close', self._mock_os_close_oserror) self.assertRaises(OSError, soc.daemonize, keepfd=None, chdir='./') def test_daemonize_EBADF_error(self): soc = self._get_websockserver(daemon=True, ssl_only=1, idle_timeout=1) self.stubs.Set(os, 'fork', lambda *args: None) self.stubs.Set(os, 'setsid', lambda *args: None) self.stubs.Set(os, 'close', self._mock_os_close_oserror_EBADF) self.stubs.Set(os, 'open', self._mock_os_open_oserror) self.assertRaises(OSError, soc.daemonize, keepfd=None, chdir='./') def test_decode_hybi(self): soc = self._get_websockserver(daemon=False, ssl_only=1, idle_timeout=1) self.assertRaises(Exception, soc.decode_hybi, 'a' * 128, base64=True) def test_do_websocket_handshake(self): soc = self._get_websockserver(daemon=True, ssl_only=0, idle_timeout=1) soc.scheme = 'scheme' headers = {'Sec-WebSocket-Protocol': 'binary', 'Sec-WebSocket-Version': '7', 'Sec-WebSocket-Key': 'foo'} soc.do_websocket_handshake(headers, '127.0.0.1') def test_do_handshake(self): soc = self._get_websockserver(daemon=True, ssl_only=0, idle_timeout=1) self.stubs.Set(select, 'select', self._mock_select) self.stubs.Set(socket._socketobject, 'recv', lambda *args: 'mock_recv') self.assertRaises(Exception, soc.do_handshake, self.soc, '127.0.0.1') def test_do_handshake_ssl_error(self): soc = self._get_websockserver(daemon=True, ssl_only=0, idle_timeout=1) def _mock_wrap_socket(*args, **kwargs): from ssl import SSLError raise SSLError('unit test exception') self.stubs.Set(select, 'select', self._mock_select) self.stubs.Set(socket._socketobject, 'recv', lambda *args: '\x16') self.stubs.Set(ssl, 'wrap_socket', _mock_wrap_socket) self.assertRaises(SSLError, soc.do_handshake, self.soc, '127.0.0.1') def test_fallback_SIGCHILD(self): soc = self._get_websockserver(daemon=True, ssl_only=0, idle_timeout=1) soc.fallback_SIGCHLD(None, None) def test_start_server_Exception(self): soc = self._get_websockserver(daemon=False, ssl_only=1, idle_timeout=1) self.stubs.Set(websocket.WebSocketServer, 'socket', self._mock_socket) self.stubs.Set(websocket.WebSocketServer, 'daemonize', lambda *args, **kwargs: None) self.stubs.Set(select, 'select', self._mock_select_exception) self.assertEqual(None, soc.start_server()) def test_start_server_KeyboardInterrupt(self): soc = self._get_websockserver(daemon=False, ssl_only=1, idle_timeout=1) self.stubs.Set(websocket.WebSocketServer, 'socket', self._mock_socket) self.stubs.Set(websocket.WebSocketServer, 'daemonize', lambda *args, **kwargs: None) self.stubs.Set(select, 'select', self._mock_select_keyboardinterrupt) self.assertEqual(None, soc.start_server()) def test_start_server_systemexit(self): websocket.ssl = None self.stubs.Set(websocket.WebSocketServer, 'socket', self._mock_socket) self.stubs.Set(websocket.WebSocketServer, 'daemonize', lambda *args, **kwargs: None) self.stubs.Set(select, 'select', self._mock_select_systemexit) soc = self._get_websockserver(daemon=True, ssl_only=0, idle_timeout=1, verbose=True) self.assertEqual(None, soc.start_server()) def test_WSRequestHandle_do_GET_nofile(self): request = 'GET /tmp.txt HTTP/0.9' with tempfile.NamedTemporaryFile() as test_file: test_file.write(request) test_file.flush() test_file.seek(0) con = MockConnection(test_file.name) soc = websocket.WSRequestHandler(con, "127.0.0.1", file_only=True) soc.path = '' soc.headers = {'upgrade': ''} self.stubs.Set(SimpleHTTPRequestHandler, 'send_response', lambda *args: None) soc.do_GET() self.assertEqual(404, soc.last_code) def test_WSRequestHandle_do_GET_hidden_resource(self): request = 'GET /tmp.txt HTTP/0.9' with tempfile.NamedTemporaryFile() as test_file: test_file.write(request) test_file.flush() test_file.seek(0) con = MockConnection(test_file.name) soc = websocket.WSRequestHandler(con, '127.0.0.1', no_parent=True) soc.path = test_file.name + '?' soc.headers = {'upgrade': ''} soc.webroot = 'no match startswith' self.stubs.Set(SimpleHTTPRequestHandler, 'send_response', lambda *args: None) soc.do_GET() self.assertEqual(403, soc.last_code) def testsocket_set_keepalive_options(self): keepcnt = 12 keepidle = 34 keepintvl = 56 sock = self.server.socket('localhost', tcp_keepcnt=keepcnt, tcp_keepidle=keepidle, tcp_keepintvl=keepintvl) self.assertEqual(sock.getsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT), keepcnt) self.assertEqual(sock.getsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE), keepidle) self.assertEqual(sock.getsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL), keepintvl) sock = self.server.socket('localhost', tcp_keepalive=False, tcp_keepcnt=keepcnt, tcp_keepidle=keepidle, tcp_keepintvl=keepintvl) self.assertNotEqual(sock.getsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT), keepcnt) self.assertNotEqual(sock.getsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE), keepidle) self.assertNotEqual(sock.getsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL), keepintvl) websockify-0.6.1+dfsg1/tests/test_websocketproxy.py000066400000000000000000000104361253263715700225450ustar00rootroot00000000000000# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright(c)2013 NTT corp. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Unit tests for websocketproxy """ import os import logging import select import shutil import stubout import subprocess import tempfile import time import unittest from websockify import websocketproxy class MockSocket(object): def __init__(*args, **kwargs): pass def shutdown(*args): pass def close(*args): pass class WebSocketProxyTest(unittest.TestCase): def _init_logger(self, tmpdir): name = 'websocket-unittest' logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) logger.propagate = True filename = "%s.log" % (name) handler = logging.FileHandler(filename) handler.setFormatter(logging.Formatter("%(message)s")) logger.addHandler(handler) def setUp(self): """Called automatically before each test.""" super(WebSocketProxyTest, self).setUp() self.soc = '' self.stubs = stubout.StubOutForTesting() # Temporary dir for test data self.tmpdir = tempfile.mkdtemp() # Put log somewhere persistent self._init_logger('./') # Mock this out cause it screws tests up self.stubs.Set(os, 'chdir', lambda *args, **kwargs: None) def tearDown(self): """Called automatically after each test.""" self.stubs.UnsetAll() shutil.rmtree(self.tmpdir) super(WebSocketProxyTest, self).tearDown() def _get_websockproxy(self, **kwargs): return websocketproxy.WebSocketProxy(key=self.tmpdir, web=self.tmpdir, record=self.tmpdir, **kwargs) def test_run_wrap_cmd(self): web_socket_proxy = self._get_websockproxy() web_socket_proxy.__dict__["wrap_cmd"] = "wrap_cmd" def mock_Popen(*args, **kwargs): return '_mock_cmd' self.stubs.Set(subprocess, 'Popen', mock_Popen) web_socket_proxy.run_wrap_cmd() self.assertEquals(web_socket_proxy.spawn_message, True) def test_started(self): web_socket_proxy = self._get_websockproxy() web_socket_proxy.__dict__["spawn_message"] = False web_socket_proxy.__dict__["wrap_cmd"] = "wrap_cmd" def mock_run_wrap_cmd(*args, **kwargs): web_socket_proxy.__dict__["spawn_message"] = True self.stubs.Set(web_socket_proxy, 'run_wrap_cmd', mock_run_wrap_cmd) web_socket_proxy.started() self.assertEquals(web_socket_proxy.__dict__["spawn_message"], True) def test_poll(self): web_socket_proxy = self._get_websockproxy() web_socket_proxy.__dict__["wrap_cmd"] = "wrap_cmd" web_socket_proxy.__dict__["wrap_mode"] = "respawn" web_socket_proxy.__dict__["wrap_times"] = [99999999] web_socket_proxy.__dict__["spawn_message"] = True web_socket_proxy.__dict__["cmd"] = None self.stubs.Set(time, 'time', lambda: 100000000.000) web_socket_proxy.poll() self.assertEquals(web_socket_proxy.spawn_message, False) def test_new_client(self): web_socket_proxy = self._get_websockproxy() web_socket_proxy.__dict__["verbose"] = "verbose" web_socket_proxy.__dict__["daemon"] = None web_socket_proxy.__dict__["client"] = "client" self.stubs.Set(web_socket_proxy, 'socket', MockSocket) def mock_select(*args, **kwargs): ins = None outs = None excepts = "excepts" return ins, outs, excepts self.stubs.Set(select, 'select', mock_select) self.assertRaises(Exception, web_socket_proxy.new_websocket_client) websockify-0.6.1+dfsg1/tests/tox.ini000066400000000000000000000010161253263715700173510ustar00rootroot00000000000000# Tox (http://tox.testrun.org/) is a tool for running tests # in multiple virtualenvs. This configuration file will run the # test suite on all supported python versions. To use it, "pip install tox" # and then run "tox" from this directory. [tox] envlist = py24,py25,py26,py27,py30 setupdir = ../ [testenv] commands = nosetests {posargs} deps = mox nose # At some point we should enable this since tox epdctes it to exist but # the code will need pep8ising first. #[testenv:pep8] #commands = flake8 #dep = flake8 websockify-0.6.1+dfsg1/tests/utf8-list.py000077500000000000000000000011451253263715700202550ustar00rootroot00000000000000#!/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.join(os.path.dirname(__file__), "..")) from websockify.websocket import WebSocketServer if __name__ == '__main__': print "val: hybi_base64 | hybi_binary" for c in range(0, 256): 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" % (c, repr(hybi_base64), repr(hybi_binary)) websockify-0.6.1+dfsg1/websockify.py000077700000000000000000000000001253263715700201372runustar00rootroot00000000000000websockify-0.6.1+dfsg1/websockify/000077500000000000000000000000001253263715700170435ustar00rootroot00000000000000websockify-0.6.1+dfsg1/websockify/__init__.py000066400000000000000000000000651253263715700211550ustar00rootroot00000000000000from websocket import * from websocketproxy import * websockify-0.6.1+dfsg1/websockify/websocket.py000066400000000000000000001121721253263715700214070ustar00rootroot00000000000000#!/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-ietf-hybi-thewebsocketprotocol-07 - http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10 - http://tools.ietf.org/html/rfc6455 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, select, logging 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 sha1 except: 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, msg in [('numpy', 'HyBi protocol will be slower'), ('ssl', 'TLS/SSL/wss is disabled'), ('multiprocessing', 'Multi-Processing is disabled'), ('resource', 'daemonizing is disabled')]: try: globals()[mod] = __import__(mod) except ImportError: globals()[mod] = None print("WARNING: no '%s' module, %s" % (mod, msg)) if multiprocessing and sys.platform == 'win32': # make sockets pickle-able/inheritable import multiprocessing.reduction # HTTP handler with WebSocket upgrade support class WebSocketRequestHandler(SimpleHTTPRequestHandler): """ WebSocket Request Handler Class, derived from SimpleHTTPRequestHandler. Must be sub-classed with new_websocket_client method definition. The request handler can be configured by setting optional attributes on the server object: * only_upgrade: If true, SimpleHTTPRequestHandler will not be enabled, only websocket is allowed. * verbose: If true, verbose logging is activated. * daemon: Running as daemon, do not write to console etc * record: Record raw frame data as JavaScript array into specified filename * run_once: Handle a single request * handler_id: A sequence number for this connection, appended to record filename """ buffer_size = 65536 GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" server_version = "WebSockify" protocol_version = "HTTP/1.1" # An exception while the WebSocket client was connected class CClose(Exception): pass def __init__(self, req, addr, server): # Retrieve a few configuration variables from the server self.only_upgrade = getattr(server, "only_upgrade", False) self.verbose = getattr(server, "verbose", False) self.daemon = getattr(server, "daemon", False) self.record = getattr(server, "record", False) self.run_once = getattr(server, "run_once", False) self.rec = None self.handler_id = getattr(server, "handler_id", False) self.file_only = getattr(server, "file_only", False) self.traffic = getattr(server, "traffic", False) self.logger = getattr(server, "logger", None) if self.logger is None: self.logger = WebSocketServer.get_logger() SimpleHTTPRequestHandler.__init__(self, req, addr, server) @staticmethod def unmask(buf, hlen, plen): pstart = hlen + 4 pend = pstart + plen if numpy: b = c = s2b('') if plen >= 4: mask = numpy.frombuffer(buf, dtype=numpy.dtype('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) #self.msg("Encoded: %s", repr(header + buf)) return header + buf, len(header), 0 @staticmethod def decode_hybi(buf, base64=False, logger=None): """ Decode HyBi style WebSocket packets. Returns: {'fin' : 0_or_1, 'opcode' : number, 'masked' : boolean, '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, 'masked' : False, 'hlen' : 2, 'length' : 0, 'payload' : None, 'left' : 0, 'close_code' : 1000, 'close_reason' : ''} if logger is None: logger = WebSocketServer.get_logger() 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 f['masked'] = (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'] + f['masked'] * 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 f['masked']: # unmask payload f['payload'] = WebSocketRequestHandler.unmask(buf, f['hlen'], f['length']) else: logger.debug("Unmasked frame: %s" % repr(buf)) f['payload'] = buf[(f['hlen'] + f['masked'] * 4):full_len] if base64 and f['opcode'] in [1, 2]: try: f['payload'] = b64decode(f['payload']) except: logger.exception("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 # # WebSocketRequestHandler logging/output functions # def print_traffic(self, token="."): """ Show traffic flow mode. """ if self.traffic: sys.stdout.write(token) sys.stdout.flush() def msg(self, msg, *args, **kwargs): """ Output message with handler_id prefix. """ prefix = "% 3d: " % self.handler_id self.logger.log(logging.INFO, "%s%s" % (prefix, msg), *args, **kwargs) def vmsg(self, msg, *args, **kwargs): """ Same as msg() but as debug. """ prefix = "% 3d: " % self.handler_id self.logger.log(logging.DEBUG, "%s%s" % (prefix, msg), *args, **kwargs) def warn(self, msg, *args, **kwargs): """ Same as msg() but as warning. """ prefix = "% 3d: " % self.handler_id self.logger.log(logging.WARN, "%s%s" % (prefix, msg), *args, **kwargs) # # Main WebSocketRequestHandler 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.base64: encbuf, lenhead, lentail = self.encode_hybi(buf, opcode=1, base64=True) else: encbuf, lenhead, lentail = self.encode_hybi(buf, opcode=2, base64=False) if self.rec: self.rec.write("%s,\n" % repr("{%s{" % tdelta + encbuf[lenhead:len(encbuf)-lentail])) self.send_parts.append(encbuf) while self.send_parts: # Send pending frames buf = self.send_parts.pop(0) sent = self.request.send(buf) if sent == len(buf): self.print_traffic("<") else: self.print_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.request.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: frame = self.decode_hybi(buf, base64=self.base64, logger=self.logger) #self.msg("Received buf: %s, frame: %s", repr(buf), frame) if frame['payload'] == None: # Incomplete/partial frame self.print_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 self.print_traffic("}") if self.rec: start = frame['hlen'] end = frame['hlen'] + frame['length'] if frame['masked']: recbuf = WebSocketRequestHandler.unmask(buf, frame['hlen'], frame['length']) else: recbuf = buf[frame['hlen']:frame['hlen'] + frame['length']] self.rec.write("%s,\n" % repr("}%s}" % tdelta + recbuf)) 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. """ msg = pack(">H%ds" % len(reason), code, reason) buf, h, t = self.encode_hybi(msg, opcode=0x08, base64=False) self.request.send(buf) def do_websocket_handshake(self): h = self.headers 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: self.send_error(400, "Unsupported protocol version %s" % ver) return False 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: self.send_error(400, "Client must support 'binary' or 'base64' protocol") return False # Generate the hash value for the accept header accept = b64encode(sha1(s2b(key + self.GUID)).digest()) self.send_response(101, "Switching Protocols") self.send_header("Upgrade", "websocket") self.send_header("Connection", "Upgrade") self.send_header("Sec-WebSocket-Accept", b2s(accept)) if self.base64: self.send_header("Sec-WebSocket-Protocol", "base64") else: self.send_header("Sec-WebSocket-Protocol", "binary") self.end_headers() return True else: self.send_error(400, "Missing Sec-WebSocket-Version header. Hixie protocols not supported.") return False def handle_websocket(self): """Upgrade a connection to Websocket, if requested. If this succeeds, new_websocket_client() will be called. Otherwise, False is returned. """ if (self.headers.get('upgrade') and self.headers.get('upgrade').lower() == 'websocket'): if not self.do_websocket_handshake(): return False # Indicate to server that a Websocket upgrade was done self.server.ws_connection = True # Initialize per client settings self.send_parts = [] self.recv_part = None self.start_time = int(time.time()*1000) # client_address is empty with, say, UNIX domain sockets client_addr = "" is_ssl = False try: client_addr = self.client_address[0] is_ssl = self.client_address[2] except IndexError: pass if is_ssl: self.stype = "SSL/TLS (wss://)" else: self.stype = "Plain non-SSL (ws://)" self.log_message("%s: %s WebSocket connection" % (client_addr, self.stype)) self.log_message("%s: Version %s, base64: '%s'" % (client_addr, self.version, self.base64)) if self.path != '/': self.log_message("%s: Path: '%s'" % (client_addr, self.path)) if self.record: # Record raw frame data as JavaScript array fname = "%s.%s" % (self.record, self.handler_id) self.log_message("opening record file: %s" % fname) self.rec = open(fname, 'w+') encoding = "binary" if self.base64: encoding = "base64" self.rec.write("var VNC_frame_encoding = '%s';\n" % encoding) self.rec.write("var VNC_frame_data = [\n") try: self.new_websocket_client() except self.CClose: # Close the client _, exc, _ = sys.exc_info() self.send_close(exc.args[0], exc.args[1]) return True else: return False def do_GET(self): """Handle GET request. Calls handle_websocket(). If unsuccessful, and web server is enabled, SimpleHTTPRequestHandler.do_GET will be called.""" if not self.handle_websocket(): if self.only_upgrade: self.send_error(405, "Method Not Allowed") else: SimpleHTTPRequestHandler.do_GET(self) def list_directory(self, path): if self.file_only: self.send_error(404, "No such file") else: return SimpleHTTPRequestHandler.list_directory(self, path) def new_websocket_client(self): """ Do something with a WebSockets client connection. """ raise Exception("WebSocketRequestHandler.new_websocket_client() must be overloaded") def do_HEAD(self): if self.only_upgrade: self.send_error(405, "Method Not Allowed") else: SimpleHTTPRequestHandler.do_HEAD(self) def finish(self): if self.rec: self.rec.write("'EOF'];\n") self.rec.close() def handle(self): # When using run_once, we have a single process, so # we cannot loop in BaseHTTPRequestHandler.handle; we # must return and handle new connections if self.run_once: self.handle_one_request() else: SimpleHTTPRequestHandler.handle(self) def log_request(self, code='-', size='-'): if self.verbose: SimpleHTTPRequestHandler.log_request(self, code, size) class WebSocketServer(object): """ WebSockets server class. As an alternative, the standard library SocketServer can be used """ policy_response = """\n""" log_prefix = "websocket" # An exception before the WebSocket connection was established class EClose(Exception): pass class Terminate(Exception): pass def __init__(self, RequestHandlerClass, listen_host='', listen_port=None, source_is_ipv6=False, verbose=False, cert='', key='', ssl_only=None, daemon=False, record='', web='', file_only=False, run_once=False, timeout=0, idle_timeout=0, traffic=False, tcp_keepalive=True, tcp_keepcnt=None, tcp_keepidle=None, tcp_keepintvl=None): # settings self.RequestHandlerClass = RequestHandlerClass 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.traffic = traffic self.file_only = file_only self.launch_time = time.time() self.ws_connection = False self.handler_id = 1 self.logger = self.get_logger() self.tcp_keepalive = tcp_keepalive self.tcp_keepcnt = tcp_keepcnt self.tcp_keepidle = tcp_keepidle self.tcp_keepintvl = tcp_keepintvl # 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) self.only_upgrade = not 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 self.msg("WebSocket server settings:") self.msg(" - Listen on %s:%s", self.listen_host, self.listen_port) self.msg(" - Flash security policy server") if self.web: if self.file_only: self.msg(" - Web server (no directory listings). Web root: %s", self.web) else: self.msg(" - Web server. Web root: %s", self.web) if ssl: if os.path.exists(self.cert): self.msg(" - SSL/TLS support") if self.ssl_only: self.msg(" - Deny non-SSL/TLS connections") else: self.msg(" - No SSL/TLS support (no cert file)") else: self.msg(" - No SSL/TLS support (no 'ssl' module)") if self.daemon: self.msg(" - Backgrounding (daemon)") if self.record: self.msg(" - Recording to '%s.*'", self.record) # # WebSocketServer static methods # @staticmethod def get_logger(): return logging.getLogger("%s.%s" % ( WebSocketServer.log_prefix, WebSocketServer.__class__.__name__)) @staticmethod def socket(host, port=None, connect=False, prefer_ipv6=False, unix_socket=None, use_ssl=False, tcp_keepalive=True, tcp_keepcnt=None, tcp_keepidle=None, tcp_keepintvl=None): """ 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 tcp_keepalive: sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) if tcp_keepcnt: sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, tcp_keepcnt) if tcp_keepidle: sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, tcp_keepidle) if tcp_keepintvl: sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, tcp_keepintvl) 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 signal.signal(signal.SIGTERM, signal.SIG_IGN) 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()) 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. """ 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("")): # 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 elif self.ssl_only: raise self.EClose("non-SSL connection received but disallowed") else: retsock = sock # If the address is like (host, port), we are extending it # with a flag indicating SSL. Not many other options # available... if len(address) == 2: address = (address[0], address[1], (retsock != sock)) self.RequestHandlerClass(retsock, address, self) # Return the WebSockets socket which may be SSL wrapped return retsock # # WebSocketServer logging/output functions # def msg(self, *args, **kwargs): """ Output message as info """ self.logger.log(logging.INFO, *args, **kwargs) def vmsg(self, *args, **kwargs): """ Same as msg() but as debug. """ self.logger.log(logging.DEBUG, *args, **kwargs) def warn(self, *args, **kwargs): """ Same as msg() but as warning. """ self.logger.log(logging.WARN, *args, **kwargs) # # 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 terminate(self): raise self.Terminate() def multiprocessing_SIGCHLD(self, sig, stack): self.vmsg('Reaing zombies, active child count is %s', len(multiprocessing.active_children())) 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") self.terminate() def do_SIGTERM(self, sig, stack): self.msg("Got SIGTERM, exiting") self.terminate() def top_new_client(self, startsock, address): """ Do something with a WebSockets client connection. """ # handler process client = None try: try: client = self.do_handshake(startsock, address) 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 WebSocketServer.Terminate: raise except Exception: _, exc, _ = sys.exc_info() self.msg("handler exception: %s" % str(exc)) self.vmsg("exception", exc_info=True) finally: if client and client != startsock: # Close the SSL wrapped socket # Original socket closed by caller client.close() 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_websocket_client() method (which must be overridden) for each new client connection. """ lsock = self.socket(self.listen_host, self.listen_port, False, self.prefer_ipv6, tcp_keepalive=self.tcp_keepalive, tcp_keepcnt=self.tcp_keepcnt, tcp_keepidle=self.tcp_keepidle, tcp_keepintvl=self.tcp_keepintvl) if self.daemon: self.daemonize(keepfd=lsock.fileno(), chdir=self.web) self.started() # Some things need to happen after daemonizing # Allow override of signals original_signals = { signal.SIGINT: signal.getsignal(signal.SIGINT), signal.SIGTERM: signal.getsignal(signal.SIGTERM), signal.SIGCHLD: signal.getsignal(signal.SIGCHLD), } signal.signal(signal.SIGINT, self.do_SIGINT) signal.signal(signal.SIGTERM, self.do_SIGTERM) if not multiprocessing: # os.fork() (python 2.4) child reaper signal.signal(signal.SIGCHLD, self.fallback_SIGCHLD) else: # make sure that _cleanup is called when children die # by calling active_children on SIGCHLD signal.signal(signal.SIGCHLD, self.multiprocessing_SIGCHLD) last_active_time = self.launch_time try: while True: try: try: startsock = None pid = err = 0 child_count = 0 if multiprocessing: # Collect zombie child processes 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 self.Terminate: raise 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 (self.Terminate, SystemExit, KeyboardInterrupt): self.msg("In exit") break except Exception: self.msg("handler exception: %s", str(exc)) self.vmsg("exception", exc_info=True) finally: if startsock: startsock.close() finally: # Close listen port self.vmsg("Closing socket listening at %s:%s", self.listen_host, self.listen_port) lsock.close() # Restore signals for sig, func in original_signals.items(): signal.signal(sig, func) websockify-0.6.1+dfsg1/websockify/websocketproxy.py000077500000000000000000000424031253263715700225130ustar00rootroot00000000000000#!/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, logging try: from socketserver import ForkingMixIn except: from SocketServer import ForkingMixIn try: from http.server import HTTPServer except: from BaseHTTPServer import HTTPServer from select import select import websocket try: from urllib.parse import parse_qs, urlparse except: from cgi import parse_qs from urlparse import urlparse class ProxyRequestHandler(websocket.WebSocketRequestHandler): traffic_legend = """ Traffic Legend: } - Client receive }. - Client receive partial { - Target receive > - Target send >. - Target send partial < - Client send <. - Client send partial """ def new_websocket_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.server.target_cfg: (self.server.target_host, self.server.target_port) = self.get_target(self.server.target_cfg, self.path) # Connect to the target if self.server.wrap_cmd: msg = "connecting to command: '%s' (port %s)" % (" ".join(self.server.wrap_cmd), self.server.target_port) elif self.server.unix_target: msg = "connecting to unix socket: %s" % self.server.unix_target else: msg = "connecting to: %s:%s" % ( self.server.target_host, self.server.target_port) if self.server.ssl_target: msg += " (using SSL)" self.log_message(msg) tsock = websocket.WebSocketServer.socket(self.server.target_host, self.server.target_port, connect=True, use_ssl=self.server.ssl_target, unix_socket=self.server.unix_target) self.print_traffic(self.traffic_legend) # Start proxying try: self.do_proxy(tsock) except: if tsock: tsock.shutdown(socket.SHUT_RDWR) tsock.close() if self.verbose: self.log_message("%s:%s: Closed target" %( self.server.target_host, self.server.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 args.has_key('token') or 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.request, target] while True: wlist = [] if tqueue: wlist.append(target) if cqueue or c_pend: wlist.append(self.request) ins, outs, excepts = select(rlist, wlist, [], 1) if excepts: raise Exception("Socket exception") if self.request in outs: # Send queued target data to the client c_pend = self.send_frames(cqueue) cqueue = [] if self.request 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? if self.verbose: self.log_message("%s:%s: Client closed connection" %( self.server.target_host, self.server.target_port)) raise self.CClose(closed['code'], closed['reason']) if target in outs: # Send queued client data to the target dat = tqueue.pop(0) sent = target.send(dat) if sent == len(dat): self.print_traffic(">") else: # requeue the remaining data tqueue.insert(0, dat[sent:]) self.print_traffic(".>") if target in ins: # Receive target data, encode it and queue for client buf = target.recv(self.buffer_size) if len(buf) == 0: if self.verbose: self.log_message("%s:%s: Target closed connection" %( self.server.target_host, self.server.target_port)) raise self.CClose(1000, "Target closed") cqueue.append(buf) self.print_traffic("{") 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 def __init__(self, RequestHandlerClass=ProxyRequestHandler, *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: wsdir = os.path.dirname(sys.argv[0]) rebinder_path = [os.path.join(wsdir, "..", "lib"), os.path.join(wsdir, "..", "lib", "websockify"), wsdir] 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)}) websocket.WebSocketServer.__init__(self, RequestHandlerClass, *args, **kwargs) def run_wrap_cmd(self): self.msg("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)" self.msg("%s", msg) 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: self.warn("Command respawning too fast") self.spawn_message = False else: self.run_wrap_cmd() 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 logger_init(): logger = logging.getLogger(WebSocketProxy.log_prefix) logger.propagate = False logger.setLevel(logging.INFO) h = logging.StreamHandler() h.setLevel(logging.DEBUG) h.setFormatter(logging.Formatter("%(message)s")) logger.addHandler(h) def websockify_init(): logger_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") parser.add_option("--traffic", action="store_true", help="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") parser.add_option("--libserver", action="store_true", help="use Python library SocketServer engine") (opts, args) = parser.parse_args() if opts.verbose: logging.getLogger(WebSocketProxy.log_prefix).setLevel(logging.DEBUG) # 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") # Transform to absolute path as daemon may chdir if opts.target_cfg: opts.target_cfg = os.path.abspath(opts.target_cfg) # Create and start the WebSockets proxy libserver = opts.libserver del opts.libserver if libserver: # Use standard Python SocketServer framework server = LibProxyServer(**opts.__dict__) server.serve_forever() else: # Use internal service framework server = WebSocketProxy(**opts.__dict__) server.start_server() class LibProxyServer(ForkingMixIn, HTTPServer): """ Just like WebSocketProxy, but uses standard Python SocketServer framework. """ def __init__(self, RequestHandlerClass=ProxyRequestHandler, **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) self.daemon = False self.target_cfg = None # Server configuration listen_host = kwargs.pop('listen_host', '') listen_port = kwargs.pop('listen_port', None) web = kwargs.pop('web', '') # Configuration affecting base request handler self.only_upgrade = not web self.verbose = kwargs.pop('verbose', False) record = kwargs.pop('record', '') if record: self.record = os.path.abspath(record) self.run_once = kwargs.pop('run_once', False) self.handler_id = 0 for arg in kwargs.keys(): print("warning: option %s ignored when using --libserver" % arg) if web: os.chdir(web) HTTPServer.__init__(self, (listen_host, listen_port), RequestHandlerClass) def process_request(self, request, client_address): """Override process_request to implement a counter""" self.handler_id += 1 ForkingMixIn.process_request(self, request, client_address) if __name__ == '__main__': websockify_init() websockify-0.6.1+dfsg1/wsirc.html000066400000000000000000000064731253263715700167250ustar00rootroot00000000000000 IRC Client using WebSockets Host:   Port:   Encrypt:  
Nick:  
Channel: # 

> websockify-0.6.1+dfsg1/wstelnet.html000066400000000000000000000046061253263715700174370ustar00rootroot00000000000000 Telnet client using WebSockets Host:   Port:   Encrypt: