diff -Nru websockify-0.3.0/CHANGES.txt websockify-0.5.1+dfsg1/CHANGES.txt --- websockify-0.3.0/CHANGES.txt 2013-01-15 17:25:32.000000000 +0000 +++ websockify-0.5.1+dfsg1/CHANGES.txt 2013-09-12 14:43:43.000000000 +0000 @@ -1,6 +1,29 @@ Changes ======= +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 -------------------- diff -Nru websockify-0.3.0/cserv.py websockify-0.5.1+dfsg1/cserv.py --- websockify-0.3.0/cserv.py 2012-10-11 19:31:34.000000000 +0000 +++ websockify-0.5.1+dfsg1/cserv.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -import argparse -import random -import os - -import cherrypy - -from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool -from ws4py.websocket import WebSocket -from ws4py.messaging import TextMessage - -class ChatWebSocketHandler(WebSocket): - def received_message(self, m): - cherrypy.engine.publish('websocket-broadcast', m) - - def closed(self, code, reason="A client left the room without a proper explanation."): - cherrypy.engine.publish('websocket-broadcast', TextMessage(reason)) - -class Root(object): - def __init__(self, host, port, ssl=False): - self.host = host - self.port = port - - @cherrypy.expose - def ws(self): - cherrypy.log("Handler created: %s" % repr(cherrypy.request.ws_handler)) - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description='Echo CherryPy Server') - parser.add_argument('--host', default='127.0.0.1') - parser.add_argument('-p', '--port', default=9000, type=int) - parser.add_argument('--ssl', action='store_true') - args = parser.parse_args() - - cherrypy.config.update({'server.socket_host': args.host, - 'server.socket_port': args.port, - 'tools.staticdir.root': os.path.abspath(os.path.dirname(__file__))}) - - if args.ssl: - cherrypy.config.update({'server.ssl_certificate': './server.crt', - 'server.ssl_private_key': './server.key'}) - - WebSocketPlugin(cherrypy.engine).subscribe() - cherrypy.tools.websocket = WebSocketTool() - - cherrypy.quickstart(Root(args.host, args.port, args.ssl), '', config={ - '/ws': { - 'tools.websocket.on': True, - 'tools.websocket.handler_cls': ChatWebSocketHandler - }, - '/': { - 'tools.staticdir.on': True, - 'tools.staticdir.dir': '.' - } - } - ) diff -Nru websockify-0.3.0/debian/changelog websockify-0.5.1+dfsg1/debian/changelog --- websockify-0.3.0/debian/changelog 2013-02-08 09:15:43.000000000 +0000 +++ websockify-0.5.1+dfsg1/debian/changelog 2014-08-15 07:06:12.000000000 +0000 @@ -1,36 +1,75 @@ -websockify (0.3.0-0ubuntu1~cloud0) precise-grizzly; urgency=low +websockify (0.5.1+dfsg1-3ubuntu0.14.04.1~cloud0) precise-icehouse; urgency=medium * New update for the Ubuntu Cloud Archive. - -- James Page Fri, 08 Feb 2013 09:15:43 +0000 + -- Openstack Ubuntu Testing Bot Fri, 15 Aug 2014 03:06:12 -0400 -websockify (0.3.0-0ubuntu1) raring; urgency=low +websockify (0.5.1+dfsg1-3ubuntu0.14.04.1) trusty; urgency=medium - * New upstream release. - * debian/patches/add-missing-files.patch: Add missing files - due to a bad Manifest.inf - * debian/control: Add depends on pyhton-numpy. + * Fixup handling of child processes to avoid zombies (LP: #1350352): + - d/p/avoid-zombies.patch, + d/p/handle-multiprocessing.patch: Cherry picked fixes from upstream + VCS to handle signals to child processes correctly. - -- Chuck Short Tue, 29 Jan 2013 08:21:35 -0600 + -- James Page Thu, 31 Jul 2014 14:40:12 +0100 -websockify (0.2~20121002-0ubuntu1) quantal; urgency=low +websockify (0.5.1+dfsg1-3) unstable; urgency=low - * New upstream release. (LP: #1060374) + * Fixes the shell wrapper for rebind. Thanks to Philipp Hahn + for reporting and his fix (Closes: #726304). + * Cleans correctly, and allow 2 builds in a raw. - -- Chuck Short Tue, 02 Oct 2012 13:39:54 -0500 + -- Thomas Goirand Sun, 08 Dec 2013 06:20:11 +0000 -websockify (0.1.0~20120906-0ubuntu2) quantal; urgency=low +websockify (0.5.1+dfsg1-2) unstable; urgency=low - [ Chuck Short ] - * debian/control: Drop python-numpy. + * Added upstream patch to fix rebind.so not found (Closes: #719889). - [Vish Ishaya] - * debian/rules, debian/install: Add missing files. + -- Thomas Goirand Sat, 28 Sep 2013 22:45:51 +0800 - -- Chuck Short Mon, 17 Sep 2012 13:57:40 -0500 +websockify (0.5.1+dfsg1-1) unstable; urgency=low -websockify (0.1.0~20120906-0ubuntu1) quantal; urgency=low + * New upstream release. + * Ran wrap-and-sort. + * Do not install include/web-socket-js/WebSocketMain.swf in setup.py + (patches setup.py). - * Initial release. + -- Thomas Goirand Thu, 30 May 2013 16:00:31 +0800 - -- Chuck Short Thu, 06 Sep 2012 13:45:48 -0500 +websockify (0.3.0+dfsg1-6) unstable; urgency=low + + * Uploading to unstable. + + -- Thomas Goirand Mon, 13 May 2013 08:15:02 +0000 + +websockify (0.3.0+dfsg1-5) experimental; urgency=low + + * Really adds build-depends: openstack-pkg-tools. + + -- Thomas Goirand Mon, 29 Apr 2013 13:38:29 +0000 + +websockify (0.3.0+dfsg1-4) experimental; urgency=low + + * Added missing build-dependency: openstack-pkg-tools. + + -- Thomas Goirand Mon, 29 Apr 2013 20:50:49 +0800 + +websockify (0.3.0+dfsg1-3) experimental; urgency=low + + * The breaks + replaces now include the novnc epoch (this was missing in + previous upload), thanks to Jeremy Bicha for reporting (Closes: #706357). + + -- Thomas Goirand Mon, 29 Apr 2013 18:08:34 +0800 + +websockify (0.3.0+dfsg1-2) experimental; urgency=low + + * Added Breaks: + Replaces: novnc (<< 0.4+dfsg+1-6) since websockify now + holds the /usr/bin/websockify and /usr/bin/rebind binaries. + + -- Thomas Goirand Fri, 12 Apr 2013 16:35:29 +0000 + +websockify (0.3.0+dfsg1-1) experimental; urgency=low + + * Initial release. (Closes: #701822). + + -- Thomas Goirand Sat, 23 Feb 2013 01:22:51 +0800 diff -Nru websockify-0.3.0/debian/compat websockify-0.5.1+dfsg1/debian/compat --- websockify-0.3.0/debian/compat 2012-09-06 18:45:50.000000000 +0000 +++ websockify-0.5.1+dfsg1/debian/compat 2013-12-08 06:27:05.000000000 +0000 @@ -1 +1 @@ -8 +9 diff -Nru websockify-0.3.0/debian/control websockify-0.5.1+dfsg1/debian/control --- websockify-0.3.0/debian/control 2013-01-29 14:30:44.000000000 +0000 +++ websockify-0.5.1+dfsg1/debian/control 2014-07-31 13:23:07.000000000 +0000 @@ -1,17 +1,49 @@ Source: websockify Section: python Priority: optional -Maintainer: Chuck Short -Build-Depends: debhelper (>= 8.0.0), python-setuptools, python-dev (>= 2.6.6-3~) -Standards-Version: 3.9.3 +Maintainer: Ubuntu Developers +XSBC-Original-Maintainer: PKG OpenStack +Uploaders: Loic Dachary (OuoU) , + Julien Danjou , + Thomas Goirand , + Ghe Rivero , + Mehdi Abaakouk +Build-Depends: debhelper (>= 9), + openstack-pkg-tools, + python-dev (>= 2.6.6-3~), + python-setuptools +Standards-Version: 3.9.4 +Vcs-Browser: http://anonscm.debian.org/gitweb/?p=openstack/websockify.git +Vcs-Git: git://anonscm.debian.org/openstack/websockify.git +Homepage: https://pypi.python.org/pypi/websockify Package: websockify Architecture: any -Depends: ${python:Depends}, ${misc:Depends}, python-numpy -Description: WebSocket to TCP proxy/bridge. +Pre-Depends: dpkg (>= 1.15.6~) +Depends: python-numpy, ${misc:Depends}, ${python:Depends}, ${shlibs:Depends} +Breaks: novnc (<< 1:0.4+dfsg+1-6) +Replaces: novnc (<< 1:0.4+dfsg+1-6) +Description: WebSockets support for any application/server websockify was formerly named wsproxy and was part of the 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. + 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. + . + 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. + . + With Hixie clients, Websockify uses base64 to encode all traffic to and from + the client. This does not affect the data between websockify and the server. + . + With HyBi clients, 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. diff -Nru websockify-0.3.0/debian/copyright websockify-0.5.1+dfsg1/debian/copyright --- websockify-0.3.0/debian/copyright 2012-09-10 13:44:11.000000000 +0000 +++ websockify-0.5.1+dfsg1/debian/copyright 2013-12-08 06:27:05.000000000 +0000 @@ -2,85 +2,438 @@ Upstream-Name: websockify Source: https://github.com/kanaka/websockify +Files: debian/* +Copyright: (c) 2012, Canonical Ltd + (c) 2013, Thomas Goirand +License: GPL-2+ + Files: * -Copyright: 2012 Joel Martin -License: GPL-3 - 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. +Copyright: Ed Schouten + Algervivien + Joel Martin + Karim Allah Ahmed + Chris Gordon + Vishvananda Ishaya + Thomas Goirand + primalmotion + Kevin Chan + Cédric de Saint Martin + Aric Stewart + Amir Malik + Alexandre Sicard + Vivien Alger + Tomas Edwardsson + mostafa sameh + Jodok Batlogg + Hector Sanjuan + François Revol + Daniel Shields + Chris Custine + Antoine Mercadal +License: LGPL-3 + +Files: include/util.js include/websock.js include/webutil.js + tests/include/util.js tests/include/websock.js tests/include/webutil.js +Copyright: (c) 2012 Joel Martin +License: MPL-2.0 Files: include/base64.js Copyright: 2000 Digital Creations 2 Inc -License: MPL - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - for the specific language governing rights and limitations under the - License. +License: MPL-2.0 -Files: include/web-socket-js/ +Files: include/VT100.js +Copyright: (c) Frank Bi +License: LGPL-2 + +Files: include/web-socket-js/* Copyright: 2012 Hiroshi Ichikawa -License: BSD - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - . - Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - . - Redistributions in binary form must reproduce the above copyright notice, this list of - conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - . - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS - BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +License: BSD-2-clauses Files: other/kumina.c -Copyright: 2010 Joel Martin -License: BSD +Copyright: (c) 2010, Joel Martin +License: BSD-2-clauses + +License: LGPL-2 + This library is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free + Software Foundation; version 2 of the License. + . + This library is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + details. + . + You should have received a copy of the GNU Lesser General Public License along + with this library; if not, write to the Free Software Foundation, Inc., 51 + Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + . + On Debian systems, the complete text of the GNU Lesser General Public License + (LGPL) may be found in /usr/share/common-licenses/LGPL-2. + +License: BSD-2-clauses Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - . - THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. + modification, are permitted provided that the following conditions are met: + . + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + . + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + . + THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License: LGPL-3 + This library is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free + Software Foundation; version 3 of the License. + . + This library is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + details. + . + You should have received a copy of the GNU Lesser General Public License along + with this library; if not, write to the Free Software Foundation, Inc., 51 + Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + . + On Debian systems, the complete text of the GNU Lesser General Public License + (LGPL) may be found in /usr/share/common-licenses/LGPL-3. -Files: debian/* -Copyright: 2012 Canonical Ltd License: GPL-2+ - This package is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - . - This package is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This package is free software; you can redistribute it and/or modify it under + the terms of the GNU General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + . + This package is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + . + You should have received a copy of the GNU General Public License along with + this program. If not, see + . + On Debian systems, the complete text of the GNU General Public License version + 2 can be found in "/usr/share/common-licenses/GPL-2". + +License: MPL-2.0 + This Source Code 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/. + . + Mozilla 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. . - You should have received a copy of the GNU General Public License - along with this program. If not, see + Exhibit B - "Incompatible With Secondary Licenses" Notice . - On Debian systems, the complete text of the GNU General - Public License version 2 can be found in "/usr/share/common-licenses/GPL-2". + This Source Code Form is "Incompatible With Secondary Licenses", as defined + by the Mozilla Public License, v. 2.0. diff -Nru websockify-0.3.0/debian/docs websockify-0.5.1+dfsg1/debian/docs --- websockify-0.3.0/debian/docs 2012-09-06 18:45:50.000000000 +0000 +++ websockify-0.5.1+dfsg1/debian/docs 2013-12-08 06:27:05.000000000 +0000 @@ -1,3 +1,2 @@ CHANGES.txt -LICENSE.txt README.md diff -Nru websockify-0.3.0/debian/gbp.conf websockify-0.5.1+dfsg1/debian/gbp.conf --- websockify-0.3.0/debian/gbp.conf 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/debian/gbp.conf 2013-12-08 06:27:05.000000000 +0000 @@ -0,0 +1,8 @@ +[DEFAULT] +upstream-branch = master +debian-branch = debian/unstable +upstream-tag = %(version)s +compression = xz + +[git-buildpackage] +export-dir = ../build-area/ diff -Nru websockify-0.3.0/debian/install websockify-0.5.1+dfsg1/debian/install --- websockify-0.3.0/debian/install 2012-09-17 20:02:59.000000000 +0000 +++ websockify-0.5.1+dfsg1/debian/install 2013-12-08 06:27:05.000000000 +0000 @@ -1,5 +1,5 @@ -rebind.so usr/lib/websockify -rebind.o usr/lib/websockify rebind usr/bin +rebind.o usr/lib/websockify +rebind.so usr/lib/websockify usr/bin/websockify usr/lib/python*/dist-packages/* diff -Nru websockify-0.3.0/debian/manpages websockify-0.5.1+dfsg1/debian/manpages --- websockify-0.3.0/debian/manpages 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/debian/manpages 2013-12-08 06:27:05.000000000 +0000 @@ -0,0 +1 @@ +docs/websockify.1 diff -Nru websockify-0.3.0/debian/patches/add-missing-files.patch websockify-0.5.1+dfsg1/debian/patches/add-missing-files.patch --- websockify-0.3.0/debian/patches/add-missing-files.patch 2013-01-29 14:27:12.000000000 +0000 +++ websockify-0.5.1+dfsg1/debian/patches/add-missing-files.patch 1970-01-01 00:00:00.000000000 +0000 @@ -1,135 +0,0 @@ -diff -Naurp websockify-0.3.0.orig/Makefile websockify-0.3.0/Makefile ---- websockify-0.3.0.orig/Makefile 1969-12-31 18:00:00.000000000 -0600 -+++ websockify-0.3.0/Makefile 2013-01-29 08:17:43.017495421 -0600 -@@ -0,0 +1,11 @@ -+TARGETS=rebind.so -+CFLAGS += -fPIC -+ -+all: $(TARGETS) -+ -+rebind.so: rebind.o -+ $(CC) $(LDFLAGS) $^ -shared -fPIC -ldl -o $@ -+ -+clean: -+ rm -f rebind.o rebind.so -+ -diff -Naurp websockify-0.3.0.orig/rebind websockify-0.3.0/rebind ---- websockify-0.3.0.orig/rebind 1969-12-31 18:00:00.000000000 -0600 -+++ websockify-0.3.0/rebind 2013-01-29 08:17:43.049495420 -0600 -@@ -0,0 +1,18 @@ -+#!/usr/bin/env bash -+ -+usage() { -+ echo "Usage: $(basename $0) OLD_PORT NEW_PORT COMMAND_LINE" -+ echo -+ echo "Launch COMMAND_LINE, but intercept system calls to bind" -+ echo "to OLD_PORT and instead bind them to localhost:NEW_PORT" -+ exit 2 -+} -+ -+# Parameter defaults -+mydir=$(readlink -f $(dirname ${0})) -+ -+export REBIND_PORT_OLD="${1}"; shift -+export REBIND_PORT_NEW="${1}"; shift -+ -+LD_PRELOAD=${mydir}/rebind.so "${@}" -+ -diff -Naurp websockify-0.3.0.orig/rebind.c websockify-0.3.0/rebind.c ---- websockify-0.3.0.orig/rebind.c 1969-12-31 18:00:00.000000000 -0600 -+++ websockify-0.3.0/rebind.c 2013-01-29 08:17:43.049495420 -0600 -@@ -0,0 +1,94 @@ -+/* -+ * rebind: Intercept bind calls and bind to a different port -+ * Copyright 2010 Joel Martin -+ * Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) -+ * -+ * Overload (LD_PRELOAD) bind system call. If REBIND_PORT_OLD and -+ * REBIND_PORT_NEW environment variables are set then bind on the new -+ * port (of localhost) instead of the old port. -+ * -+ * This allows a proxy (such as wsproxy) to run on the old port and translate -+ * traffic to/from the new port. -+ * -+ * Usage: -+ * LD_PRELOAD=./rebind.so \ -+ * REBIND_PORT_OLD=23 \ -+ * REBIND_PORT_NEW=2023 \ -+ * program -+ */ -+ -+//#define DO_DEBUG 1 -+ -+#include -+#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; -+} diff -Nru websockify-0.3.0/debian/patches/avoid-zombies.patch websockify-0.5.1+dfsg1/debian/patches/avoid-zombies.patch --- websockify-0.3.0/debian/patches/avoid-zombies.patch 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/debian/patches/avoid-zombies.patch 2014-07-31 12:58:57.000000000 +0000 @@ -0,0 +1,31 @@ +From 354dd6b0a216cb7ee49f0ec39aa57fa7f96990f7 Mon Sep 17 00:00:00 2001 +From: directxman12 +Date: Fri, 20 Sep 2013 14:12:35 -0400 +Subject: [PATCH] Enable Process Reaping in All Conditions + +Process reaping via the SIGCHLD handler is now enabled in all +circumstances, instead of just when os.fork is being used. + +Fixes #95 +--- + websockify/websocket.py | 4 +--- + 1 file changed, 1 insertion(+), 3 deletions(-) + +diff --git a/websockify/websocket.py b/websockify/websocket.py +index d37fa71..4fe98b8 100644 +--- a/websockify/websocket.py ++++ b/websockify/websocket.py +@@ -754,9 +754,7 @@ def start_server(self): + + # Allow override of SIGINT + signal.signal(signal.SIGINT, self.do_SIGINT) +- if not multiprocessing: +- # os.fork() (python 2.4) child reaper +- signal.signal(signal.SIGCHLD, self.fallback_SIGCHLD) ++ signal.signal(signal.SIGCHLD, self.fallback_SIGCHLD) + + last_active_time = self.launch_time + while True: +-- +2.0.3 + diff -Nru websockify-0.3.0/debian/patches/fixes-rebind-wrapper.patch websockify-0.5.1+dfsg1/debian/patches/fixes-rebind-wrapper.patch --- websockify-0.3.0/debian/patches/fixes-rebind-wrapper.patch 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/debian/patches/fixes-rebind-wrapper.patch 2013-12-08 06:27:05.000000000 +0000 @@ -0,0 +1,35 @@ +Description: Fixes rebind wrapper + The default upstream wrapper expects rebind.so to be next to the wrapper, + this is not Debian policy compliant, so we're just fixing the wrapper. +Author: Philipp Hahn +Bug-Debian: http://bugs.debian.org/726304 +Forwarded: no +Last-Update: 2013-12-08 + +--- websockify-0.5.1+dfsg1.orig/rebind ++++ websockify-0.5.1+dfsg1/rebind +@@ -1,5 +1,9 @@ + #!/usr/bin/env bash + ++mydir="$(readlink -f "$(dirname "${0}")")" ++mylib="${mydir}/../lib/websockify/rebind.so" ++[ -e "${mylib}" ] || { echo "${mylib} not found" >&2; exit 1; } ++ + usage() { + echo "Usage: $(basename $0) OLD_PORT NEW_PORT COMMAND_LINE" + echo +@@ -9,10 +13,9 @@ usage() { + } + + # Parameter defaults +-mydir=$(readlink -f $(dirname ${0})) +- +-export REBIND_PORT_OLD="${1}"; shift +-export REBIND_PORT_NEW="${1}"; shift + +-LD_PRELOAD=${mydir}/rebind.so "${@}" ++export REBIND_PORT_OLD="${1}" ++export REBIND_PORT_NEW="${2}" ++shift 2 + ++LD_PRELOAD="${mylib}" exec "${@}" diff -Nru websockify-0.3.0/debian/patches/fix-rebind.so-not-found-when-installed.patch websockify-0.5.1+dfsg1/debian/patches/fix-rebind.so-not-found-when-installed.patch --- websockify-0.3.0/debian/patches/fix-rebind.so-not-found-when-installed.patch 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/debian/patches/fix-rebind.so-not-found-when-installed.patch 2013-12-08 06:27:05.000000000 +0000 @@ -0,0 +1,30 @@ +From f30ad05c70ab2a43c9078e2f79da40f1dc0c60ec Mon Sep 17 00:00:00 2001 +From: Joel Martin +Date: Fri, 27 Sep 2013 07:42:57 -0500 +Subject: [PATCH] Fix #97: rebind.so not found when installed + +This should fix the upstream Debian bug: +http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=719889 +--- + websockify/websocketproxy.py | 5 ++++- + 1 file changed, 4 insertions(+), 1 deletion(-) + +diff --git a/websockify/websocketproxy.py b/websockify/websocketproxy.py +index 1154d92..f893d1f 100755 +--- a/websockify/websocketproxy.py ++++ b/websockify/websocketproxy.py +@@ -55,7 +55,10 @@ def __init__(self, *args, **kwargs): + self.wrap_times = [0, 0, 0] + + if self.wrap_cmd: +- rebinder_path = ['./', os.path.dirname(sys.argv[0])] ++ 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: +-- +1.8.4 + diff -Nru websockify-0.3.0/debian/patches/handle-multiprocessing.patch websockify-0.5.1+dfsg1/debian/patches/handle-multiprocessing.patch --- websockify-0.3.0/debian/patches/handle-multiprocessing.patch 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/debian/patches/handle-multiprocessing.patch 2014-07-31 13:34:22.000000000 +0000 @@ -0,0 +1,42 @@ +From 53f1f1989ecf3d3086242831c74faa3801026f37 Mon Sep 17 00:00:00 2001 +From: Solly Ross +Date: Mon, 21 Oct 2013 16:50:52 -0400 +Subject: [PATCH] Handle SIGCHLD properly for multiprocessing + +This commit should fix #101 by enabling a special SIGCHLD +handler for when multiprocessing is in use. The handler +simply calls `multiprocessing.active_children()` (which in +turn calls `_cleanup()`) upon receiving a SIGCHLD. Now, +the `fallback_SIGCHLD` is only called when `multiprocessing` +is not in use. See also #95. +--- + websockify/websocket.py | 11 ++++++++++- + 1 file changed, 10 insertions(+), 1 deletion(-) + +--- a/websockify/websocket.py ++++ b/websockify/websocket.py +@@ -666,6 +666,9 @@ Sec-WebSocket-Accept: %s\r + #self.vmsg("Running poll()") + pass + ++ def multiprocessing_SIGCHLD(self, sig, stack): ++ self.vmsg('Reaping 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") +@@ -754,7 +757,13 @@ Sec-WebSocket-Accept: %s\r + + # Allow override of SIGINT + signal.signal(signal.SIGINT, self.do_SIGINT) +- signal.signal(signal.SIGCHLD, self.fallback_SIGCHLD) ++ 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 + while True: diff -Nru websockify-0.3.0/debian/patches/removes-websocket-swf-file.patch websockify-0.5.1+dfsg1/debian/patches/removes-websocket-swf-file.patch --- websockify-0.3.0/debian/patches/removes-websocket-swf-file.patch 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/debian/patches/removes-websocket-swf-file.patch 2013-12-08 06:27:05.000000000 +0000 @@ -0,0 +1,21 @@ +Description: Removes include/web-socket-js/WebSocketMain.swf from setup.py + Websockify is +dfsg because include/web-socket-js/WebSocketMain.swf isn't + built from source. So we also need to remove the WebSocketMain.swf file from + setup.py to avoid failure (eg: this file isn't there anymore in the dfsg + version of websockify). +Author: Thomas Goirand +Forwarded: not-needed +Last-Update: 2013-07-21 + +--- websockify-0.5.1+dfsg1.orig/setup.py ++++ websockify-0.5.1+dfsg1/setup.py +@@ -17,8 +17,7 @@ setup(name=name, + '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/swfobject.js', + 'include/web-socket-js/web_socket.js'])], + keywords='noVNC websockify', + license='LGPLv3', diff -Nru websockify-0.3.0/debian/patches/series websockify-0.5.1+dfsg1/debian/patches/series --- websockify-0.3.0/debian/patches/series 2013-01-29 14:22:51.000000000 +0000 +++ websockify-0.5.1+dfsg1/debian/patches/series 2014-07-31 13:01:15.000000000 +0000 @@ -1 +1,5 @@ -add-missing-files.patch +removes-websocket-swf-file.patch +fix-rebind.so-not-found-when-installed.patch +fixes-rebind-wrapper.patch +avoid-zombies.patch +handle-multiprocessing.patch diff -Nru websockify-0.3.0/debian/rules websockify-0.5.1+dfsg1/debian/rules --- websockify-0.3.0/debian/rules 2012-09-17 20:02:40.000000000 +0000 +++ websockify-0.5.1+dfsg1/debian/rules 2013-12-08 06:27:05.000000000 +0000 @@ -1,8 +1,8 @@ #!/usr/bin/make -f -# -*- makefile -*- -# Uncomment this to turn on verbose mode. -#export DH_VERBOSE=1 +UPSTREAM_GIT = git://github.com/kanaka/websockify.git + +include /usr/share/openstack-pkg-tools/pkgos.make %: dh $@ --with python2 @@ -17,4 +17,7 @@ override_dh_auto_clean: make clean python setup.py clean - + rm -rf build/ websockify.egg-info + +override_dh_compress: + dh_compress diff -Nru websockify-0.3.0/debian/watch websockify-0.5.1+dfsg1/debian/watch --- websockify-0.3.0/debian/watch 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/debian/watch 2013-12-08 06:27:05.000000000 +0000 @@ -0,0 +1,3 @@ +version=3 +opts="dversionmangle=s/\+dfsg\d+$//,uversionmangle=s/^v//" \ +https://github.com/kanaka/websockify/tags .*/v(\d[\d\.]+)\.tar\.gz diff -Nru websockify-0.3.0/docs/flash_policy.txt websockify-0.5.1+dfsg1/docs/flash_policy.txt --- websockify-0.3.0/docs/flash_policy.txt 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/docs/flash_policy.txt 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,4 @@ +Manual setup: + +DATA="echo \'\'" +/usr/bin/socat -T 1 TCP-L:843,reuseaddr,fork,crlf SYSTEM:"$DATA" diff -Nru websockify-0.3.0/docs/latency_results.txt websockify-0.5.1+dfsg1/docs/latency_results.txt --- websockify-0.3.0/docs/latency_results.txt 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/docs/latency_results.txt 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,114 @@ +This data is raw copy from the latency tester set to send a frame with +a little over 2000 KB of data every 10ms. + +The number of packets sent and received is just a visual counter and +is just the total when I chose to stop the test (around 3000 or so +packets). + +The latency measure are from the point the packet was sent to when it +was received back again in milliseconds. One notable data point +missing from this is how long it actually took for the client to send +3000 packets because sending large packets can put load on the browser +and it may be a lot longer than 10ms before the timer event to +send the next packet fires. So even with low latency numbers, the +actual send rate may be fairly low because sending the WebSockets +frames is impacting the performance of the browser in general. + + +------------------------------------------------------------ + +Native WebSockets implementations, 2000 byte payload, 10ms delay + +Chrome 8.0.552 - native WebSockets + Packets sent: 2998 + Packets Received: 2998 + Average Latency: 1.84 + 40 Frame Running Average Latency: 1.90 + Minimum Latency: 1.00 + Maximum Latency: 10.00 + +firefox 4.0b9 - WebSockets enabled + Packets sent: 3011 + Packets Received: 3011 + Average Latency: 6.45 + 40 Frame Running Average Latency: 6.08 + Minimum Latency: 5.00 + Maximum Latency: 119.00 + +Opera 11 - WebSockets enabled + Packets sent: 3065 + Packets Received: 3064 + Average Latency: 9.56 + 40 Frame Running Average Latency: 8.15 + Minimum Latency: 4.00 + Maximum Latency: 53.00 + +------------------------------------------------------------ + +New web-socket-js (20f837425d4), 2000 byte payload, 10ms delay + +firefox 4.0b9 - no WebSockets + Packets sent: 3088 + Packets Received: 3087 + Average Latency: 16.71 + 40 Frame Running Average Latency: 16.80 + Minimum Latency: 7.00 + Maximum Latency: 75.00 + + - First 1000 sent in 13 seconds + - Second 1000 sent in 12 seconds + - Third 1000 sent in 12 seconds + +firefox 3.6.10 - no WebSockets + Packets sent: 3100 + Packets Received: 3099 + Average Latency: 17.32 + 40 Frame Running Average Latency: 16.73 + Minimum Latency: 6.00 + Maximum Latency: 72.00 + +Opera 11 - no WebSockets + Packets sent: 3007 + Packets Received: 3007 + Average Latency: 465.91 + 40 Frame Running Average Latency: 147.95 + Minimum Latency: 12.00 + Maximum Latency: 9143.00 + + - average starts at around 28ms + - time for each 500 packets: 13s, 16s, 25s, 37s, 50s, 72s + - also start seeing sent, receive lags around 1200 packets + +--------------------------------------------------------------- + +Old web-socket-js (9e7663771), 2000 byte payload, 10ms delay + +firefox 4.0b9 - no WebSockets + Packets sent: 3024 + Packets Received: 3020 + Average Latency: 80.59 + 40 Frame Running Average Latency: 60.15 + Minimum Latency: 10.00 + Maximm Latency: 348.00 + + +firefox 3.6.10 - no WebSockets + Packets sent: 2777 + Packets Received: 2775 + Average Latency: 34.89 + 40 Frame Running Average Latency: 24.50 + Minimum Latency: 10.00 + Maximum Latency: 208.00 + + +Opera 11 - no Websockets + Packets sent: 3012 + Packets Received: 3011 + Average Latency: 380.87 + 40 Frame Running Average Latency: 341.90 + Minimum Latency: 28.00 + Maximum Latency: 2175.00 + + - average starts at around 290ms + - time for each 1000 packets: 23s, 38s, 65s + diff -Nru websockify-0.3.0/docs/LICENSE.GPL-3 websockify-0.5.1+dfsg1/docs/LICENSE.GPL-3 --- websockify-0.3.0/docs/LICENSE.GPL-3 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/docs/LICENSE.GPL-3 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,621 @@ + 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 diff -Nru websockify-0.3.0/docs/LICENSE.LGPL-3 websockify-0.5.1+dfsg1/docs/LICENSE.LGPL-3 --- websockify-0.3.0/docs/LICENSE.LGPL-3 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/docs/LICENSE.LGPL-3 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,165 @@ + 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. diff -Nru websockify-0.3.0/docs/LICENSE.MPL-2.0 websockify-0.5.1+dfsg1/docs/LICENSE.MPL-2.0 --- websockify-0.3.0/docs/LICENSE.MPL-2.0 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/docs/LICENSE.MPL-2.0 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,373 @@ +Mozilla 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. diff -Nru websockify-0.3.0/docs/notes websockify-0.5.1+dfsg1/docs/notes --- websockify-0.3.0/docs/notes 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/docs/notes 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,24 @@ +Some implementation notes: + +There is an included flash object (web-socket-js) that is used to +emulate websocket support on browsers without websocket support +(currently only Chrome has WebSocket support). + +Javascript doesn't have a bytearray type, so what you get out of +a WebSocket object is just Javascript strings. Javascript has UTF-16 +unicode strings and anything sent through the WebSocket gets converted +to UTF-8 and vice-versa. So, one additional (and necessary) function +of wsproxy is base64 encoding/decoding what is sent to/from the +browser. + +Building web-socket-js emulator: + + cd include/web-socket-js/flash-src + mxmlc -static-link-runtime-shared-libraries WebSocketMain.as + +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 diff -Nru websockify-0.3.0/docs/release.txt websockify-0.5.1+dfsg1/docs/release.txt --- websockify-0.3.0/docs/release.txt 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/docs/release.txt 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,13 @@ +- 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 diff -Nru websockify-0.3.0/docs/TODO websockify-0.5.1+dfsg1/docs/TODO --- websockify-0.3.0/docs/TODO 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/docs/TODO 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,6 @@ +- 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 + diff -Nru websockify-0.3.0/docs/websockify.1 websockify-0.5.1+dfsg1/docs/websockify.1 --- websockify-0.3.0/docs/websockify.1 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/docs/websockify.1 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,110 @@ +.TH websockify 1 "June 7, 2012" "version 0.3" "USER COMMANDS" + +.SH NAME + +websockify - WebSockets to TCP socket bridge + +.SH SYNOPSIS + + websockify [options] [source_addr:]source_port target_addr:target_port + websockify [options] [source_addr:]source_port \-\- WRAP_COMMAND_LINE + +.SH OPTIONS + + -h, --help show this help message and exit + -v, --verbose verbose messages and per frame traffic + --record=FILE record sessions to FILE.[session_number] + -D, --daemon become a daemon (background process) + --run-once handle a single WebSocket connection and exit + --timeout=TIMEOUT after TIMEOUT seconds exit when not connected + --cert=CERT SSL certificate file + --key=KEY SSL key file (if separate from cert) + --ssl-only disallow non-encrypted connections + --web=DIR run webserver on same port. Serve files from DIR. + --wrap-mode=MODE action to take when the wrapped program exits or + daemonizes: exit (default), ignore, respawn + +.SH DESCRIPTION + +At the most basic level, websockify just translates WebSockets traffic to normal TCP socket traffic. Websockify accepts the WebSockets handshake, parses it, and then begins forwarding traffic between the client and the target in both directions. + +websockify was formerly named wsproxy and was part of the noVNC project. + +.SH NOTES + +.SS WebSockets binary data + +Websockify supports all versions of the WebSockets protocol (Hixie and HyBI). The older Hixie versions of the protocol only support UTF-8 text payloads. In order to transport binary data over UTF-8 an encoding must used to encapsulate the data within UTF-8. Websockify uses base64 to encode all traffic to and from the client. This does not affect the data between websockify and the server. + +.SS Encrypted WebSocket connections (wss://) + +To encrypt the traffic using the WebSocket 'wss://' URI scheme you need to generate a certificate for websockify to load. By default websockify loads a certificate file name self.pem but the --cert=CERT option can override the file name. You can generate a self-signed certificate using openssl. When asked for the common name, use the hostname of the server where the proxy will be running: + +openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem + +.SS Websock Javascript library + +The websock.js (see https://github.com/kanaka/websockify) Javascript library library provides a Websock object that is similar to the standard WebSocket object but Websock enables communication with raw TCP sockets (i.e. the binary stream) via websockify. This is accomplished by base64 encoding the data stream between Websock and websockify. + +Websock has built-in receive queue buffering; the message event does not contain actual data but is simply a notification that there is new data available. Several rQ* methods are available to read binary data off of the receive queue. + +The Websock API is documented on the websock.js API wiki page: + +https://github.com/kanaka/websockify/wiki/websock.js + +See the "Wrap a Program" section below for an example of using Websock and websockify as a browser telnet client (wstelnet.html). + +.SS Additional websockify features + +These are not necessary for the basic operation. + +.IP * +Daemonizing: When the -D option is specified, websockify runs in the background as a daemon process. + +.IP * +SSL (the wss:// WebSockets URI): This is detected automatically by websockify by sniffing the first byte sent from the client and then wrapping the socket if the data starts with '\\x16' or '\\x80' (indicating SSL). + +.IP * +Flash security policy: websockify detects flash security policy requests (again by sniffing the first packet) and answers with an appropriate flash security policy response (and then closes the port). This means no separate flash security policy server is needed for supporting the flash WebSockets fallback emulator. + +.IP * +Session recording: This feature that allows recording of the traffic sent and received from the client to a file using the --record option. + +.IP * +Mini-webserver: websockify can detect and respond to normal web requests on the same port as the WebSockets proxy and Flash security policy. This functionality is activate with the --web DIR option where DIR is the root of the web directory to serve. + +.IP * +Wrap a program: see the "Wrap a Program" section below. + +.SS Wrap a Program + +In addition to proxying from a source address to a target address (which may be on a different system), websockify has the ability to launch a program on the local system and proxy WebSockets traffic to a normal TCP port owned/bound by the program. + +The is accomplished with a small LD_PRELOAD library (rebind.so) which intercepts bind() system calls by the program. The specified port is moved to a new localhost/loopback free high port. websockify then proxies WebSockets traffic directed to the original port to the new (moved) port of the program. + +The program wrap mode is invoked by replacing the target with -- followed by the program command line to wrap. + +`./websockify 2023 -- PROGRAM ARGS` + +The --wrap-mode option can be used to indicate what action to take when the wrapped program exits or daemonizes. + +Here is an example of using websockify to wrap the vncserver command (which backgrounds itself) for use with noVNC: + +`./websockify 5901 --wrap-mode=ignore -- vncserver -geometry 1024x768 :1` + +Here is an example of wrapping telnetd (from krb5-telnetd).telnetd exits after the connection closes so the wrap mode is set to respawn the command: + +`sudo ./websockify 2023 --wrap-mode=respawn -- telnetd -debug 2023` + +The wstelnet.html page demonstrates a simple WebSockets based telnet client. + + +.SH AUTHOR +Joel Martin (github@martintribe.org) + +.SH SEE ALSO + +https://github.com/kanaka/websockify/ + +https://github.com/kanaka/websockify/wiki/ + diff -Nru websockify-0.3.0/.gitignore websockify-0.5.1+dfsg1/.gitignore --- websockify-0.3.0/.gitignore 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/.gitignore 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,11 @@ +*.pyc +*.o +*.so +other/.lein-deps-sum +other/classes +other/lib +other/node_modules +.project +.pydevproject +target.cfg +target.cfg.d diff -Nru websockify-0.3.0/.gitmodules websockify-0.5.1+dfsg1/.gitmodules --- websockify-0.3.0/.gitmodules 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/.gitmodules 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,3 @@ +[submodule "include/web-socket-js-project"] + path = include/web-socket-js-project + url = https://github.com/gimite/web-socket-js.git diff -Nru websockify-0.3.0/include/base64.js websockify-0.5.1+dfsg1/include/base64.js --- websockify-0.3.0/include/base64.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/include/base64.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,114 @@ +/* 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 */ diff -Nru websockify-0.3.0/include/keysym.js websockify-0.5.1+dfsg1/include/keysym.js --- websockify-0.3.0/include/keysym.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/include/keysym.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,99 @@ +/* + * from noVNC: HTML5 VNC client + * Copyright (C) 2010 Joel Martin + * Licensed under LGPL-3 (see LICENSE.txt) + */ + +/* Translate DOM key down/up event to keysym value */ +function getKeysym(e) { + var evt, keysym; + evt = (e ? e : window.event); + + /* Remap modifier and special keys */ + switch ( evt.keyCode ) { + case 8 : keysym = 0xFF08; break; // BACKSPACE + case 9 : keysym = 0xFF09; break; // TAB + case 13 : keysym = 0xFF0D; break; // ENTER + case 27 : keysym = 0xFF1B; break; // ESCAPE + case 45 : keysym = 0xFF63; break; // INSERT + case 46 : keysym = 0xFFFF; break; // DELETE + case 36 : keysym = 0xFF50; break; // HOME + case 35 : keysym = 0xFF57; break; // END + case 33 : keysym = 0xFF55; break; // PAGE_UP + case 34 : keysym = 0xFF56; break; // PAGE_DOWN + case 37 : keysym = 0xFF51; break; // LEFT + case 38 : keysym = 0xFF52; break; // UP + case 39 : keysym = 0xFF53; break; // RIGHT + case 40 : keysym = 0xFF54; break; // DOWN + case 112 : keysym = 0xFFBE; break; // F1 + case 113 : keysym = 0xFFBF; break; // F2 + case 114 : keysym = 0xFFC0; break; // F3 + case 115 : keysym = 0xFFC1; break; // F4 + case 116 : keysym = 0xFFC2; break; // F5 + case 117 : keysym = 0xFFC3; break; // F6 + case 118 : keysym = 0xFFC4; break; // F7 + case 119 : keysym = 0xFFC5; break; // F8 + case 120 : keysym = 0xFFC6; break; // F9 + case 121 : keysym = 0xFFC7; break; // F10 + case 122 : keysym = 0xFFC8; break; // F11 + case 123 : keysym = 0xFFC9; break; // F12 + case 16 : keysym = 0xFFE1; break; // SHIFT + case 17 : keysym = 0xFFE3; break; // CONTROL + //case 18 : keysym = 0xFFE7; break; // Left Meta (Mac Option) + case 18 : keysym = 0xFFE9; break; // Left ALT (Mac Command) + default : keysym = evt.keyCode; break; + } + + /* Remap symbols */ + switch (keysym) { + case 186 : keysym = 59; break; // ; (IE) + case 187 : keysym = 61; break; // = (IE) + case 188 : keysym = 44; break; // , (Mozilla, IE) + case 109 : // - (Mozilla) + if (Util.Engine.gecko) { + keysym = 45; } + break; + case 189 : keysym = 45; break; // - (IE) + case 190 : keysym = 46; break; // . (Mozilla, IE) + case 191 : keysym = 47; break; // / (Mozilla, IE) + case 192 : keysym = 96; break; // ` (Mozilla, IE) + case 219 : keysym = 91; break; // [ (Mozilla, IE) + case 220 : keysym = 92; break; // \ (Mozilla, IE) + case 221 : keysym = 93; break; // ] (Mozilla, IE) + case 222 : keysym = 39; break; // ' (Mozilla, IE) + } + + /* Remap shifted and unshifted keys */ + if (!!evt.shiftKey) { + switch (keysym) { + case 48 : keysym = 41 ; break; // ) (shifted 0) + case 49 : keysym = 33 ; break; // ! (shifted 1) + case 50 : keysym = 64 ; break; // @ (shifted 2) + case 51 : keysym = 35 ; break; // # (shifted 3) + case 52 : keysym = 36 ; break; // $ (shifted 4) + case 53 : keysym = 37 ; break; // % (shifted 5) + case 54 : keysym = 94 ; break; // ^ (shifted 6) + case 55 : keysym = 38 ; break; // & (shifted 7) + case 56 : keysym = 42 ; break; // * (shifted 8) + case 57 : keysym = 40 ; break; // ( (shifted 9) + + case 59 : keysym = 58 ; break; // : (shifted `) + case 61 : keysym = 43 ; break; // + (shifted ;) + case 44 : keysym = 60 ; break; // < (shifted ,) + case 45 : keysym = 95 ; break; // _ (shifted -) + case 46 : keysym = 62 ; break; // > (shifted .) + case 47 : keysym = 63 ; break; // ? (shifted /) + case 96 : keysym = 126; break; // ~ (shifted `) + case 91 : keysym = 123; break; // { (shifted [) + case 92 : keysym = 124; break; // | (shifted \) + case 93 : keysym = 125; break; // } (shifted ]) + case 39 : keysym = 34 ; break; // " (shifted ') + } + } else if ((keysym >= 65) && (keysym <=90)) { + /* Remap unshifted A-Z */ + keysym += 32; + } + + return keysym; +} + diff -Nru websockify-0.3.0/include/util.js websockify-0.5.1+dfsg1/include/util.js --- websockify-0.3.0/include/util.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/include/util.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,379 @@ +/* + * 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}; +}()); diff -Nru websockify-0.3.0/include/VT100.js websockify-0.5.1+dfsg1/include/VT100.js --- websockify-0.3.0/include/VT100.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/include/VT100.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,919 @@ +// VT100.js -- a text terminal emulator in JavaScript with a ncurses-like +// interface and a POSIX-like interface. (The POSIX-like calls are +// implemented on top of the ncurses-like calls, not the other way round.) +// +// Released under the GNU LGPL v2.1, by Frank Bi +// +// 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"); +} diff -Nru websockify-0.3.0/include/web-socket-js/README.txt websockify-0.5.1+dfsg1/include/web-socket-js/README.txt --- websockify-0.3.0/include/web-socket-js/README.txt 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/include/web-socket-js/README.txt 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,109 @@ +* How to try + +Assuming you have Web server (e.g. Apache) running at http://example.com/ . + +- Download web_socket.rb from: + http://github.com/gimite/web-socket-ruby/tree/master +- Run sample Web Socket server (echo server) in example.com with: (#1) + $ ruby web-socket-ruby/samples/echo_server.rb example.com 10081 +- If your server already provides socket policy file at port 843, modify the file to allow access to port 10081. Otherwise you can skip this step. See below for details. +- Publish the web-socket-js directory with your Web server (e.g. put it in ~/public_html). +- Change ws://localhost:10081 to ws://example.com:10081 in sample.html. +- Open sample.html in your browser. +- After "onopen" is shown, input something, click [Send] and confirm echo back. + +#1: First argument of echo_server.rb means that it accepts Web Socket connection from HTML pages in example.com. + + +* Troubleshooting + +If it doesn't work, try these: + +1. Try Chrome and Firefox 3.x. +- It doesn't work on Chrome: +-- It's likely an issue of your code or the server. Debug your code as usual e.g. using console.log. +- It works on Chrome but it doesn't work on Firefox: +-- It's likely an issue of web-socket-js specific configuration (e.g. 3 and 4 below). +- It works on both Chrome and Firefox, but it doesn't work on your browser: +-- Check "Supported environment" section below. Your browser may not be supported by web-socket-js. + +2. Add this line before your code: + WEB_SOCKET_DEBUG = true; +and use Developer Tools (Chrome/Safari) or Firebug (Firefox) to see if console.log outputs any errors. + +3. Make sure you do NOT open your HTML page as local file e.g. file:///.../sample.html. web-socket-js doesn't work on local file. Open it via Web server e.g. http:///.../sample.html. + +4. If you are NOT using web-socket-ruby as your WebSocket server, you need to place Flash socket policy file on your server. See "Flash socket policy file" section below for details. + +5. Check if sample.html bundled with web-socket-js works. + +6. Make sure the port used for WebSocket (10081 in example above) is not blocked by your server/client's firewall. + +7. Install debugger version of Flash Player available here to see Flash errors: +http://www.adobe.com/support/flashplayer/downloads.html + + +* Supported environments + +It should work on: +- Google Chrome 4 or later (just uses native implementation) +- Firefox 3.x, Internet Explorer 8 + Flash Player 9 or later + +It may or may not work on other browsers such as Safari, Opera or IE 6. Patch for these browsers are appreciated, but I will not work on fixing issues specific to these browsers by myself. + + +* Flash socket policy file + +This implementation uses Flash's socket, which means that your server must provide Flash socket policy file to declare the server accepts connections from Flash. + +If you use web-socket-ruby available at +http://github.com/gimite/web-socket-ruby/tree/master +, you don't need anything special, because web-socket-ruby handles Flash socket policy file request. But if you already provide socket policy file at port 843, you need to modify the file to allow access to Web Socket port, because it precedes what web-socket-ruby provides. + +If you use other Web Socket server implementation, you need to provide socket policy file yourself. See +http://www.lightsphere.com/dev/articles/flash_socket_policy.html +for details and sample script to run socket policy file server. node.js implementation is available here: +http://github.com/LearnBoost/Socket.IO-node/blob/master/lib/socket.io/transports/flashsocket.js + +Actually, it's still better to provide socket policy file at port 843 even if you use web-socket-ruby. Flash always try to connect to port 843 first, so providing the file at port 843 makes startup faster. + + +* Cookie considerations + +Cookie is sent if Web Socket host is the same as the origin of JavaScript. Otherwise it is not sent, because I don't know way to send right Cookie (which is Cookie of the host of Web Socket, I heard). + +Note that it's technically possible that client sends arbitrary string as Cookie and any other headers (by modifying this library for example) once you place Flash socket policy file in your server. So don't trust Cookie and other headers if you allow connection from untrusted origin. + + +* Proxy considerations + +The WebSocket spec (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol) specifies instructions for User Agents to support proxied connections by implementing the HTTP CONNECT method. + +The AS3 Socket class doesn't implement this mechanism, which renders it useless for the scenarios where the user trying to open a socket is behind a proxy. + +The class RFC2817Socket (by Christian Cantrell) effectively lets us implement this, as long as the proxy settings are known and provided by the interface that instantiates the WebSocket. As such, if you want to support proxied conncetions, you'll have to supply this information to the WebSocket constructor when Flash is being used. One way to go about it would be to ask the user for proxy settings information if the initial connection fails. + + +* How to host HTML file and SWF file in different domains + +By default, HTML file and SWF file must be in the same domain. You can follow steps below to allow hosting them in different domain. + +WARNING: If you use the method below, HTML files in ANY domains can send arbitrary TCP data to your WebSocket server, regardless of configuration in Flash socket policy file. Arbitrary TCP data means that they can even fake request headers including Origin and Cookie. + +- Unzip WebSocketMainInsecure.zip to extract WebSocketMainInsecure.swf. +- Put WebSocketMainInsecure.swf on your server, instead of WebSocketMain.swf. +- In JavaScript, set WEB_SOCKET_SWF_LOCATION to URL of your WebSocketMainInsecure.swf. + + +* How to build WebSocketMain.swf + +Install Flex 4 SDK: +http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+4 + +$ cd flash-src +$ ./build.sh + + +* License + +New BSD License. diff -Nru websockify-0.3.0/include/web-socket-js/swfobject.js websockify-0.5.1+dfsg1/include/web-socket-js/swfobject.js --- websockify-0.3.0/include/web-socket-js/swfobject.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/include/web-socket-js/swfobject.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,777 @@ +/*! 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; + } + } + }; +}(); diff -Nru websockify-0.3.0/include/web-socket-js/web_socket.js websockify-0.5.1+dfsg1/include/web-socket-js/web_socket.js --- websockify-0.3.0/include/web-socket-js/web_socket.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/include/web-socket-js/web_socket.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,391 @@ +// 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(); + }); + } + +})(); diff -Nru websockify-0.3.0/include/websock.js websockify-0.5.1+dfsg1/include/websock.js --- websockify-0.3.0/include/websock.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/include/websock.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,422 @@ +/* + * 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(); + +} diff -Nru websockify-0.3.0/include/webutil.js websockify-0.5.1+dfsg1/include/webutil.js --- websockify-0.3.0/include/webutil.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/include/webutil.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,216 @@ +/* + * 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; +}; diff -Nru websockify-0.3.0/include/wsirc.js websockify-0.5.1+dfsg1/include/wsirc.js --- websockify-0.3.0/include/wsirc.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/include/wsirc.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,235 @@ +/* + * WebSockets IRC client + * Copyright (C) 2011 Joel Martin + * Licensed under LGPL-3 (see LICENSE.txt) + * + * Includes VT100.js from: + * http://code.google.com/p/sshconsole + * Which was modified from: + * http://fzort.org/bi/o.php#vt100_js + + * IRC Client protocol: + * http://www.faqs.org/rfcs/rfc2812.html + */ + + +function IRC(target, connect_callback, disconnect_callback) { + +var that = {}, // Public API interface + vt100, ws, sQ = [], + state = "unconnected", + irc_nick, irc_channel, + termType = "VT100"; + + +Array.prototype.pushStr = function (str) { + var n = str.length; + for (var i=0; i < n; i++) { + this.push(str.charCodeAt(i)); + } +} + +function do_send() { + if (sQ.length > 0) { + Util.Debug("Sending " + sQ); + ws.send(sQ); + sQ = []; + } +} + +function do_recv() { + console.log(">> do_recv"); + var rQ, rQi, i; + + while (ws.rQlen() > 1) { + rQ = ws.get_rQ(); + rQi = ws.get_rQi(); + for (i = rQi; i < rQ.length; i++) { + if (rQ[i] === 10) { + break; + } + } + if (i >= rQ.length) { + // No line break found + break; + } + recvMsg(ws.rQshiftStr((i-rQi) + 1)); + } + //console.log("<< do_recv"); +} + +// Handle an IRC message +function recvMsg(msg) { + Util.Debug(">> recvMsg('" + msg + "')"); + + var tokens = msg.split(' '), in_params = true, + prefix, command, params = [], trailing = []; + + Util.Info(" tokens: " + tokens); + + if (tokens[0].charAt(0) === ":") { + prefix = tokens.shift(); + } + + command = tokens.shift(); + + while (tokens.length > 0) { + if (tokens[0].charAt(0) === ":") { + in_params = false; + } + if (in_params) { + params.push(tokens.shift()); + } else { + trailing.push(tokens.shift()); + } + } + + Util.Info(" prefix: " + prefix); + Util.Info(" command: " + command); + Util.Info(" params: " + params); + Util.Info(" trailing: " + trailing); + + // Show raw received + vt100.write(msg); + + switch (command) { + case "004": + state = "registered"; + vt100.write("Joining channel #" + irc_channel); + sendCmd("JOIN #" + irc_channel); + break; + case "JOIN": + state = "joined"; + vt100.write("Joined channel #" + irc_channel); + break; + + } + + Util.Debug("<< recvMsg('" + msg + "')"); +} + +function sendCmd(msg) { + Util.Info("Sending: " + msg); + sQ.pushStr(msg + "\r\n"); + do_send(); +} + +that.sendMsg = function(msg) { + // TODO parse into message + sendCmd("PRIVMSG #" + irc_channel + " :" + msg); +} + + +that.connect = function(host, port, encrypt, nick, channel) { + var host = host, + port = port, + scheme = "ws://", uri; + + irc_nick = nick; + irc_channel = channel; + + Util.Debug(">> connect"); + if ((!host) || (!port)) { + alert("must set host and port"); + return false; + } + + if (ws) { + ws.close(); + } + + if (encrypt) { + scheme = "wss://"; + } + uri = scheme + host + ":" + port; + Util.Info("connecting to " + uri); + + ws.open(uri); + + Util.Debug("<< connect"); + + return true; +} + +that.disconnect = function() { + Util.Debug(">> disconnect"); + if (ws) { + ws.close(); + } + + disconnect_callback(); + Util.Debug("<< disconnect"); +} + + +function constructor() { + /* Initialize Websock object */ + ws = new Websock(); + + ws.on('message', do_recv); + ws.on('open', function(e) { + Util.Info(">> WebSockets.onopen"); + // Send registration commands + state = "connected"; + sendCmd("NICK " + irc_nick); + // TODO: how to determine this? + sendCmd("USER joelm 0 * :Joel Martin"); + connect_callback(); + Util.Info("<< WebSockets.onopen"); + }); + ws.on('close', function(e) { + Util.Info(">> WebSockets.onclose"); + that.disconnect(); + Util.Info("<< WebSockets.onclose"); + }); + ws.on('error', function(e) { + Util.Info(">> WebSockets.onerror"); + that.disconnect(); + Util.Info("<< WebSockets.onerror"); + }); + + /* Initialize the terminal emulator/renderer */ + + vt100 = new VT100(80, 24, target); + + // Show cursor + vt100.curs_set(true, false); + + /* + * Override VT100 I/O routines + */ + + // Set handler for sending characters + vt100.getch( + function send_chr(chr, vt) { + var i; + Util.Debug(">> send_chr: " + chr); + for (i = 0; i < chr.length; i++) { + sQ.push(chr.charCodeAt(i)); + } + do_send(); + vt100.getch(send_chr); + } + ); + + vt100.debug = function(message) { + Util.Debug(message + "\n"); + } + + vt100.warn = function(message) { + Util.Warn(message + "\n"); + } + + vt100.curs_set = function(vis, grab, eventist) + { + this.debug("curs_set:: vis: " + vis + ", grab: " + grab); + if (vis !== undefined) + this.cursor_vis_ = (vis > 0); + } + + return that; +} + +return constructor(); // Return the public API interface + +} // End of Telnet() diff -Nru websockify-0.3.0/include/wstelnet.js websockify-0.5.1+dfsg1/include/wstelnet.js --- websockify-0.3.0/include/wstelnet.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/include/wstelnet.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,335 @@ +/* + * WebSockets telnet client + * Copyright (C) 2011 Joel Martin + * Licensed under LGPL-3 (see LICENSE.txt) + * + * Includes VT100.js from: + * http://code.google.com/p/sshconsole + * Which was modified from: + * http://fzort.org/bi/o.php#vt100_js + * + * Telnet protocol: + * http://www.networksorcery.com/enp/protocol/telnet.htm + * http://www.networksorcery.com/enp/rfc/rfc1091.txt + * + * ANSI escape sequeneces: + * http://en.wikipedia.org/wiki/ANSI_escape_code + * http://ascii-table.com/ansi-escape-sequences-vt-100.php + * http://www.termsys.demon.co.uk/vtansi.htm + * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html + * + * ASCII codes: + * http://en.wikipedia.org/wiki/ASCII + * http://www.hobbyprojects.com/ascii-table/ascii-table.html + * + * Other web consoles: + * http://stackoverflow.com/questions/244750/ajax-console-window-with-ansi-vt100-support + */ + + + + +function Telnet(target, connect_callback, disconnect_callback) { + +var that = {}, // Public API interface + vt100, ws, sQ = []; + termType = "VT100"; + + +Array.prototype.pushStr = function (str) { + var n = str.length; + for (var i=0; i < n; i++) { + this.push(str.charCodeAt(i)); + } +} + +function do_send() { + if (sQ.length > 0) { + Util.Debug("Sending " + sQ); + ws.send(sQ); + sQ = []; + } +} + +function do_recv() { + //console.log(">> do_recv"); + var arr = ws.rQshiftBytes(ws.rQlen()), str = "", + chr, cmd, code, value; + + Util.Debug("Received array '" + arr + "'"); + while (arr.length > 0) { + chr = arr.shift(); + switch (chr) { + case 255: // IAC + cmd = chr; + code = arr.shift(); + value = arr.shift(); + switch (code) { + case 254: // DONT + Util.Debug("Got Cmd DONT '" + value + "', ignoring"); + break; + case 253: // DO + Util.Debug("Got Cmd DO '" + value + "'"); + if (value === 24) { + // Terminal type + Util.Info("Send WILL '" + value + "' (TERM-TYPE)"); + sQ.push(255, 251, value); + } else { + // Refuse other DO requests with a WONT + Util.Debug("Send WONT '" + value + "'"); + sQ.push(255, 252, value); + } + break; + case 252: // WONT + Util.Debug("Got Cmd WONT '" + value + "', ignoring"); + break; + case 251: // WILL + Util.Debug("Got Cmd WILL '" + value + "'"); + if (value === 1) { + // Server will echo, turn off local echo + vt100.noecho(); + // Affirm echo with DO + Util.Info("Send Cmd DO '" + value + "' (echo)"); + sQ.push(255, 253, value); + } else { + // Reject other WILL offers with a DONT + Util.Debug("Send Cmd DONT '" + value + "'"); + sQ.push(255, 254, value); + } + break; + case 250: // SB (subnegotiation) + if (value === 24) { + Util.Info("Got IAC SB TERM-TYPE SEND(1) IAC SE"); + // TERM-TYPE subnegotiation + if (arr[0] === 1 && + arr[1] === 255 && + arr[2] === 240) { + arr.shift(); arr.shift(); arr.shift(); + Util.Info("Send IAC SB TERM-TYPE IS(0) '" + + termType + "' IAC SE"); + sQ.push(255, 250, 24, 0); + sQ.pushStr(termType); + sQ.push(255, 240); + } else { + Util.Info("Invalid subnegotiation received" + arr); + } + } else { + Util.Info("Ignoring SB " + value); + } + break; + default: + Util.Info("Got Cmd " + cmd + " " + value + ", ignoring"); } + continue; + case 242: // Data Mark (Synch) + cmd = chr; + code = arr.shift(); + value = arr.shift(); + Util.Info("Ignoring Data Mark (Synch)"); + break; + default: // everything else + str += String.fromCharCode(chr); + } + } + + if (sQ) { + do_send(); + } + + if (str) { + vt100.write(str); + } + + //console.log("<< do_recv"); +} + + + +that.connect = function(host, port, encrypt) { + var host = host, + port = port, + scheme = "ws://", uri; + + Util.Debug(">> connect"); + if ((!host) || (!port)) { + console.log("must set host and port"); + return; + } + + if (ws) { + ws.close(); + } + + if (encrypt) { + scheme = "wss://"; + } + uri = scheme + host + ":" + port; + Util.Info("connecting to " + uri); + + ws.open(uri); + + Util.Debug("<< connect"); +} + +that.disconnect = function() { + Util.Debug(">> disconnect"); + if (ws) { + ws.close(); + } + vt100.curs_set(true, false); + + disconnect_callback(); + Util.Debug("<< disconnect"); +} + + +function constructor() { + /* Initialize Websock object */ + ws = new Websock(); + + ws.on('message', do_recv); + ws.on('open', function(e) { + Util.Info(">> WebSockets.onopen"); + vt100.curs_set(true, true); + connect_callback(); + Util.Info("<< WebSockets.onopen"); + }); + ws.on('close', function(e) { + Util.Info(">> WebSockets.onclose"); + that.disconnect(); + Util.Info("<< WebSockets.onclose"); + }); + ws.on('error', function(e) { + Util.Info(">> WebSockets.onerror"); + that.disconnect(); + Util.Info("<< WebSockets.onerror"); + }); + + /* Initialize the terminal emulator/renderer */ + + vt100 = new VT100(80, 24, target); + + + /* + * Override VT100 I/O routines + */ + + // Set handler for sending characters + vt100.getch( + function send_chr(chr, vt) { + var i; + Util.Debug(">> send_chr: " + chr); + for (i = 0; i < chr.length; i++) { + sQ.push(chr.charCodeAt(i)); + } + do_send(); + vt100.getch(send_chr); + } + ); + + vt100.debug = function(message) { + Util.Debug(message + "\n"); + } + + vt100.warn = function(message) { + Util.Warn(message + "\n"); + } + + vt100.curs_set = function(vis, grab, eventist) + { + this.debug("curs_set:: vis: " + vis + ", grab: " + grab); + if (vis !== undefined) + this.cursor_vis_ = (vis > 0); + if (eventist === undefined) + eventist = window; + if (grab === true || grab === false) { + if (grab === this.grab_events_) + return; + if (grab) { + this.grab_events_ = true; + VT100.the_vt_ = this; + Util.addEvent(eventist, 'keydown', vt100.key_down); + Util.addEvent(eventist, 'keyup', vt100.key_up); + } else { + Util.removeEvent(eventist, 'keydown', vt100.key_down); + Util.removeEvent(eventist, 'keyup', vt100.key_up); + this.grab_events_ = false; + VT100.the_vt_ = undefined; + } + } + } + + vt100.key_down = function(e) { + var vt = VT100.the_vt_, keysym, ch, str = ""; + + if (vt === undefined) + return true; + + keysym = getKeysym(e); + + if (keysym < 128) { + if (e.ctrlKey) { + if (keysym == 64) { + // control 0 + ch = 0; + } else if ((keysym >= 97) && (keysym <= 122)) { + // control codes 1-26 + ch = keysym - 96; + } else if ((keysym >= 91) && (keysym <= 95)) { + // control codes 27-31 + ch = keysym - 64; + } else { + Util.Info("Debug unknown control keysym: " + keysym); + } + } else { + ch = keysym; + } + str = String.fromCharCode(ch); + } else { + switch (keysym) { + case 65505: // Shift, do not send directly + break; + case 65507: // Ctrl, do not send directly + break; + case 65293: // Carriage return, line feed + str = '\n'; break; + case 65288: // Backspace + str = '\b'; break; + case 65307: // Escape + str = '\x1b'; break; + case 65361: // Left arrow + str = '\x1b[D'; break; + case 65362: // Up arrow + str = '\x1b[A'; break; + case 65363: // Right arrow + str = '\x1b[C'; break; + case 65364: // Down arrow + str = '\x1b[B'; break; + default: + Util.Info("Unrecoginized keysym " + keysym); + } + } + + if (str) { + vt.key_buf_.push(str); + setTimeout(VT100.go_getch_, 0); + } + + Util.stopEvent(e); + return false; + } + + vt100.key_up = function(e) { + var vt = VT100.the_vt_; + if (vt === undefined) + return true; + Util.stopEvent(e); + return false; + } + + + return that; +} + +return constructor(); // Return the public API interface + +} // End of Telnet() diff -Nru websockify-0.3.0/Makefile websockify-0.5.1+dfsg1/Makefile --- websockify-0.3.0/Makefile 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/Makefile 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,11 @@ +TARGETS=rebind.so +CFLAGS += -fPIC + +all: $(TARGETS) + +rebind.so: rebind.o + $(CC) $(LDFLAGS) $^ -shared -fPIC -ldl -o $@ + +clean: + rm -f rebind.o rebind.so + diff -Nru websockify-0.3.0/MANIFEST.in websockify-0.5.1+dfsg1/MANIFEST.in --- websockify-0.3.0/MANIFEST.in 2012-02-18 20:56:33.000000000 +0000 +++ websockify-0.5.1+dfsg1/MANIFEST.in 2013-09-12 14:43:43.000000000 +0000 @@ -1 +1,2 @@ -include CHANGES.txt *.py README.md LICENSE.txt +include CHANGES.txt README.md LICENSE.txt +graft include diff -Nru websockify-0.3.0/mod_websockify.py websockify-0.5.1+dfsg1/mod_websockify.py --- websockify-0.3.0/mod_websockify.py 2012-06-26 18:34:44.000000000 +0000 +++ websockify-0.5.1+dfsg1/mod_websockify.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,82 +0,0 @@ -"""PythonHeaderParserHandler for websockify. - -Apache HTTP Server and mod_python must be configured such that this -function is called to handle WebSocket request. -""" - - -import websockify - -from mod_python import apache - - -def headerparserhandler(request): - """Handle request. - - Args: - request: mod_python request. - - This function is named headerparserhandler because it is the default - name for a PythonHeaderParserHandler. - """ - - request.log_error('in websockify.headerparserhandler: %s' % request.unparsed_uri) - #request.log_error('1: %s' % request.unparsed_uri) - request.log_error('2: %s' % dir(request)) - #request.log_error('3: %s' % request.headers_in) - - headers = request.headers_in - if (headers.get('Upgrade') and - headers.get('Upgrade').lower() == 'websocket'): - - #if (headers.get('sec-websocket-key1') or - # headers.get('websocket-key1')): - # # For Hixie-76 read out the key hash - # headers.__setitem__('key3', self.rfile.read(8)) - # challenge += self._request.connection.read(8) - -# try: -# options = request.get_options() -# request.subprocess_env['targetHost'] = options['websockify.targetHost'] -# request.subprocess_env['targetPort'] = options['websockify.targetPort'] -# except: -# request.log_error("websockify - handshake exception: %s" % (exc_info()[1])) -# raise handshake.AbortedByUserException("websockify: connection denied: %s" % (exc_info()[1])) -# -# request.ws_protocol = request.ws_requested_protocols[0] -# request.log_error("websockify: ws_protocol = '%s' (%s)" % ( -# request.ws_protocol, request.ws_requested_protocols), apache.APLOG_NOTICE) -# -# if request.ws_protocol not in ['base64', 'binary']: -# request.log_error( -# "websockify - unsupport protocol: %s" % request.ws_protocol) -# raise handshake.AbortedByUserException( -# "websockify: unsupported protocol: %s" % request.ws_protocol) -# - - wsproxy = websockify.WebSocketProxy(target_host="localhost", target_port=5901, - wrap_cmd=None, wrap_mode=None, unix_target=False, ssl_target=False) - response = wsproxy.do_websocket_handshake(request.headers_in, request.unparsed_uri) - request.log_error('4: %s' % response) - - request.connection.write(response) - - request.log_error('5: connection: %s' % type(request.connection)) - request.log_error('5.1: dir(connection): %s' % dir(request.connection)) - wsproxy.client = request.connection - wsproxy.new_client() - request.log_error('6: done proxying') - - # Set assbackwards to suppress response header generation by Apache. - request.assbackwards = 1 - return apache.DONE # Return DONE such that no other handlers are invoked. - - #response = WebSocket.do_websocket_handshake(request.headers_in, path) - #request.connection.write(raw_response) - ## Set assbackwards to suppress response header generation by Apache. - #request.assbackwards = 1 - #return apache.DONE # Return DONE such that no other handlers are invoked. - - return apache.DECLINED - -# vi:sts=4 sw=4 et diff -Nru websockify-0.3.0/other/js/package.json websockify-0.5.1+dfsg1/other/js/package.json --- websockify-0.3.0/other/js/package.json 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/other/js/package.json 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,24 @@ +{ + "author": "Joel Martin (http://github.com/kanaka)", + "name": "websockify", + "description": "websockify is a WebSocket-to-TCP proxy/bridge", + "license": "LGPL-3", + "version": "0.5.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" + } +} diff -Nru websockify-0.3.0/other/js/README.md websockify-0.5.1+dfsg1/other/js/README.md --- websockify-0.3.0/other/js/README.md 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/other/js/README.md 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,7 @@ +A 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. diff -Nru websockify-0.3.0/other/js/websockify.js websockify-0.5.1+dfsg1/other/js/websockify.js --- websockify-0.3.0/other/js/websockify.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/other/js/websockify.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,192 @@ +#!/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); diff -Nru websockify-0.3.0/other/launch.sh websockify-0.5.1+dfsg1/other/launch.sh --- websockify-0.3.0/other/launch.sh 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/other/launch.sh 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,118 @@ +#!/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} diff -Nru websockify-0.3.0/other/Makefile websockify-0.5.1+dfsg1/other/Makefile --- websockify-0.3.0/other/Makefile 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/other/Makefile 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,14 @@ +TARGETS=websockify +CFLAGS += -fPIC + +all: $(TARGETS) + +websockify: websockify.o websocket.o + $(CC) $(LDFLAGS) $^ -lssl -lcrypto -lresolv -o $@ + +websocket.o: websocket.c websocket.h +websockify.o: websockify.c websocket.h + +clean: + rm -f websockify *.o + diff -Nru websockify-0.3.0/other/project.clj websockify-0.5.1+dfsg1/other/project.clj --- websockify-0.3.0/other/project.clj 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/other/project.clj 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,13 @@ +(defproject websockify "1.0.0-SNAPSHOT" + :description "Clojure implementation of Websockify" + :url "https://github.com/kanaka/websockify" + :dependencies [[org.clojure/clojure "1.2.1"] + [org.clojure/tools.cli "0.2.1"] + [ring/ring-jetty-adapter "1.0.0-beta2"] + [org.eclipse.jetty/jetty-websocket "7.5.4.v20111024"] + [org.eclipse.jetty/jetty-server "7.5.4.v20111024"] + [org.eclipse.jetty/jetty-servlet "7.5.4.v20111024"] + [org.jboss.netty/netty "3.2.5.Final"]] + ;:dev-dependencies [[swank-clojure "1.3.0-SNAPSHOT"]] + :main websockify + ) diff -Nru websockify-0.3.0/other/README.md websockify-0.5.1+dfsg1/other/README.md --- websockify-0.3.0/other/README.md 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/other/README.md 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,51 @@ +This directory contain alternate implementations of +WebSockets-to-TCP-Socket proxies (for noVNC). + +## websockify.c (C) + +### Description + +This is a C version of the original websockify. It is more limited in +functionality than the original. + + +## websockify.js + +### Description + +This is a Node.JS (server-side event driven Javascript) implementation +of websockify. + + +## kumina.c (C) + +### Description + +The upstream source of the kumina proxy is [here](https://github.com/kumina/wsproxy). + +[This article](http://blog.kumina.nl/2011/06/proxying-and-multiplexing-novnc-using-wsproxy/) +describes the kumina proxy. + +kumina is an application that is run from inetd, which allows noVNC +to connect to an unmodified VNC server. Furthermore, it makes use of +the recently added support in noVNC for file names. The file name is +used to denote the port number. Say, you connect to: + + ws://host:41337/25900 + +The kumina proxy opens a connection to: + + vnc://host:25900/ + +The address to which kumina connects, is the same as the address to +which the client connected (using getsockname()). + +### Configuration + +kumina can be enabled by adding the following line to inetd.conf: + + 41337 stream tcp nowait nobody /usr/sbin/kumina kumina 25900 25909 + +The two parameters of kumina denote the minimum and the maximum allowed +port numbers. This allows a single kumina instance to multiplex +connections to multiple VNC servers. diff -Nru websockify-0.3.0/other/websocket.c websockify-0.5.1+dfsg1/other/websocket.c --- websockify-0.3.0/other/websocket.c 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/other/websocket.c 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,802 @@ +/* + * WebSocket lib with support for "wss://" encryption. + * Copyright 2010 Joel Martin + * Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) + * + * You can make a cert/key with openssl using: + * openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem + * as taken from http://docs.python.org/dev/library/ssl.html#certificates + */ +#include +#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"); + } + +} + diff -Nru websockify-0.3.0/other/websocket.h websockify-0.5.1+dfsg1/other/websocket.h --- websockify-0.3.0/other/websocket.h 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/other/websocket.h 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,84 @@ +#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__); + diff -Nru websockify-0.3.0/other/websocket.rb websockify-0.5.1+dfsg1/other/websocket.rb --- websockify-0.3.0/other/websocket.rb 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/other/websocket.rb 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,456 @@ + +# Python WebSocket library with support for "wss://" encryption. +# Copyright 2011 Joel Martin +# Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) +# +# Supports following protocol versions: +# - http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75 +# - http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 +# - http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10 + +require 'gserver' +require 'stringio' +require 'digest/md5' +require 'digest/sha1' +require 'base64' + +class EClose < Exception +end + +class WebSocketServer < GServer + @@Buffer_size = 65536 + + # + # WebSocket constants + # + @@Server_handshake_hixie = "HTTP/1.1 101 Web Socket Protocol Handshake\r +Upgrade: WebSocket\r +Connection: Upgrade\r +%sWebSocket-Origin: %s\r +%sWebSocket-Location: %s://%s%s\r +" + + @@Server_handshake_hybi = "HTTP/1.1 101 Switching Protocols\r +Upgrade: websocket\r +Connection: Upgrade\r +Sec-WebSocket-Accept: %s\r +" + @@GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + + + def initialize(opts) + vmsg "in WebSocketServer.initialize" + port = opts['listen_port'] + host = opts['listen_host'] || GServer::DEFAULT_HOST + + super(port, host) + + @@client_id = 0 # Track client number total on class + + @verbose = opts['verbose'] + @opts = opts + end + + def serve(io) + @@client_id += 1 + + # Initialize per thread state + t = Thread.current + t[:my_client_id] = @@client_id + t[:send_parts] = [] + t[:recv_part] = nil + t[:base64] = nil + + puts "in serve, client: #{t[:client].inspect}" + + begin + t[:client] = do_handshake(io) + new_client(t[:client]) + rescue EClose => e + msg "Client closed: #{e.message}" + return + rescue Exception => e + msg "Uncaught exception: #{e.message}" + msg "Trace: #{e.backtrace}" + return + end + + msg "Client disconnected" + end + + # + # WebSocketServer logging/output functions + # + def traffic(token) + if @verbose then print token; STDOUT.flush; end + end + + def msg(msg) + puts "% 3d: %s" % [Thread.current[:my_client_id], msg] + end + + def vmsg(msg) + if @verbose then msg(msg) end + end + + # + # WebSocketServer general support routines + # + def gen_md5(h) + key1 = h['sec-websocket-key1'] + key2 = h['sec-websocket-key2'] + key3 = h['key3'] + spaces1 = key1.count(" ") + spaces2 = key2.count(" ") + num1 = key1.scan(/[0-9]/).join('').to_i / spaces1 + num2 = key2.scan(/[0-9]/).join('').to_i / spaces2 + + return Digest::MD5.digest([num1, num2, key3].pack('NNa8')) + end + + def unmask(buf, hlen, length) + pstart = hlen + 4 + mask = buf[hlen...hlen+4] + data = buf[pstart...pstart+length] + #data = data.bytes.zip(mask.bytes.cycle(length)).map { |d,m| d^m } + for i in (0...data.length) do + data[i] ^= mask[i%4] + end + return data + end + + def encode_hybi(buf, opcode, base64=false) + if base64 + buf = Base64.encode64(buf).gsub(/\n/, '') + end + + b1 = 0x80 | (opcode & 0x0f) # FIN + opcode + payload_len = buf.length + if payload_len <= 125 + header = [b1, payload_len].pack('CC') + elsif payload_len > 125 && payload_len < 65536 + header = [b1, 126, payload_len].pack('CCn') + elsif payload_len >= 65536 + header = [b1, 127, payload_len >> 32, + payload_len & 0xffffffff].pack('CCNN') + end + + return [header + buf, header.length, 0] + end + + def decode_hybi(buf, base64=false) + f = {'fin' => 0, + 'opcode' => 0, + 'hlen' => 2, + 'length' => 0, + 'payload' => nil, + 'left' => 0, + 'close_code' => nil, + 'close_reason' => nil} + + blen = buf.length + f['left'] = blen + + if blen < f['hlen'] then return f end # incomplete frame + + b1, b2 = buf.unpack('CC') + f['opcode'] = b1 & 0x0f + f['fin'] = (b1 & 0x80) >> 7 + has_mask = (b2 & 0x80) >> 7 + + f['length'] = b2 & 0x7f + + if f['length'] == 126 + f['hlen'] = 4 + if blen < f['hlen'] then return f end # incomplete frame + f['length'] = buf.unpack('xxn')[0] + elsif f['length'] == 127 + f['hlen'] = 10 + if blen < f['hlen'] then return f end # incomplete frame + top, bottom = buf.unpack('xxNN') + f['length'] = (top << 32) & bottom + end + + full_len = f['hlen'] + has_mask * 4 + f['length'] + + if blen < full_len then return f end # incomplete frame + + # number of bytes that are part of the next frame(s) + f['left'] = blen - full_len + + if has_mask > 0 + f['payload'] = unmask(buf, f['hlen'], f['length']) + else + f['payload'] = buf[f['hlen']...full_len] + end + + if base64 and [1, 2].include?(f['opcode']) + f['payload'] = Base64.decode64(f['payload']) + end + + # close frame + if f['opcode'] == 0x08 + if f['length'] >= 2 + f['close_code'] = f['payload'].unpack('n') + end + if f['length'] > 3 + f['close_reason'] = f['payload'][2...f['payload'].length] + end + end + + return f + end + + def encode_hixie(buf) + return ["\x00" + Base64.encode64(buf).gsub(/\n/, '') + "\xff", 1, 1] + end + + def decode_hixie(buf) + last = buf.index("\377") + return {'payload' => Base64.decode64(buf[1...last]), + 'hlen' => 1, + 'length' => last - 1, + 'left' => buf.length - (last + 1)} + end + + def send_frames(bufs) + t = Thread.current + if bufs.length > 0 + encbuf = "" + bufs.each do |buf| + if t[:version].start_with?("hybi") + if t[:base64] + encbuf, lenhead, lentail = encode_hybi( + buf, opcode=1, base64=true) + else + encbuf, lenhead, lentail = encode_hybi( + buf, opcode=2, base64=false) + end + else + encbuf, lenhead, lentail = encode_hixie(buf) + end + + t[:send_parts] << encbuf + end + + end + + while t[:send_parts].length > 0 + buf = t[:send_parts].shift + sent = t[:client].send(buf, 0) + + if sent == buf.length + traffic "<" + else + traffic "<." + t[:send_parts].unshift(buf[sent...buf.length]) + end + end + + return t[:send_parts].length + end + + # Receive and decode Websocket frames + # Returns: [bufs_list, closed_string] + def recv_frames() + t = Thread.current + closed = false + bufs = [] + + buf = t[:client].recv(@@Buffer_size) + + if buf.length == 0 + return bufs, "Client closed abrubtly" + end + + if t[:recv_part] + buf = t[:recv_part] + buf + t[:recv_part] = nil + end + + while buf.length > 0 + if t[:version].start_with?("hybi") + frame = decode_hybi(buf, base64=t[:base64]) + + if frame['payload'] == nil + traffic "}." + if frame['left'] > 0 + t[:recv_part] = buf[-frame['left']...buf.length] + end + break + else + if frame['opcode'] == 0x8 + closed = "Client closed, reason: %s - %s" % [ + frame['close_code'], frame['close_reason']] + break + end + end + else + if buf[0...2] == "\xff\x00": + closed = "Client sent orderly close frame" + break + elsif buf[0...2] == "\x00\xff": + buf = buf[2...buf.length] + continue # No-op frame + elsif buf.count("\xff") == 0 + # Partial frame + traffic "}." + t[:recv_part] = buf + break + end + + frame = decode_hixie(buf) + end + + #msg "Receive frame: #{frame.inspect}" + + traffic "}" + + bufs << frame['payload'] + + if frame['left'] > 0: + buf = buf[-frame['left']...buf.length] + else + buf = '' + end + end + + return bufs, closed + end + + + def send_close(code=nil, reason='') + t = Thread.current + if t[:version].start_with?("hybi") + msg = '' + if code + msg = [reason.length, code].pack("na8") + end + + buf, lenh, lent = encode_hybi(msg, opcode=0x08, base64=false) + t[:client].send(buf, 0) + elsif t[:version] == "hixie-76" + buf = "\xff\x00" + t[:client].send(buf, 0) + end + end + + def do_handshake(sock) + + t = Thread.current + stype = "" + + if !IO.select([sock], nil, nil, 3) + raise EClose, "ignoring socket not ready" + end + + handshake = sock.recv(1024, Socket::MSG_PEEK) + #msg "Handshake [#{handshake.inspect}]" + + if handshake == "" + raise(EClose, "ignoring empty handshake") + else + stype = "Plain non-SSL (ws://)" + scheme = "ws" + retsock = sock + sock.recv(1024) + end + + h = t[:headers] = {} + hlines = handshake.split("\r\n") + req_split = hlines.shift.match(/^(\w+) (\/[^\s]*) HTTP\/1\.1$/) + t[:path] = req_split[2].strip + hlines.each do |hline| + break if hline == "" + hsplit = hline.match(/^([^:]+):\s*(.+)$/) + h[hsplit[1].strip.downcase] = hsplit[2] + end + #puts "Headers: #{h.inspect}" + + unless h.has_key?('upgrade') && + h['upgrade'].downcase == 'websocket' + raise EClose, "Non-WebSocket connection" + end + + protocols = h.fetch("sec-websocket-protocol", h["websocket-protocol"]) + ver = h.fetch('sec-websocket-version', nil) + + if ver + # HyBi/IETF vesrion of the protocol + + # HyBi 07 reports version 7 + # HyBi 08 - 12 report version 8 + # HyBi 13 and up report version 13 + if ['7', '8', '13'].include?(ver) + t[:version] = "hybi-%02d" % [ver.to_i] + else + raise EClose, "Unsupported protocol version %s" % [ver] + end + + # choose binary if client supports it + if protocols.include?('binary') + t[:base64] = false + elsif protocols.include?('base64') + t[:base64] = true + else + raise EClose, "Client must support 'binary' or 'base64' sub-protocol" + end + + key = h['sec-websocket-key'] + + # Generate the hash value for the accpet header + accept = Base64.encode64( + Digest::SHA1.digest(key + @@GUID)).gsub(/\n/, '') + + response = @@Server_handshake_hybi % [accept] + + if t[:base64] + response += "Sec-WebSocket-Protocol: base64\r\n" + else + response += "Sec-WebSocket-Protocol: binary\r\n" + end + response += "\r\n" + + else + # Hixie vesrion of the protocol (75 or 76) + body = handshake.match(/\r\n\r\n(........)/) + if body + h['key3'] = body[1] + trailer = gen_md5(h) + pre = "Sec-" + t[:version] = "hixie-76" + else + trailer = "" + pre = "" + t[:version] = "hixie-75" + end + + # base64 required for Hixie since payload is only UTF-8 + t[:base64] = true + + response = @@Server_handshake_hixie % [pre, h['origin'], pre, + "ws", h['host'], t[:path]] + + if protocols && protocols.include?('base64') + response += "%sWebSocket-Protocol: base64\r\n" % [pre] + else + msg "Warning: client does not report 'base64' protocol support" + end + + response += "\r\n" + trailer + end + + msg "%s WebSocket connection" % [stype] + msg "Version %s, base64: '%s'" % [t[:version], t[:base64]] + if t[:path] then msg "Path: '%s'" % [t[:path]] end + + #puts "sending reponse #{response.inspect}" + retsock.send(response, 0) + + # Return the WebSocket socket which may be SSL wrapped + return retsock + end + +end + +# vim: sw=2 diff -Nru websockify-0.3.0/other/websockify.c websockify-0.5.1+dfsg1/other/websockify.c --- websockify-0.3.0/other/websockify.c 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/other/websockify.c 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,385 @@ +/* + * A WebSocket to TCP socket proxy with support for "wss://" encryption. + * Copyright 2010 Joel Martin + * Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) + * + * You can make a cert/key with openssl using: + * openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem + * as taken from http://docs.python.org/dev/library/ssl.html#certificates + */ +#include +#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(); + +} diff -Nru websockify-0.3.0/other/websockify.clj websockify-0.5.1+dfsg1/other/websockify.clj --- websockify-0.3.0/other/websockify.clj 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/other/websockify.clj 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,233 @@ +(ns websockify + ;(:use ring.adapter.jetty) + (:require [clojure.tools.cli :as cli] + [clojure.string :as string]) + + (:import + + ;; Netty TCP Client + [java.util.concurrent Executors] + [java.net InetSocketAddress] + [org.jboss.netty.channel + Channels SimpleChannelHandler ChannelPipelineFactory] + [org.jboss.netty.buffer ChannelBuffers] + [org.jboss.netty.channel.socket.nio NioClientSocketChannelFactory] + [org.jboss.netty.bootstrap ClientBootstrap] + [org.jboss.netty.handler.codec.base64 Base64] + [org.jboss.netty.util CharsetUtil] + + ;; Jetty WebSocket Server + [org.eclipse.jetty.server Server] + [org.eclipse.jetty.server.nio BlockingChannelConnector] + [org.eclipse.jetty.servlet + ServletContextHandler ServletHolder DefaultServlet] + [org.eclipse.jetty.websocket + WebSocket WebSocket$OnTextMessage + WebSocketClientFactory WebSocketClient WebSocketServlet])) + + +;; TCP / NIO + +;; (defn tcp-channel [host port] +;; (try +;; (let [address (InetSocketAddress. host port) +;; channel (doto (SocketChannel/open) +;; (.connect address))] +;; channel) +;; (catch Exception e +;; (println (str "Failed to connect to'" host ":" port "':" e)) +;; nil))) + +;; http://docs.jboss.org/netty/3.2/guide/html/start.html#d0e51 +;; http://stackoverflow.com/questions/5453602/highly-concurrent-http-with-netty-and-nio +;; https://github.com/datskos/ring-netty-adapter/blob/master/src/ring/adapter/netty.clj + + +(defn netty-client [host port open close message] + (let [handler (proxy [SimpleChannelHandler] [] + (channelConnected [ctx e] (open ctx e)) + (channelDisconnected [ctx e] (close ctx e)) + (messageReceived [ctx e] (message ctx e)) + (exceptionCaught [ctx e] + (println "exceptionCaught:" e))) + pipeline (proxy [ChannelPipelineFactory] [] + (getPipeline [] + (doto (Channels/pipeline) + (.addLast "handler" handler)))) + bootstrap (doto (ClientBootstrap. + (NioClientSocketChannelFactory. + (Executors/newCachedThreadPool) + (Executors/newCachedThreadPool))) + (.setPipelineFactory pipeline) + (.setOption "tcpNoDelay" true) + (.setOption "keepAlive" true)) + channel-future (.connect bootstrap (InetSocketAddress. host port)) + channel (.. channel-future (awaitUninterruptibly) (getChannel))] + channel)) + + + +;; WebSockets + +;; http://wiki.eclipse.org/Jetty/Feature/WebSockets +(defn make-websocket-servlet [open close message] + (proxy [WebSocketServlet] [] + (doGet [request response] + ;;(println "doGet" request) + (.. (proxy-super getServletContext) + (getNamedDispatcher (proxy-super getServletName)) + (forward request response))) + (doWebSocketConnect [request response] + (println "doWebSocketConnect") + (reify WebSocket$OnTextMessage + (onOpen [this connection] (open this connection)) + (onClose [this code message] (close this code message)) + (onMessage [this data] (message this data)))))) + +(defn websocket-server + [port & {:keys [open close message ws-path web] + :or {open (fn [_ conn] + (println "New websocket client:" conn)) + close (fn [_ code reason] + (println "Websocket client closed:" code reason)) + message (fn [_ data] + (println "Websocket message:" data)) + + ws-path "/websocket"}}] + (let [http-servlet (doto (ServletHolder. (DefaultServlet.)) + (.setInitParameter "dirAllowed" "true") + (.setInitParameter "resourceBase" web)) + ws-servlet (ServletHolder. + (make-websocket-servlet open close message)) + context (doto (ServletContextHandler.) + (.setContextPath "/") + (.addServlet ws-servlet ws-path)) + connector (doto (BlockingChannelConnector.) + (.setPort port) + (.setMaxIdleTime Integer/MAX_VALUE)) + server (doto (Server.) + (.setHandler context) + (.addConnector connector))] + + (when web (.addServlet context http-servlet "/")) + server)) + + + +;; Websockify + +(defonce settings (atom {})) + +;; WebSocket client to TCP target mappings + +(defonce clients (atom {})) +(defonce targets (atom {})) + + +(defn target-open [ctx e] + (println "Connected to target") + #_(println "channelConnected:" e)) + +(defn target-close [ctx e] + #_(println "channelDisconnected:" e) + (println "Target closed") + (when-let [channel (get @targets (.getChannel ctx))] + (.disconnect channel))) + +(defn target-message [ctx e] + (let [channel (.getChannel ctx) + client (get @targets channel) + msg (.getMessage e) + len (.readableBytes msg) + b64 (Base64/encode msg false) + blen (.readableBytes b64)] + #_(println "received" len "bytes from target") + #_(println "target receive:" (.toString msg 0 len CharsetUtil/UTF_8)) + #_(println "sending to client:" (.toString b64 0 blen CharsetUtil/UTF_8)) + (.sendMessage client (.toString b64 0 blen CharsetUtil/UTF_8)))) + +(defn client-open [this connection] + #_(println "Got WebSocket connection:" connection) + (println "New client") + (let [target (netty-client + (:target-host @settings) + (:target-port @settings) + target-open target-close target-message)] + (swap! clients assoc this {:client connection + :target target}) + (swap! targets assoc target connection))) + +(defn client-close [this code message] + (println "WebSocket connection closed") + (when-let [target (:target (get @clients this))] + (println "Closing target") + (.close target) + (println "Target closed") + (swap! targets dissoc target)) + (swap! clients dissoc this)) + +(defn client-message [this data] + #_(println "WebSocket onMessage:" data) + (let [target (:target (get @clients this)) + cbuf (ChannelBuffers/copiedBuffer data CharsetUtil/UTF_8) + decbuf (Base64/decode cbuf) + rlen (.readableBytes decbuf)] + #_(println "Sending" rlen "bytes to target") + #_(println "Sending to target:" (.toString decbuf 0 rlen CharsetUtil/UTF_8)) + (.write target decbuf))) + +(defn start-websockify + [& {:keys [listen-port target-host target-port web] + :or {listen-port 6080 + target-host "localhost" + target-port 5900 + }}] + + (reset! clients {}) + (reset! targets {}) + + (reset! settings {:target-host target-host + :target-port target-port}) + (let [server (websocket-server listen-port + :web web + :ws-path "/websockify" + :open client-open + :close client-close + :message client-message)] + + (.start server) + + (if web + (println "Serving web requests from:" web) + (println "Not serving web requests")) + + (defn stop-websockify [] + (doseq [client (vals @clients)] + (.disconnect (:client client)) + (.close (:target client))) + (.stop server) + (reset! clients {}) + (reset! targets {}) + nil))) + +(defn -main [& args] + (let [[options args banner] + (cli/cli + args + ["-v" "--[no-]verbose" "Verbose output"] + ["--web" "Run webserver with root at given location"] + ["-h" "--help" "Show help" :default false :flag true] + )] + (when (or (:help options) + (not= 2 (count args))) + (println banner) + (System/exit 0)) + (println options) + (println args) + (let [target (second args) + [target-host target-port] (string/split target #":")] + (start-websockify :listen-port (Integer/parseInt (first args)) + :target-host target-host + :target-port (Integer/parseInt target-port) + :web (:web options)))) + nil) \ No newline at end of file diff -Nru websockify-0.3.0/other/websockify.rb websockify-0.5.1+dfsg1/other/websockify.rb --- websockify-0.3.0/other/websockify.rb 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/other/websockify.rb 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,171 @@ +#!/usr/bin/env ruby + +# A WebSocket to TCP socket proxy +# Copyright 2011 Joel Martin +# Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) + +require 'socket' +$: << "other" +$: << "../other" +require 'websocket' +require 'optparse' + +# Proxy traffic to and from a WebSockets client to a normal TCP +# socket server target. All traffic to/from the client is base64 +# encoded/decoded to allow binary data to be sent/received to/from +# the target. +class WebSocketProxy < WebSocketServer + + @@Traffic_legend = " +Traffic Legend: + } - Client receive + }. - Client receive partial + { - Target receive + + > - Target send + >. - Target send partial + < - Client send + <. - Client send partial +" + + + def initialize(opts) + vmsg "in WebSocketProxy.initialize" + + super(opts) + + @target_host = opts["target_host"] + @target_port = opts["target_port"] + end + + # Echo back whatever is received + def new_client(client) + + msg "connecting to: %s:%s" % [@target_host, @target_port] + tsock = TCPSocket.open(@target_host, @target_port) + + if @verbose then puts @@Traffic_legend end + + begin + do_proxy(client, tsock) + rescue + tsock.shutdown(Socket::SHUT_RDWR) + tsock.close + raise + end + end + + # Proxy client WebSocket to normal target socket. + def do_proxy(client, target) + cqueue = [] + c_pend = 0 + tqueue = [] + rlist = [client, target] + + loop do + wlist = [] + + if tqueue.length > 0 + wlist << target + end + if cqueue.length > 0 || c_pend > 0 + wlist << client + end + + ins, outs, excepts = IO.select(rlist, wlist, nil, 0.001) + if excepts && excepts.length > 0 + raise Exception, "Socket exception" + end + + # Send queued client data to the target + if outs && outs.include?(target) + dat = tqueue.shift + sent = target.send(dat, 0) + if sent == dat.length + traffic ">" + else + tqueue.unshift(dat[sent...dat.length]) + traffic ".>" + end + end + + # Receive target data and queue for the client + if ins && ins.include?(target) + buf = target.recv(@@Buffer_size) + if buf.length == 0: + raise EClose, "Target closed" + end + + cqueue << buf + traffic "{" + end + + # Encode and send queued data to the client + if outs && outs.include?(client) + c_pend = send_frames(cqueue) + cqueue = [] + end + + # Receive client data, decode it, and send it back + if ins && ins.include?(client) + frames, closed = recv_frames + tqueue += frames + + if closed + send_close + raise EClose, closed + end + end + + end # loop + end +end + +# Parse parameters +opts = {} +parser = OptionParser.new do |o| + o.on('--verbose', '-v') { |b| opts['verbose'] = b } + o.parse! +end + +if ARGV.length < 2: + puts "Too few arguments" + exit 2 +end + +# Parse host:port and convert ports to numbers +if ARGV[0].count(":") > 0 + opts['listen_host'], _, opts['listen_port'] = ARGV[0].rpartition(':') +else + opts['listen_host'], opts['listen_port'] = nil, ARGV[0] +end + +begin + opts['listen_port'] = opts['listen_port'].to_i +rescue + puts "Error parsing listen port" + exit 2 +end + +if ARGV[1].count(":") > 0 + opts['target_host'], _, opts['target_port'] = ARGV[1].rpartition(':') +else + puts "Error parsing target" + exit 2 +end + +begin + opts['target_port'] = opts['target_port'].to_i +rescue + puts "Error parsing target port" + exit 2 +end + +puts "Starting server on #{opts['listen_host']}:#{opts['listen_port']}" +server = WebSocketProxy.new(opts) +server.start(100) +server.join + +puts "Server has been terminated" + +# vim: sw=2 diff -Nru websockify-0.3.0/other/wswrap websockify-0.5.1+dfsg1/other/wswrap --- websockify-0.3.0/other/wswrap 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/other/wswrap 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + +usage() { + echo "Usage: $(basename $0) PORT CMDLINE" + echo + echo " PORT Port to wrap with WebSockets support" + echo " CMDLINE Command line to wrap" + exit 2 +} + +# Parameter defaults +mydir=$(readlink -f $(dirname ${0})) + +# Process parameters +#while [ "${1}" != "${1#-}" ]; do +# param=$1; shift +#done + +export WSWRAP_PORT="${1}"; shift + +LD_PRELOAD=${mydir}/wswrapper.so "${@}" + diff -Nru websockify-0.3.0/PKG-INFO websockify-0.5.1+dfsg1/PKG-INFO --- websockify-0.3.0/PKG-INFO 2013-01-15 17:43:55.000000000 +0000 +++ websockify-0.5.1+dfsg1/PKG-INFO 1970-01-01 00:00:00.000000000 +0000 @@ -1,213 +0,0 @@ -Metadata-Version: 1.0 -Name: websockify -Version: 0.3.0 -Summary: Websockify. -Home-page: https://github.com/kanaka/websockify -Author: Joel Martin -Author-email: github@martintribe.org -License: LGPLv3 -Description: ## websockify: WebSockets support for any application/server - - websockify was formerly named wsproxy and was part of the - [noVNC](https://github.com/kanaka/noVNC) project. - - At the most basic level, websockify just translates WebSockets traffic - to normal socket traffic. Websockify accepts the WebSockets handshake, - parses it, and then begins forwarding traffic between the client and - the target in both directions. - - ### WebSockets binary data - - Websockify supports all versions of the WebSockets protocol (Hixie and - HyBi). The older Hixie versions of the protocol only support UTF-8 - text payloads. In order to transport binary data over UTF-8 an - encoding must used to encapsulate the data within UTF-8. - - With Hixie clients, Websockify uses base64 to encode all traffic to - and from the client. This does not affect the data between websockify - and the server. - - With HyBi clients, 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. - - `./websockify 2023 -- PROGRAM ARGS` - - The `--wrap-mode` option can be used to indicate what action to take - when the wrapped program exits or daemonizes. - - Here is an example of using websockify to wrap the vncserver command - (which backgrounds itself) for use with - [noVNC](https://github.com/kanaka/noVNC): - - `./websockify 5901 --wrap-mode=ignore -- vncserver -geometry 1024x768 :1` - - Here is an example of wrapping telnetd (from krb5-telnetd).telnetd - exits after the connection closes so the wrap mode is set to respawn - the command: - - `sudo ./websockify 2023 --wrap-mode=respawn -- telnetd -debug 2023` - - The `wstelnet.html` page demonstrates a simple WebSockets based telnet - client. - - - ### Building the Python ssl module (for python 2.5 and older) - - * Install the build dependencies. On Ubuntu use this command: - - `sudo aptitude install python-dev bluetooth-dev` - - * Download, build the ssl module and symlink to it: - - `cd websockify/` - - `wget http://pypi.python.org/packages/source/s/ssl/ssl-1.15.tar.gz` - - `tar xvzf ssl-1.15.tar.gz` - - `cd ssl-1.15` - - `make` - - `cd ../` - - `ln -sf ssl-1.15/build/lib.linux-*/ssl ssl` - - - Changes - ======= - - 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. - - - -Keywords: noVNC websockify -Platform: UNKNOWN -Classifier: Programming Language :: Python diff -Nru websockify-0.3.0/README.md websockify-0.5.1+dfsg1/README.md --- websockify-0.3.0/README.md 2012-10-29 22:18:10.000000000 +0000 +++ websockify-0.5.1+dfsg1/README.md 2013-09-12 14:43:43.000000000 +0000 @@ -10,24 +10,17 @@ ### 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. +Starting with websockify 0.5.0, only the HyBi / IETF +6455 WebSocket protocol is supported. -With Hixie clients, Websockify uses base64 to encode all traffic to -and from the client. This does not affect the data between websockify -and the server. - -With HyBi clients, 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. +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://) diff -Nru websockify-0.3.0/rebind websockify-0.5.1+dfsg1/rebind --- websockify-0.3.0/rebind 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/rebind 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +usage() { + echo "Usage: $(basename $0) OLD_PORT NEW_PORT COMMAND_LINE" + echo + echo "Launch COMMAND_LINE, but intercept system calls to bind" + echo "to OLD_PORT and instead bind them to localhost:NEW_PORT" + exit 2 +} + +# Parameter defaults +mydir=$(readlink -f $(dirname ${0})) + +export REBIND_PORT_OLD="${1}"; shift +export REBIND_PORT_NEW="${1}"; shift + +LD_PRELOAD=${mydir}/rebind.so "${@}" + diff -Nru websockify-0.3.0/rebind.c websockify-0.5.1+dfsg1/rebind.c --- websockify-0.3.0/rebind.c 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/rebind.c 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,94 @@ +/* + * rebind: Intercept bind calls and bind to a different port + * Copyright 2010 Joel Martin + * Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) + * + * Overload (LD_PRELOAD) bind system call. If REBIND_PORT_OLD and + * REBIND_PORT_NEW environment variables are set then bind on the new + * port (of localhost) instead of the old port. + * + * This allows a 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; +} diff -Nru websockify-0.3.0/run websockify-0.5.1+dfsg1/run --- websockify-0.3.0/run 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/run 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,5 @@ +#!/usr/bin/python + +import websockify + +websockify.websocketproxy.websockify_init() diff -Nru websockify-0.3.0/setup.cfg websockify-0.5.1+dfsg1/setup.cfg --- websockify-0.3.0/setup.cfg 2013-01-15 17:43:55.000000000 +0000 +++ websockify-0.5.1+dfsg1/setup.cfg 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -[egg_info] -tag_build = -tag_date = 0 -tag_svn_revision = 0 - diff -Nru websockify-0.3.0/setup.py websockify-0.5.1+dfsg1/setup.py --- websockify-0.3.0/setup.py 2013-01-15 17:34:30.000000000 +0000 +++ websockify-0.5.1+dfsg1/setup.py 2013-09-12 14:43:43.000000000 +0000 @@ -1,6 +1,6 @@ from setuptools import setup, find_packages -version = '0.3.0' +version = '0.5.1' name = 'websockify' long_description = open("README.md").read() + "\n" + \ open("CHANGES.txt").read() + "\n" @@ -12,6 +12,14 @@ 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", diff -Nru websockify-0.3.0/tests/b64_vs_utf8.py websockify-0.5.1+dfsg1/tests/b64_vs_utf8.py --- websockify-0.3.0/tests/b64_vs_utf8.py 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/b64_vs_utf8.py 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,29 @@ +#!/usr/bin/env python + +from base64 import b64encode, b64decode +from codecs import (utf_8_encode, utf_8_decode, + latin_1_encode, latin_1_decode) +import random, time + +buf_len = 10000 +iterations = 10000 + +print "Generating random input buffer" +r = random.Random() +buf = "".join([chr(r.randint(0, 255)) for i in range(buf_len)]) + +tests = {'UTF8 encode': lambda: utf_8_encode(unicode(buf, 'latin-1'))[0], + 'B64 encode': lambda: b64encode(buf)} +utf8_buf = tests['UTF8 encode']() +b64_buf = tests['B64 encode']() +tests.update({'UTF8 decode': lambda: latin_1_encode(utf_8_decode(utf8_buf)[0])[0], + 'B64 decode': lambda: b64decode(b64_buf)}) + +print "Running tests" +for test in 'UTF8 encode', 'B64 encode', 'UTF8 decode', 'B64 decode': + start = time.time() + for i in range(iterations): + res_buf = tests[test]() + print "%s took %s seconds (result size %s)" % ( + test, (time.time() - start), len(res_buf)) + diff -Nru websockify-0.3.0/tests/base64.html websockify-0.5.1+dfsg1/tests/base64.html --- websockify-0.3.0/tests/base64.html 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/base64.html 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,91 @@ + + + + Native Base64 Tests + + + + + +

Native Base64 Tests

+ +
+ Messages:
+ + +
+ + + diff -Nru websockify-0.3.0/tests/base64.js websockify-0.5.1+dfsg1/tests/base64.js --- websockify-0.3.0/tests/base64.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/base64.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,12 @@ +// The following results in 'hello [MANGLED]' +// +// Filed as https://github.com/ry/node/issues/issue/402 + +var sys = require("sys"), + buf = new Buffer(1024), len, + str1 = "aGVsbG8g", // 'hello ' + str2 = "d29ybGQ=", // 'world' + +len = buf.write(str1, 0, 'base64'); +len += buf.write(str2, len, 'base64'); +sys.log("decoded result: " + buf.toString('binary', 0, len)); diff -Nru websockify-0.3.0/tests/echo.html websockify-0.5.1+dfsg1/tests/echo.html --- websockify-0.3.0/tests/echo.html 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/echo.html 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,148 @@ + + + + WebSockets Echo Test + + + + + + + + + + + + + Host:   + Port:   + Encrypt:   +   + + +
+ Log:
+ + + + + + + diff -Nru websockify-0.3.0/tests/echo.py websockify-0.5.1+dfsg1/tests/echo.py --- websockify-0.3.0/tests/echo.py 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/echo.py 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,75 @@ +#!/usr/bin/env python + +''' +A WebSocket server that echos back whatever it receives from the client. +Copyright 2010 Joel Martin +Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) + +You can make a cert/key with openssl using: +openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem +as taken from http://docs.python.org/dev/library/ssl.html#certificates +''' + +import os, sys, select, optparse +sys.path.insert(0,os.path.dirname(__file__) + "/../websockify") +from websocket import WebSocketServer + +class WebSocketEcho(WebSocketServer): + """ + WebSockets server that echos back whatever is received from the + client. """ + buffer_size = 8096 + + def new_client(self): + """ + Echo back whatever is received. + """ + + cqueue = [] + c_pend = 0 + cpartial = "" + rlist = [self.client] + + while True: + wlist = [] + + if cqueue or c_pend: wlist.append(self.client) + ins, outs, excepts = select.select(rlist, wlist, [], 1) + if excepts: raise Exception("Socket exception") + + if self.client in outs: + # Send queued target data to the client + c_pend = self.send_frames(cqueue) + cqueue = [] + + if self.client in ins: + # Receive client data, decode it, and send it back + frames, closed = self.recv_frames() + cqueue.extend(frames) + + if closed: + self.send_close() + raise self.EClose(closed) + +if __name__ == '__main__': + parser = optparse.OptionParser(usage="%prog [options] listen_port") + parser.add_option("--verbose", "-v", action="store_true", + help="verbose messages and per frame traffic") + parser.add_option("--cert", default="self.pem", + help="SSL certificate file") + parser.add_option("--key", default=None, + help="SSL key file (if separate from cert)") + parser.add_option("--ssl-only", action="store_true", + help="disallow non-encrypted connections") + (opts, args) = parser.parse_args() + + try: + if len(args) != 1: raise + opts.listen_port = int(args[0]) + except: + parser.error("Invalid arguments") + + opts.web = "." + server = WebSocketEcho(**opts.__dict__) + server.start_server() + diff -Nru websockify-0.3.0/tests/echo.rb websockify-0.5.1+dfsg1/tests/echo.rb --- websockify-0.3.0/tests/echo.rb 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/echo.rb 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,62 @@ +#!/usr/bin/env ruby + +# A WebSocket server that echos back whatever it receives from the client. +# Copyright 2011 Joel Martin +# Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) + +require 'socket' +$: << "other" +$: << "../other" +require 'websocket' + +class WebSocketEcho < WebSocketServer + + # Echo back whatever is received + def new_client(client) + + cqueue = [] + c_pend = 0 + rlist = [client] + + loop do + wlist = [] + + if cqueue.length > 0 or c_pend + wlist << client + end + + ins, outs, excepts = IO.select(rlist, wlist, nil, 1) + if excepts.length > 0 + raise Exception, "Socket exception" + end + + if outs.include?(client) + # Send queued data to the client + c_pend = send_frames(cqueue) + cqueue = [] + end + + if ins.include?(client) + # Receive client data, decode it, and send it back + frames, closed = recv_frames + cqueue += frames + + if closed + raise EClose, closed + end + end + + end # loop + end +end + +port = ARGV[0].to_i +puts "Starting server on port #{port}" + +server = WebSocketEcho.new('listen_port' => port, 'verbose' => true) +server.start +server.join + +puts "Server has been terminated" + +# vim: sw=2 diff -Nru websockify-0.3.0/tests/include/base64.js websockify-0.5.1+dfsg1/tests/include/base64.js --- websockify-0.3.0/tests/include/base64.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/include/base64.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,114 @@ +/* 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 */ diff -Nru websockify-0.3.0/tests/include/keysym.js websockify-0.5.1+dfsg1/tests/include/keysym.js --- websockify-0.3.0/tests/include/keysym.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/include/keysym.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,99 @@ +/* + * from noVNC: HTML5 VNC client + * Copyright (C) 2010 Joel Martin + * Licensed under LGPL-3 (see LICENSE.txt) + */ + +/* Translate DOM key down/up event to keysym value */ +function getKeysym(e) { + var evt, keysym; + evt = (e ? e : window.event); + + /* Remap modifier and special keys */ + switch ( evt.keyCode ) { + case 8 : keysym = 0xFF08; break; // BACKSPACE + case 9 : keysym = 0xFF09; break; // TAB + case 13 : keysym = 0xFF0D; break; // ENTER + case 27 : keysym = 0xFF1B; break; // ESCAPE + case 45 : keysym = 0xFF63; break; // INSERT + case 46 : keysym = 0xFFFF; break; // DELETE + case 36 : keysym = 0xFF50; break; // HOME + case 35 : keysym = 0xFF57; break; // END + case 33 : keysym = 0xFF55; break; // PAGE_UP + case 34 : keysym = 0xFF56; break; // PAGE_DOWN + case 37 : keysym = 0xFF51; break; // LEFT + case 38 : keysym = 0xFF52; break; // UP + case 39 : keysym = 0xFF53; break; // RIGHT + case 40 : keysym = 0xFF54; break; // DOWN + case 112 : keysym = 0xFFBE; break; // F1 + case 113 : keysym = 0xFFBF; break; // F2 + case 114 : keysym = 0xFFC0; break; // F3 + case 115 : keysym = 0xFFC1; break; // F4 + case 116 : keysym = 0xFFC2; break; // F5 + case 117 : keysym = 0xFFC3; break; // F6 + case 118 : keysym = 0xFFC4; break; // F7 + case 119 : keysym = 0xFFC5; break; // F8 + case 120 : keysym = 0xFFC6; break; // F9 + case 121 : keysym = 0xFFC7; break; // F10 + case 122 : keysym = 0xFFC8; break; // F11 + case 123 : keysym = 0xFFC9; break; // F12 + case 16 : keysym = 0xFFE1; break; // SHIFT + case 17 : keysym = 0xFFE3; break; // CONTROL + //case 18 : keysym = 0xFFE7; break; // Left Meta (Mac Option) + case 18 : keysym = 0xFFE9; break; // Left ALT (Mac Command) + default : keysym = evt.keyCode; break; + } + + /* Remap symbols */ + switch (keysym) { + case 186 : keysym = 59; break; // ; (IE) + case 187 : keysym = 61; break; // = (IE) + case 188 : keysym = 44; break; // , (Mozilla, IE) + case 109 : // - (Mozilla) + if (Util.Engine.gecko) { + keysym = 45; } + break; + case 189 : keysym = 45; break; // - (IE) + case 190 : keysym = 46; break; // . (Mozilla, IE) + case 191 : keysym = 47; break; // / (Mozilla, IE) + case 192 : keysym = 96; break; // ` (Mozilla, IE) + case 219 : keysym = 91; break; // [ (Mozilla, IE) + case 220 : keysym = 92; break; // \ (Mozilla, IE) + case 221 : keysym = 93; break; // ] (Mozilla, IE) + case 222 : keysym = 39; break; // ' (Mozilla, IE) + } + + /* Remap shifted and unshifted keys */ + if (!!evt.shiftKey) { + switch (keysym) { + case 48 : keysym = 41 ; break; // ) (shifted 0) + case 49 : keysym = 33 ; break; // ! (shifted 1) + case 50 : keysym = 64 ; break; // @ (shifted 2) + case 51 : keysym = 35 ; break; // # (shifted 3) + case 52 : keysym = 36 ; break; // $ (shifted 4) + case 53 : keysym = 37 ; break; // % (shifted 5) + case 54 : keysym = 94 ; break; // ^ (shifted 6) + case 55 : keysym = 38 ; break; // & (shifted 7) + case 56 : keysym = 42 ; break; // * (shifted 8) + case 57 : keysym = 40 ; break; // ( (shifted 9) + + case 59 : keysym = 58 ; break; // : (shifted `) + case 61 : keysym = 43 ; break; // + (shifted ;) + case 44 : keysym = 60 ; break; // < (shifted ,) + case 45 : keysym = 95 ; break; // _ (shifted -) + case 46 : keysym = 62 ; break; // > (shifted .) + case 47 : keysym = 63 ; break; // ? (shifted /) + case 96 : keysym = 126; break; // ~ (shifted `) + case 91 : keysym = 123; break; // { (shifted [) + case 92 : keysym = 124; break; // | (shifted \) + case 93 : keysym = 125; break; // } (shifted ]) + case 39 : keysym = 34 ; break; // " (shifted ') + } + } else if ((keysym >= 65) && (keysym <=90)) { + /* Remap unshifted A-Z */ + keysym += 32; + } + + return keysym; +} + diff -Nru websockify-0.3.0/tests/include/util.js websockify-0.5.1+dfsg1/tests/include/util.js --- websockify-0.3.0/tests/include/util.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/include/util.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,379 @@ +/* + * 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}; +}()); diff -Nru websockify-0.3.0/tests/include/VT100.js websockify-0.5.1+dfsg1/tests/include/VT100.js --- websockify-0.3.0/tests/include/VT100.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/include/VT100.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,919 @@ +// VT100.js -- a text terminal emulator in JavaScript with a ncurses-like +// interface and a POSIX-like interface. (The POSIX-like calls are +// implemented on top of the ncurses-like calls, not the other way round.) +// +// Released under the GNU LGPL v2.1, by Frank Bi +// +// 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"); +} diff -Nru websockify-0.3.0/tests/include/web-socket-js/README.txt websockify-0.5.1+dfsg1/tests/include/web-socket-js/README.txt --- websockify-0.3.0/tests/include/web-socket-js/README.txt 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/include/web-socket-js/README.txt 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,109 @@ +* How to try + +Assuming you have Web server (e.g. Apache) running at http://example.com/ . + +- Download web_socket.rb from: + http://github.com/gimite/web-socket-ruby/tree/master +- Run sample Web Socket server (echo server) in example.com with: (#1) + $ ruby web-socket-ruby/samples/echo_server.rb example.com 10081 +- If your server already provides socket policy file at port 843, modify the file to allow access to port 10081. Otherwise you can skip this step. See below for details. +- Publish the web-socket-js directory with your Web server (e.g. put it in ~/public_html). +- Change ws://localhost:10081 to ws://example.com:10081 in sample.html. +- Open sample.html in your browser. +- After "onopen" is shown, input something, click [Send] and confirm echo back. + +#1: First argument of echo_server.rb means that it accepts Web Socket connection from HTML pages in example.com. + + +* Troubleshooting + +If it doesn't work, try these: + +1. Try Chrome and Firefox 3.x. +- It doesn't work on Chrome: +-- It's likely an issue of your code or the server. Debug your code as usual e.g. using console.log. +- It works on Chrome but it doesn't work on Firefox: +-- It's likely an issue of web-socket-js specific configuration (e.g. 3 and 4 below). +- It works on both Chrome and Firefox, but it doesn't work on your browser: +-- Check "Supported environment" section below. Your browser may not be supported by web-socket-js. + +2. Add this line before your code: + WEB_SOCKET_DEBUG = true; +and use Developer Tools (Chrome/Safari) or Firebug (Firefox) to see if console.log outputs any errors. + +3. Make sure you do NOT open your HTML page as local file e.g. file:///.../sample.html. web-socket-js doesn't work on local file. Open it via Web server e.g. http:///.../sample.html. + +4. If you are NOT using web-socket-ruby as your WebSocket server, you need to place Flash socket policy file on your server. See "Flash socket policy file" section below for details. + +5. Check if sample.html bundled with web-socket-js works. + +6. Make sure the port used for WebSocket (10081 in example above) is not blocked by your server/client's firewall. + +7. Install debugger version of Flash Player available here to see Flash errors: +http://www.adobe.com/support/flashplayer/downloads.html + + +* Supported environments + +It should work on: +- Google Chrome 4 or later (just uses native implementation) +- Firefox 3.x, Internet Explorer 8 + Flash Player 9 or later + +It may or may not work on other browsers such as Safari, Opera or IE 6. Patch for these browsers are appreciated, but I will not work on fixing issues specific to these browsers by myself. + + +* Flash socket policy file + +This implementation uses Flash's socket, which means that your server must provide Flash socket policy file to declare the server accepts connections from Flash. + +If you use web-socket-ruby available at +http://github.com/gimite/web-socket-ruby/tree/master +, you don't need anything special, because web-socket-ruby handles Flash socket policy file request. But if you already provide socket policy file at port 843, you need to modify the file to allow access to Web Socket port, because it precedes what web-socket-ruby provides. + +If you use other Web Socket server implementation, you need to provide socket policy file yourself. See +http://www.lightsphere.com/dev/articles/flash_socket_policy.html +for details and sample script to run socket policy file server. node.js implementation is available here: +http://github.com/LearnBoost/Socket.IO-node/blob/master/lib/socket.io/transports/flashsocket.js + +Actually, it's still better to provide socket policy file at port 843 even if you use web-socket-ruby. Flash always try to connect to port 843 first, so providing the file at port 843 makes startup faster. + + +* Cookie considerations + +Cookie is sent if Web Socket host is the same as the origin of JavaScript. Otherwise it is not sent, because I don't know way to send right Cookie (which is Cookie of the host of Web Socket, I heard). + +Note that it's technically possible that client sends arbitrary string as Cookie and any other headers (by modifying this library for example) once you place Flash socket policy file in your server. So don't trust Cookie and other headers if you allow connection from untrusted origin. + + +* Proxy considerations + +The WebSocket spec (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol) specifies instructions for User Agents to support proxied connections by implementing the HTTP CONNECT method. + +The AS3 Socket class doesn't implement this mechanism, which renders it useless for the scenarios where the user trying to open a socket is behind a proxy. + +The class RFC2817Socket (by Christian Cantrell) effectively lets us implement this, as long as the proxy settings are known and provided by the interface that instantiates the WebSocket. As such, if you want to support proxied conncetions, you'll have to supply this information to the WebSocket constructor when Flash is being used. One way to go about it would be to ask the user for proxy settings information if the initial connection fails. + + +* How to host HTML file and SWF file in different domains + +By default, HTML file and SWF file must be in the same domain. You can follow steps below to allow hosting them in different domain. + +WARNING: If you use the method below, HTML files in ANY domains can send arbitrary TCP data to your WebSocket server, regardless of configuration in Flash socket policy file. Arbitrary TCP data means that they can even fake request headers including Origin and Cookie. + +- Unzip WebSocketMainInsecure.zip to extract WebSocketMainInsecure.swf. +- Put WebSocketMainInsecure.swf on your server, instead of WebSocketMain.swf. +- In JavaScript, set WEB_SOCKET_SWF_LOCATION to URL of your WebSocketMainInsecure.swf. + + +* How to build WebSocketMain.swf + +Install Flex 4 SDK: +http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+4 + +$ cd flash-src +$ ./build.sh + + +* License + +New BSD License. diff -Nru websockify-0.3.0/tests/include/web-socket-js/swfobject.js websockify-0.5.1+dfsg1/tests/include/web-socket-js/swfobject.js --- websockify-0.3.0/tests/include/web-socket-js/swfobject.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/include/web-socket-js/swfobject.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,777 @@ +/*! 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; + } + } + }; +}(); diff -Nru websockify-0.3.0/tests/include/web-socket-js/web_socket.js websockify-0.5.1+dfsg1/tests/include/web-socket-js/web_socket.js --- websockify-0.3.0/tests/include/web-socket-js/web_socket.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/include/web-socket-js/web_socket.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,391 @@ +// 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(); + }); + } + +})(); diff -Nru websockify-0.3.0/tests/include/websock.js websockify-0.5.1+dfsg1/tests/include/websock.js --- websockify-0.3.0/tests/include/websock.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/include/websock.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,422 @@ +/* + * 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(); + +} diff -Nru websockify-0.3.0/tests/include/webutil.js websockify-0.5.1+dfsg1/tests/include/webutil.js --- websockify-0.3.0/tests/include/webutil.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/include/webutil.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,216 @@ +/* + * 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; +}; diff -Nru websockify-0.3.0/tests/include/wsirc.js websockify-0.5.1+dfsg1/tests/include/wsirc.js --- websockify-0.3.0/tests/include/wsirc.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/include/wsirc.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,235 @@ +/* + * WebSockets IRC client + * Copyright (C) 2011 Joel Martin + * Licensed under LGPL-3 (see LICENSE.txt) + * + * Includes VT100.js from: + * http://code.google.com/p/sshconsole + * Which was modified from: + * http://fzort.org/bi/o.php#vt100_js + + * IRC Client protocol: + * http://www.faqs.org/rfcs/rfc2812.html + */ + + +function IRC(target, connect_callback, disconnect_callback) { + +var that = {}, // Public API interface + vt100, ws, sQ = [], + state = "unconnected", + irc_nick, irc_channel, + termType = "VT100"; + + +Array.prototype.pushStr = function (str) { + var n = str.length; + for (var i=0; i < n; i++) { + this.push(str.charCodeAt(i)); + } +} + +function do_send() { + if (sQ.length > 0) { + Util.Debug("Sending " + sQ); + ws.send(sQ); + sQ = []; + } +} + +function do_recv() { + console.log(">> do_recv"); + var rQ, rQi, i; + + while (ws.rQlen() > 1) { + rQ = ws.get_rQ(); + rQi = ws.get_rQi(); + for (i = rQi; i < rQ.length; i++) { + if (rQ[i] === 10) { + break; + } + } + if (i >= rQ.length) { + // No line break found + break; + } + recvMsg(ws.rQshiftStr((i-rQi) + 1)); + } + //console.log("<< do_recv"); +} + +// Handle an IRC message +function recvMsg(msg) { + Util.Debug(">> recvMsg('" + msg + "')"); + + var tokens = msg.split(' '), in_params = true, + prefix, command, params = [], trailing = []; + + Util.Info(" tokens: " + tokens); + + if (tokens[0].charAt(0) === ":") { + prefix = tokens.shift(); + } + + command = tokens.shift(); + + while (tokens.length > 0) { + if (tokens[0].charAt(0) === ":") { + in_params = false; + } + if (in_params) { + params.push(tokens.shift()); + } else { + trailing.push(tokens.shift()); + } + } + + Util.Info(" prefix: " + prefix); + Util.Info(" command: " + command); + Util.Info(" params: " + params); + Util.Info(" trailing: " + trailing); + + // Show raw received + vt100.write(msg); + + switch (command) { + case "004": + state = "registered"; + vt100.write("Joining channel #" + irc_channel); + sendCmd("JOIN #" + irc_channel); + break; + case "JOIN": + state = "joined"; + vt100.write("Joined channel #" + irc_channel); + break; + + } + + Util.Debug("<< recvMsg('" + msg + "')"); +} + +function sendCmd(msg) { + Util.Info("Sending: " + msg); + sQ.pushStr(msg + "\r\n"); + do_send(); +} + +that.sendMsg = function(msg) { + // TODO parse into message + sendCmd("PRIVMSG #" + irc_channel + " :" + msg); +} + + +that.connect = function(host, port, encrypt, nick, channel) { + var host = host, + port = port, + scheme = "ws://", uri; + + irc_nick = nick; + irc_channel = channel; + + Util.Debug(">> connect"); + if ((!host) || (!port)) { + alert("must set host and port"); + return false; + } + + if (ws) { + ws.close(); + } + + if (encrypt) { + scheme = "wss://"; + } + uri = scheme + host + ":" + port; + Util.Info("connecting to " + uri); + + ws.open(uri); + + Util.Debug("<< connect"); + + return true; +} + +that.disconnect = function() { + Util.Debug(">> disconnect"); + if (ws) { + ws.close(); + } + + disconnect_callback(); + Util.Debug("<< disconnect"); +} + + +function constructor() { + /* Initialize Websock object */ + ws = new Websock(); + + ws.on('message', do_recv); + ws.on('open', function(e) { + Util.Info(">> WebSockets.onopen"); + // Send registration commands + state = "connected"; + sendCmd("NICK " + irc_nick); + // TODO: how to determine this? + sendCmd("USER joelm 0 * :Joel Martin"); + connect_callback(); + Util.Info("<< WebSockets.onopen"); + }); + ws.on('close', function(e) { + Util.Info(">> WebSockets.onclose"); + that.disconnect(); + Util.Info("<< WebSockets.onclose"); + }); + ws.on('error', function(e) { + Util.Info(">> WebSockets.onerror"); + that.disconnect(); + Util.Info("<< WebSockets.onerror"); + }); + + /* Initialize the terminal emulator/renderer */ + + vt100 = new VT100(80, 24, target); + + // Show cursor + vt100.curs_set(true, false); + + /* + * Override VT100 I/O routines + */ + + // Set handler for sending characters + vt100.getch( + function send_chr(chr, vt) { + var i; + Util.Debug(">> send_chr: " + chr); + for (i = 0; i < chr.length; i++) { + sQ.push(chr.charCodeAt(i)); + } + do_send(); + vt100.getch(send_chr); + } + ); + + vt100.debug = function(message) { + Util.Debug(message + "\n"); + } + + vt100.warn = function(message) { + Util.Warn(message + "\n"); + } + + vt100.curs_set = function(vis, grab, eventist) + { + this.debug("curs_set:: vis: " + vis + ", grab: " + grab); + if (vis !== undefined) + this.cursor_vis_ = (vis > 0); + } + + return that; +} + +return constructor(); // Return the public API interface + +} // End of Telnet() diff -Nru websockify-0.3.0/tests/include/wstelnet.js websockify-0.5.1+dfsg1/tests/include/wstelnet.js --- websockify-0.3.0/tests/include/wstelnet.js 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/include/wstelnet.js 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,335 @@ +/* + * WebSockets telnet client + * Copyright (C) 2011 Joel Martin + * Licensed under LGPL-3 (see LICENSE.txt) + * + * Includes VT100.js from: + * http://code.google.com/p/sshconsole + * Which was modified from: + * http://fzort.org/bi/o.php#vt100_js + * + * Telnet protocol: + * http://www.networksorcery.com/enp/protocol/telnet.htm + * http://www.networksorcery.com/enp/rfc/rfc1091.txt + * + * ANSI escape sequeneces: + * http://en.wikipedia.org/wiki/ANSI_escape_code + * http://ascii-table.com/ansi-escape-sequences-vt-100.php + * http://www.termsys.demon.co.uk/vtansi.htm + * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html + * + * ASCII codes: + * http://en.wikipedia.org/wiki/ASCII + * http://www.hobbyprojects.com/ascii-table/ascii-table.html + * + * Other web consoles: + * http://stackoverflow.com/questions/244750/ajax-console-window-with-ansi-vt100-support + */ + + + + +function Telnet(target, connect_callback, disconnect_callback) { + +var that = {}, // Public API interface + vt100, ws, sQ = []; + termType = "VT100"; + + +Array.prototype.pushStr = function (str) { + var n = str.length; + for (var i=0; i < n; i++) { + this.push(str.charCodeAt(i)); + } +} + +function do_send() { + if (sQ.length > 0) { + Util.Debug("Sending " + sQ); + ws.send(sQ); + sQ = []; + } +} + +function do_recv() { + //console.log(">> do_recv"); + var arr = ws.rQshiftBytes(ws.rQlen()), str = "", + chr, cmd, code, value; + + Util.Debug("Received array '" + arr + "'"); + while (arr.length > 0) { + chr = arr.shift(); + switch (chr) { + case 255: // IAC + cmd = chr; + code = arr.shift(); + value = arr.shift(); + switch (code) { + case 254: // DONT + Util.Debug("Got Cmd DONT '" + value + "', ignoring"); + break; + case 253: // DO + Util.Debug("Got Cmd DO '" + value + "'"); + if (value === 24) { + // Terminal type + Util.Info("Send WILL '" + value + "' (TERM-TYPE)"); + sQ.push(255, 251, value); + } else { + // Refuse other DO requests with a WONT + Util.Debug("Send WONT '" + value + "'"); + sQ.push(255, 252, value); + } + break; + case 252: // WONT + Util.Debug("Got Cmd WONT '" + value + "', ignoring"); + break; + case 251: // WILL + Util.Debug("Got Cmd WILL '" + value + "'"); + if (value === 1) { + // Server will echo, turn off local echo + vt100.noecho(); + // Affirm echo with DO + Util.Info("Send Cmd DO '" + value + "' (echo)"); + sQ.push(255, 253, value); + } else { + // Reject other WILL offers with a DONT + Util.Debug("Send Cmd DONT '" + value + "'"); + sQ.push(255, 254, value); + } + break; + case 250: // SB (subnegotiation) + if (value === 24) { + Util.Info("Got IAC SB TERM-TYPE SEND(1) IAC SE"); + // TERM-TYPE subnegotiation + if (arr[0] === 1 && + arr[1] === 255 && + arr[2] === 240) { + arr.shift(); arr.shift(); arr.shift(); + Util.Info("Send IAC SB TERM-TYPE IS(0) '" + + termType + "' IAC SE"); + sQ.push(255, 250, 24, 0); + sQ.pushStr(termType); + sQ.push(255, 240); + } else { + Util.Info("Invalid subnegotiation received" + arr); + } + } else { + Util.Info("Ignoring SB " + value); + } + break; + default: + Util.Info("Got Cmd " + cmd + " " + value + ", ignoring"); } + continue; + case 242: // Data Mark (Synch) + cmd = chr; + code = arr.shift(); + value = arr.shift(); + Util.Info("Ignoring Data Mark (Synch)"); + break; + default: // everything else + str += String.fromCharCode(chr); + } + } + + if (sQ) { + do_send(); + } + + if (str) { + vt100.write(str); + } + + //console.log("<< do_recv"); +} + + + +that.connect = function(host, port, encrypt) { + var host = host, + port = port, + scheme = "ws://", uri; + + Util.Debug(">> connect"); + if ((!host) || (!port)) { + console.log("must set host and port"); + return; + } + + if (ws) { + ws.close(); + } + + if (encrypt) { + scheme = "wss://"; + } + uri = scheme + host + ":" + port; + Util.Info("connecting to " + uri); + + ws.open(uri); + + Util.Debug("<< connect"); +} + +that.disconnect = function() { + Util.Debug(">> disconnect"); + if (ws) { + ws.close(); + } + vt100.curs_set(true, false); + + disconnect_callback(); + Util.Debug("<< disconnect"); +} + + +function constructor() { + /* Initialize Websock object */ + ws = new Websock(); + + ws.on('message', do_recv); + ws.on('open', function(e) { + Util.Info(">> WebSockets.onopen"); + vt100.curs_set(true, true); + connect_callback(); + Util.Info("<< WebSockets.onopen"); + }); + ws.on('close', function(e) { + Util.Info(">> WebSockets.onclose"); + that.disconnect(); + Util.Info("<< WebSockets.onclose"); + }); + ws.on('error', function(e) { + Util.Info(">> WebSockets.onerror"); + that.disconnect(); + Util.Info("<< WebSockets.onerror"); + }); + + /* Initialize the terminal emulator/renderer */ + + vt100 = new VT100(80, 24, target); + + + /* + * Override VT100 I/O routines + */ + + // Set handler for sending characters + vt100.getch( + function send_chr(chr, vt) { + var i; + Util.Debug(">> send_chr: " + chr); + for (i = 0; i < chr.length; i++) { + sQ.push(chr.charCodeAt(i)); + } + do_send(); + vt100.getch(send_chr); + } + ); + + vt100.debug = function(message) { + Util.Debug(message + "\n"); + } + + vt100.warn = function(message) { + Util.Warn(message + "\n"); + } + + vt100.curs_set = function(vis, grab, eventist) + { + this.debug("curs_set:: vis: " + vis + ", grab: " + grab); + if (vis !== undefined) + this.cursor_vis_ = (vis > 0); + if (eventist === undefined) + eventist = window; + if (grab === true || grab === false) { + if (grab === this.grab_events_) + return; + if (grab) { + this.grab_events_ = true; + VT100.the_vt_ = this; + Util.addEvent(eventist, 'keydown', vt100.key_down); + Util.addEvent(eventist, 'keyup', vt100.key_up); + } else { + Util.removeEvent(eventist, 'keydown', vt100.key_down); + Util.removeEvent(eventist, 'keyup', vt100.key_up); + this.grab_events_ = false; + VT100.the_vt_ = undefined; + } + } + } + + vt100.key_down = function(e) { + var vt = VT100.the_vt_, keysym, ch, str = ""; + + if (vt === undefined) + return true; + + keysym = getKeysym(e); + + if (keysym < 128) { + if (e.ctrlKey) { + if (keysym == 64) { + // control 0 + ch = 0; + } else if ((keysym >= 97) && (keysym <= 122)) { + // control codes 1-26 + ch = keysym - 96; + } else if ((keysym >= 91) && (keysym <= 95)) { + // control codes 27-31 + ch = keysym - 64; + } else { + Util.Info("Debug unknown control keysym: " + keysym); + } + } else { + ch = keysym; + } + str = String.fromCharCode(ch); + } else { + switch (keysym) { + case 65505: // Shift, do not send directly + break; + case 65507: // Ctrl, do not send directly + break; + case 65293: // Carriage return, line feed + str = '\n'; break; + case 65288: // Backspace + str = '\b'; break; + case 65307: // Escape + str = '\x1b'; break; + case 65361: // Left arrow + str = '\x1b[D'; break; + case 65362: // Up arrow + str = '\x1b[A'; break; + case 65363: // Right arrow + str = '\x1b[C'; break; + case 65364: // Down arrow + str = '\x1b[B'; break; + default: + Util.Info("Unrecoginized keysym " + keysym); + } + } + + if (str) { + vt.key_buf_.push(str); + setTimeout(VT100.go_getch_, 0); + } + + Util.stopEvent(e); + return false; + } + + vt100.key_up = function(e) { + var vt = VT100.the_vt_; + if (vt === undefined) + return true; + Util.stopEvent(e); + return false; + } + + + return that; +} + +return constructor(); // Return the public API interface + +} // End of Telnet() diff -Nru websockify-0.3.0/tests/latency.html websockify-0.5.1+dfsg1/tests/latency.html --- websockify-0.3.0/tests/latency.html 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/latency.html 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,290 @@ + + + + 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:
+ + + + + + + diff -Nru websockify-0.3.0/tests/latency.py websockify-0.5.1+dfsg1/tests/latency.py --- websockify-0.3.0/tests/latency.py 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/latency.py 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,75 @@ +#!/usr/bin/env python + +''' +A WebSocket server that echos back whatever it receives from the client. +Copyright 2010 Joel Martin +Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) + +You can make a cert/key with openssl using: +openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem +as taken from http://docs.python.org/dev/library/ssl.html#certificates +''' + +import os, sys, select, optparse +sys.path.insert(0,os.path.dirname(__file__) + "/../websockify") +from websocket import WebSocketServer + +class WebSocketEcho(WebSocketServer): + """ + WebSockets server that echos back whatever is received from the + client. """ + buffer_size = 8096 + + def new_client(self): + """ + Echo back whatever is received. + """ + + cqueue = [] + c_pend = 0 + cpartial = "" + rlist = [self.client] + + while True: + wlist = [] + + if cqueue or c_pend: wlist.append(self.client) + ins, outs, excepts = select.select(rlist, wlist, [], 1) + if excepts: raise Exception("Socket exception") + + if self.client in outs: + # Send queued target data to the client + c_pend = self.send_frames(cqueue) + cqueue = [] + + if self.client in ins: + # Receive client data, decode it, and send it back + frames, closed = self.recv_frames() + cqueue.extend(frames) + + if closed: + self.send_close() + raise self.EClose(closed) + +if __name__ == '__main__': + parser = optparse.OptionParser(usage="%prog [options] listen_port") + parser.add_option("--verbose", "-v", action="store_true", + help="verbose messages and per frame traffic") + parser.add_option("--cert", default="self.pem", + help="SSL certificate file") + parser.add_option("--key", default=None, + help="SSL key file (if separate from cert)") + parser.add_option("--ssl-only", action="store_true", + help="disallow non-encrypted connections") + (opts, args) = parser.parse_args() + + try: + if len(args) != 1: raise + opts.listen_port = int(args[0]) + except: + parser.error("Invalid arguments") + + opts.web = "." + server = WebSocketEcho(**opts.__dict__) + server.start_server() + diff -Nru websockify-0.3.0/tests/load.html websockify-0.5.1+dfsg1/tests/load.html --- websockify-0.3.0/tests/load.html 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/load.html 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,250 @@ + + + + WebSockets Load Test + + + + + + + + + + + + + Host:   + Port:   + Encrypt:   + Send Delay (ms):   +   + +

+ + + + + + + + + + + +
Packets sent:
0
Good Packets Received:
0
Errors (Bad Packets Received:)
0
+ +
+ Errors:
+ + + + + + + diff -Nru websockify-0.3.0/tests/load.py websockify-0.5.1+dfsg1/tests/load.py --- websockify-0.3.0/tests/load.py 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/load.py 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,167 @@ +#!/usr/bin/env python + +''' +WebSocket server-side load test program. Sends and receives traffic +that has a random payload (length and content) that is checksummed and +given a sequence number. Any errors are reported and counted. +''' + +import sys, os, select, random, time, optparse +sys.path.insert(0,os.path.dirname(__file__) + "/../websockify") +from websocket import WebSocketServer + +class WebSocketLoad(WebSocketServer): + + buffer_size = 65536 + + max_packet_size = 10000 + recv_cnt = 0 + send_cnt = 0 + + def __init__(self, *args, **kwargs): + self.errors = 0 + self.delay = kwargs.pop('delay') + + print "Prepopulating random array" + self.rand_array = [] + for i in range(0, self.max_packet_size): + self.rand_array.append(random.randint(0, 9)) + + WebSocketServer.__init__(self, *args, **kwargs) + + def new_client(self): + self.send_cnt = 0 + self.recv_cnt = 0 + + try: + self.responder(self.client) + except: + print "accumulated errors:", self.errors + self.errors = 0 + raise + + def responder(self, client): + c_pend = 0 + cqueue = [] + cpartial = "" + socks = [client] + last_send = time.time() * 1000 + + while True: + ins, outs, excepts = select.select(socks, socks, socks, 1) + if excepts: raise Exception("Socket exception") + + if client in ins: + frames, closed = self.recv_frames() + + err = self.check(frames) + if err: + self.errors = self.errors + 1 + print err + + if closed: + self.send_close() + raise self.EClose(closed) + + now = time.time() * 1000 + if client in outs: + if c_pend: + last_send = now + c_pend = self.send_frames() + elif now > (last_send + self.delay): + last_send = now + c_pend = self.send_frames([self.generate()]) + + def generate(self): + length = random.randint(10, self.max_packet_size) + numlist = self.rand_array[self.max_packet_size-length:] + # Error in length + #numlist.append(5) + chksum = sum(numlist) + # Error in checksum + #numlist[0] = 5 + nums = "".join( [str(n) for n in numlist] ) + data = "^%d:%d:%d:%s$" % (self.send_cnt, length, chksum, nums) + self.send_cnt += 1 + + return data + + + def check(self, frames): + + err = "" + for data in frames: + if data.count('$') > 1: + raise Exception("Multiple parts within single packet") + if len(data) == 0: + self.traffic("_") + continue + + if data[0] != "^": + err += "buf did not start with '^'\n" + continue + + try: + cnt, length, chksum, nums = data[1:-1].split(':') + cnt = int(cnt) + length = int(length) + chksum = int(chksum) + except: + print "\n" + 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") + + opts.web = "." + server = WebSocketLoad(**opts.__dict__) + server.start_server() + diff -Nru websockify-0.3.0/tests/plain_echo.html websockify-0.5.1+dfsg1/tests/plain_echo.html --- websockify-0.3.0/tests/plain_echo.html 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/plain_echo.html 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,168 @@ + + + + WebSockets Echo Test + + + + + + + + + + + Host:   + Port:   + Encrypt:   +   + + +
+ Log:
+ + + + + + + diff -Nru websockify-0.3.0/tests/simple.html websockify-0.5.1+dfsg1/tests/simple.html --- websockify-0.3.0/tests/simple.html 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/simple.html 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,68 @@ + + + + Websock Simple Client + + + + + + + WebSocket/websockify URI:   + +

+   +   +

+ Log:
+ + + + + + diff -Nru websockify-0.3.0/tests/utf8-list.py websockify-0.5.1+dfsg1/tests/utf8-list.py --- websockify-0.3.0/tests/utf8-list.py 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/tests/utf8-list.py 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,20 @@ +#!/usr/bin/python + +''' +Display UTF-8 encoding for 0-255.''' + +import sys, os, socket, ssl, time, traceback +from select import select + +sys.path.insert(0,os.path.dirname(__file__) + "/../websockify") +from 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)) + diff -Nru websockify-0.3.0/websockify/websocket.py websockify-0.5.1+dfsg1/websockify/websocket.py --- websockify-0.3.0/websockify/websocket.py 2012-10-31 15:38:13.000000000 +0000 +++ websockify-0.5.1+dfsg1/websockify/websocket.py 2013-09-12 14:43:43.000000000 +0000 @@ -6,9 +6,9 @@ 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-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 @@ -37,8 +37,8 @@ except: from SimpleHTTPServer import SimpleHTTPRequestHandler # python 2.6 differences -try: from hashlib import md5, sha1 -except: from md5 import md5; from sha import sha as sha1 +try: from hashlib import sha1 +except: from sha import sha as sha1 # python 2.5 differences try: @@ -50,15 +50,15 @@ return struct.unpack(fmt, slice) # Degraded functionality if these imports are missing -for mod, sup in [('numpy', 'HyBi protocol'), ('ssl', 'TLS/SSL/wss'), - ('multiprocessing', 'Multi-Processing'), - ('resource', 'daemonizing')]: +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 is slower or disabled" % ( - mod, sup)) + print("WARNING: no '%s' module, %s" % (mod, msg)) if multiprocessing and sys.platform == 'win32': # make sockets pickle-able/inheritable import multiprocessing.reduction @@ -72,14 +72,6 @@ buffer_size = 65536 - - server_handshake_hixie = """HTTP/1.1 101 Web Socket Protocol Handshake\r -Upgrade: WebSocket\r -Connection: Upgrade\r -%sWebSocket-Origin: %s\r -%sWebSocket-Location: %s://%s%s\r -""" - server_handshake_hybi = """HTTP/1.1 101 Switching Protocols\r Upgrade: websocket\r Connection: Upgrade\r @@ -100,7 +92,7 @@ def __init__(self, listen_host='', listen_port=None, source_is_ipv6=False, verbose=False, cert='', key='', ssl_only=None, - daemon=False, record='', web='', + daemon=False, record='', web='', file_only=False, no_parent=False, run_once=False, timeout=0, idle_timeout=0): # settings @@ -118,6 +110,9 @@ self.ws_connection = False self.handler_id = 1 + self.file_only = file_only + self.no_parent = no_parent + # Make paths settings absolute self.cert = os.path.abspath(cert) self.key = self.web = self.record = '' @@ -381,33 +376,6 @@ return f - @staticmethod - def encode_hixie(buf): - return s2b("\x00" + b2s(b64encode(buf)) + "\xff"), 1, 1 - - @staticmethod - def decode_hixie(buf): - end = buf.find(s2b('\xff')) - return {'payload': b64decode(buf[1:end]), - 'hlen': 1, - 'masked': False, - 'length': end - 1, - 'left': len(buf) - (end + 1)} - - - @staticmethod - def gen_md5(keys): - """ Generate hash value for WebSockets hixie-76. """ - key1 = keys['Sec-WebSocket-Key1'] - key2 = keys['Sec-WebSocket-Key2'] - key3 = keys['key3'] - spaces1 = key1.count(" ") - spaces2 = key2.count(" ") - num1 = int("".join([c for c in key1 if c.isdigit()])) / spaces1 - num2 = int("".join([c for c in key2 if c.isdigit()])) / spaces2 - - return b2s(md5(pack('>II8s', - int(num1), int(num2), key3)).digest()) # # WebSocketServer logging/output functions @@ -444,16 +412,10 @@ if bufs: for buf in bufs: - if self.version.startswith("hybi"): - if self.base64: - encbuf, lenhead, lentail = self.encode_hybi( - buf, opcode=1, base64=True) - else: - encbuf, lenhead, lentail = self.encode_hybi( - buf, opcode=2, base64=False) - + if self.base64: + encbuf, lenhead, lentail = self.encode_hybi(buf, opcode=1, base64=True) else: - encbuf, lenhead, lentail = self.encode_hixie(buf) + encbuf, lenhead, lentail = self.encode_hybi(buf, opcode=2, base64=False) if self.rec: self.rec.write("%s,\n" % @@ -498,41 +460,21 @@ self.recv_part = None while buf: - if self.version.startswith("hybi"): - - frame = self.decode_hybi(buf, base64=self.base64) - #print("Received buf: %s, frame: %s" % (repr(buf), frame)) - - if frame['payload'] == None: - # Incomplete/partial frame - self.traffic("}.") - if frame['left'] > 0: - self.recv_part = buf[-frame['left']:] - break - else: - if frame['opcode'] == 0x8: # connection close - closed = {'code': frame['close_code'], - 'reason': frame['close_reason']} - break + frame = self.decode_hybi(buf, base64=self.base64) + #print("Received buf: %s, frame: %s" % (repr(buf), frame)) + if frame['payload'] == None: + # Incomplete/partial frame + self.traffic("}.") + if frame['left'] > 0: + self.recv_part = buf[-frame['left']:] + break else: - if buf[0:2] == s2b('\xff\x00'): - closed = {'code': 1000, - 'reason': "Client sent orderly close frame"} - break - - elif buf[0:2] == s2b('\x00\xff'): - buf = buf[2:] - continue # No-op - - elif buf.count(s2b('\xff')) == 0: - # Partial frame - self.traffic("}.") - self.recv_part = buf + if frame['opcode'] == 0x8: # connection close + closed = {'code': frame['close_code'], + 'reason': frame['close_reason']} break - frame = self.decode_hixie(buf) - self.traffic("}") if self.rec: @@ -560,17 +502,9 @@ def send_close(self, code=1000, reason=''): """ Send a WebSocket orderly close frame. """ - if self.version.startswith("hybi"): - msg = pack(">H%ds" % len(reason), code, reason) - - buf, h, t = self.encode_hybi(msg, opcode=0x08, base64=False) - self.client.send(buf) - - elif self.version == "hixie-76": - buf = s2b('\xff\x00') - self.client.send(buf) - - # No orderly close for 75 + msg = pack(">H%ds" % len(reason), code, reason) + buf, h, t = self.encode_hybi(msg, opcode=0x08, base64=False) + self.client.send(buf) def do_websocket_handshake(self, headers, path): h = self.headers = headers @@ -612,28 +546,7 @@ response += "\r\n" else: - # Hixie version of the protocol (75 or 76) - - if h.get('key3'): - trailer = self.gen_md5(h) - pre = "Sec-" - self.version = "hixie-76" - else: - trailer = "" - pre = "" - self.version = "hixie-75" - - # We only support base64 in Hixie era - self.base64 = True - - response = self.server_handshake_hixie % (pre, - h['Origin'], pre, self.scheme, h['Host'], path) - - if 'base64' in protocols: - response += "%sWebSocket-Protocol: base64\r\n" % pre - else: - self.msg("Warning: client does not report 'base64' protocol support") - response += "\r\n" + trailer + raise self.EClose("Missing Sec-WebSocket-Version header. Hixie protocols not supported.") return response @@ -710,7 +623,8 @@ self.scheme = "ws" stype = "Plain non-SSL (ws://)" - wsh = WSRequestHandler(retsock, address, not self.web) + wsh = WSRequestHandler(retsock, address, not self.web, + self.file_only, self.no_parent) if wsh.last_code == 101: # Continue on to handle WebSocket upgrade pass @@ -949,19 +863,19 @@ # HTTP handler with WebSocket upgrade support class WSRequestHandler(SimpleHTTPRequestHandler): - def __init__(self, req, addr, only_upgrade=False): + def __init__(self, req, addr, only_upgrade=False, file_only=False, + no_parent=False): self.only_upgrade = only_upgrade # only allow upgrades + self.webroot = os.path.realpath(".") + self.file_only = file_only + self.no_parent = no_parent SimpleHTTPRequestHandler.__init__(self, req, addr, object()) def do_GET(self): + abspath = os.path.realpath("." + (self.path.split('?')[0])) if (self.headers.get('upgrade') and self.headers.get('upgrade').lower() == 'websocket'): - if (self.headers.get('sec-websocket-key1') or - self.headers.get('websocket-key1')): - # For Hixie-76 read out the key hash - self.headers.__setitem__('key3', self.rfile.read(8)) - # Just indicate that an WebSocket upgrade is needed self.last_code = 101 self.last_message = "101 Switching Protocols" @@ -969,6 +883,10 @@ # Normal web request responses are disabled self.last_code = 405 self.last_message = "405 Method Not Allowed" + elif self.file_only and not os.path.isfile(abspath): + self.send_response(404, "No such file") + elif self.no_parent and not abspath.startswith(self.webroot): + self.send_response(403, "Hidden resources") else: SimpleHTTPRequestHandler.do_GET(self) diff -Nru websockify-0.3.0/websockify_cherry.py websockify-0.5.1+dfsg1/websockify_cherry.py --- websockify-0.3.0/websockify_cherry.py 2012-10-12 14:11:40.000000000 +0000 +++ websockify-0.5.1+dfsg1/websockify_cherry.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -import argparse -import random -import os - -import cherrypy - -from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool -from ws4py.websocket import WebSocket -from ws4py.messaging import TextMessage - -class WebSocketProxy(WebSocket): - def opened(self): - - def received_message(self, m): - cherrypy.engine.publish('websocket-broadcast', m) - - def closed(self, code, reason="A client left the room without a proper explanation."): - cherrypy.engine.publish('websocket-broadcast', TextMessage(reason)) - -class Root(object): - def __init__(self, host, port, ssl=False): - self.host = host - self.port = port - - @cherrypy.expose - def ws(self): - cherrypy.log("Handler created: %s" % repr(cherrypy.request.ws_handler)) - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description='Echo CherryPy Server') - parser.add_argument('--host', default='127.0.0.1') - parser.add_argument('-p', '--port', default=9000, type=int) - parser.add_argument('--ssl', action='store_true') - args = parser.parse_args() - - cherrypy.config.update({'server.socket_host': args.host, - 'server.socket_port': args.port, - 'tools.staticdir.root': os.path.abspath(os.path.dirname(__file__))}) - - if args.ssl: - cherrypy.config.update({'server.ssl_certificate': './server.crt', - 'server.ssl_private_key': './server.key'}) - - WebSocketPlugin(cherrypy.engine).subscribe() - cherrypy.tools.websocket = WebSocketTool() - cherrypy.tools.protocols = ['binary']; - - cherrypy.quickstart(Root(args.host, args.port, args.ssl), '', config={ - '/ws': { - 'tools.websocket.on': True, - 'tools.websocket.handler_cls': WebSocketProxy - }, - '/': { - 'tools.staticdir.on': True, - 'tools.staticdir.dir': '.' - } - } - ) diff -Nru websockify-0.3.0/websockify.egg-info/dependency_links.txt websockify-0.5.1+dfsg1/websockify.egg-info/dependency_links.txt --- websockify-0.3.0/websockify.egg-info/dependency_links.txt 2013-01-15 17:43:51.000000000 +0000 +++ websockify-0.5.1+dfsg1/websockify.egg-info/dependency_links.txt 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ - diff -Nru websockify-0.3.0/websockify.egg-info/entry_points.txt websockify-0.5.1+dfsg1/websockify.egg-info/entry_points.txt --- websockify-0.3.0/websockify.egg-info/entry_points.txt 2013-01-15 17:43:52.000000000 +0000 +++ websockify-0.5.1+dfsg1/websockify.egg-info/entry_points.txt 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -[console_scripts] -websockify = websockify.websocketproxy:websockify_init - diff -Nru websockify-0.3.0/websockify.egg-info/not-zip-safe websockify-0.5.1+dfsg1/websockify.egg-info/not-zip-safe --- websockify-0.3.0/websockify.egg-info/not-zip-safe 2012-10-30 13:40:49.000000000 +0000 +++ websockify-0.5.1+dfsg1/websockify.egg-info/not-zip-safe 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ - diff -Nru websockify-0.3.0/websockify.egg-info/PKG-INFO websockify-0.5.1+dfsg1/websockify.egg-info/PKG-INFO --- websockify-0.3.0/websockify.egg-info/PKG-INFO 2013-01-15 17:43:51.000000000 +0000 +++ websockify-0.5.1+dfsg1/websockify.egg-info/PKG-INFO 1970-01-01 00:00:00.000000000 +0000 @@ -1,213 +0,0 @@ -Metadata-Version: 1.0 -Name: websockify -Version: 0.3.0 -Summary: Websockify. -Home-page: https://github.com/kanaka/websockify -Author: Joel Martin -Author-email: github@martintribe.org -License: LGPLv3 -Description: ## websockify: WebSockets support for any application/server - - websockify was formerly named wsproxy and was part of the - [noVNC](https://github.com/kanaka/noVNC) project. - - At the most basic level, websockify just translates WebSockets traffic - to normal socket traffic. Websockify accepts the WebSockets handshake, - parses it, and then begins forwarding traffic between the client and - the target in both directions. - - ### WebSockets binary data - - Websockify supports all versions of the WebSockets protocol (Hixie and - HyBi). The older Hixie versions of the protocol only support UTF-8 - text payloads. In order to transport binary data over UTF-8 an - encoding must used to encapsulate the data within UTF-8. - - With Hixie clients, Websockify uses base64 to encode all traffic to - and from the client. This does not affect the data between websockify - and the server. - - With HyBi clients, 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. - - `./websockify 2023 -- PROGRAM ARGS` - - The `--wrap-mode` option can be used to indicate what action to take - when the wrapped program exits or daemonizes. - - Here is an example of using websockify to wrap the vncserver command - (which backgrounds itself) for use with - [noVNC](https://github.com/kanaka/noVNC): - - `./websockify 5901 --wrap-mode=ignore -- vncserver -geometry 1024x768 :1` - - Here is an example of wrapping telnetd (from krb5-telnetd).telnetd - exits after the connection closes so the wrap mode is set to respawn - the command: - - `sudo ./websockify 2023 --wrap-mode=respawn -- telnetd -debug 2023` - - The `wstelnet.html` page demonstrates a simple WebSockets based telnet - client. - - - ### Building the Python ssl module (for python 2.5 and older) - - * Install the build dependencies. On Ubuntu use this command: - - `sudo aptitude install python-dev bluetooth-dev` - - * Download, build the ssl module and symlink to it: - - `cd websockify/` - - `wget http://pypi.python.org/packages/source/s/ssl/ssl-1.15.tar.gz` - - `tar xvzf ssl-1.15.tar.gz` - - `cd ssl-1.15` - - `make` - - `cd ../` - - `ln -sf ssl-1.15/build/lib.linux-*/ssl ssl` - - - Changes - ======= - - 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. - - - -Keywords: noVNC websockify -Platform: UNKNOWN -Classifier: Programming Language :: Python diff -Nru websockify-0.3.0/websockify.egg-info/requires.txt websockify-0.5.1+dfsg1/websockify.egg-info/requires.txt --- websockify-0.3.0/websockify.egg-info/requires.txt 2013-01-15 17:43:51.000000000 +0000 +++ websockify-0.5.1+dfsg1/websockify.egg-info/requires.txt 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -numpy \ No newline at end of file diff -Nru websockify-0.3.0/websockify.egg-info/SOURCES.txt websockify-0.5.1+dfsg1/websockify.egg-info/SOURCES.txt --- websockify-0.3.0/websockify.egg-info/SOURCES.txt 2013-01-15 17:43:55.000000000 +0000 +++ websockify-0.5.1+dfsg1/websockify.egg-info/SOURCES.txt 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -CHANGES.txt -LICENSE.txt -MANIFEST.in -README.md -cserv.py -mod_websockify.py -setup.py -websockify.py -websockify_cherry.py -websockify/__init__.py -websockify/websocket.py -websockify/websocketproxy.py -websockify.egg-info/PKG-INFO -websockify.egg-info/SOURCES.txt -websockify.egg-info/dependency_links.txt -websockify.egg-info/entry_points.txt -websockify.egg-info/not-zip-safe -websockify.egg-info/requires.txt -websockify.egg-info/top_level.txt \ No newline at end of file diff -Nru websockify-0.3.0/websockify.egg-info/top_level.txt websockify-0.5.1+dfsg1/websockify.egg-info/top_level.txt --- websockify-0.3.0/websockify.egg-info/top_level.txt 2013-01-15 17:43:51.000000000 +0000 +++ websockify-0.5.1+dfsg1/websockify.egg-info/top_level.txt 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -websockify diff -Nru websockify-0.3.0/Windows/noVNC Websocket Service Project/noVNC Websocket.csproj websockify-0.5.1+dfsg1/Windows/noVNC Websocket Service Project/noVNC Websocket.csproj --- websockify-0.3.0/Windows/noVNC Websocket Service Project/noVNC Websocket.csproj 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/Windows/noVNC Websocket Service Project/noVNC Websocket.csproj 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,75 @@ + + + + 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 + + + + + \ No newline at end of file diff -Nru websockify-0.3.0/Windows/noVNC Websocket Service Project/noVNC Websocket.sln websockify-0.5.1+dfsg1/Windows/noVNC Websocket Service Project/noVNC Websocket.sln --- websockify-0.3.0/Windows/noVNC Websocket Service Project/noVNC Websocket.sln 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/Windows/noVNC Websocket Service Project/noVNC Websocket.sln 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "noVNC Websocket", "noVNC Websocket.csproj", "{6B86AE7B-6BBD-4E74-8802-5995E8B6D27D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x86 = Debug|x86 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {6B86AE7B-6BBD-4E74-8802-5995E8B6D27D}.Debug|x86.ActiveCfg = Debug|x86 + {6B86AE7B-6BBD-4E74-8802-5995E8B6D27D}.Debug|x86.Build.0 = Debug|x86 + {6B86AE7B-6BBD-4E74-8802-5995E8B6D27D}.Release|x86.ActiveCfg = Release|x86 + {6B86AE7B-6BBD-4E74-8802-5995E8B6D27D}.Release|x86.Build.0 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff -Nru websockify-0.3.0/Windows/noVNC Websocket Service Project/Program.cs websockify-0.5.1+dfsg1/Windows/noVNC Websocket Service Project/Program.cs --- websockify-0.3.0/Windows/noVNC Websocket Service Project/Program.cs 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/Windows/noVNC Websocket Service Project/Program.cs 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.ServiceProcess; +using System.Text; + +namespace MELT_Command_Websocket +{ + static class Program + { + /// + /// The main entry point for the application. + /// + static void Main() + { + ServiceBase[] ServicesToRun; + ServicesToRun = new ServiceBase[] + { + new Service1() + }; + ServiceBase.Run(ServicesToRun); + } + } +} diff -Nru websockify-0.3.0/Windows/noVNC Websocket Service Project/ProjectInstaller.cs websockify-0.5.1+dfsg1/Windows/noVNC Websocket Service Project/ProjectInstaller.cs --- websockify-0.3.0/Windows/noVNC Websocket Service Project/ProjectInstaller.cs 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/Windows/noVNC Websocket Service Project/ProjectInstaller.cs 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,19 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration.Install; +using System.Linq; + + +namespace MELT_Command_Websocket +{ + [RunInstaller(true)] + public partial class ProjectInstaller : System.Configuration.Install.Installer + { + public ProjectInstaller() + { + InitializeComponent(); + } + } +} diff -Nru websockify-0.3.0/Windows/noVNC Websocket Service Project/ProjectInstaller.Designer.cs websockify-0.5.1+dfsg1/Windows/noVNC Websocket Service Project/ProjectInstaller.Designer.cs --- websockify-0.3.0/Windows/noVNC Websocket Service Project/ProjectInstaller.Designer.cs 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/Windows/noVNC Websocket Service Project/ProjectInstaller.Designer.cs 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,61 @@ +namespace 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; + } +} \ No newline at end of file diff -Nru websockify-0.3.0/Windows/noVNC Websocket Service Project/ProjectInstaller.resx websockify-0.5.1+dfsg1/Windows/noVNC Websocket Service Project/ProjectInstaller.resx --- websockify-0.3.0/Windows/noVNC Websocket Service Project/ProjectInstaller.resx 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/Windows/noVNC Websocket Service Project/ProjectInstaller.resx 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + \ No newline at end of file diff -Nru websockify-0.3.0/Windows/noVNC Websocket Service Project/Properties/AssemblyInfo.cs websockify-0.5.1+dfsg1/Windows/noVNC Websocket Service Project/Properties/AssemblyInfo.cs --- websockify-0.3.0/Windows/noVNC Websocket Service Project/Properties/AssemblyInfo.cs 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/Windows/noVNC Websocket Service Project/Properties/AssemblyInfo.cs 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MELT Command Websocket")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("MELT Command Websocket")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("5ab831cb-6852-4ce1-849c-b26725b0e10b")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff -Nru websockify-0.3.0/Windows/noVNC Websocket Service Project/Service1.cs websockify-0.5.1+dfsg1/Windows/noVNC Websocket Service Project/Service1.cs --- websockify-0.3.0/Windows/noVNC Websocket Service Project/Service1.cs 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/Windows/noVNC Websocket Service Project/Service1.cs 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Linq; +using System.ServiceProcess; +using System.Text; +using System.IO; + +namespace MELT_Command_Websocket +{ + public partial class Service1 : ServiceBase + { + Process websockify; + public Service1() + { + InitializeComponent(); + } + + protected override void OnStart(string[] args) + { + + string configpath = AppDomain.CurrentDomain.BaseDirectory + "\\noVNCConfig.ini"; + string sockifypath = AppDomain.CurrentDomain.BaseDirectory + "\\websockify.exe"; + //Load commandline arguements from config file. + StreamReader streamReader = new StreamReader(configpath); + string arguements = streamReader.ReadLine(); + streamReader.Close(); + + //Start websockify. + websockify = System.Diagnostics.Process.Start(sockifypath, arguements); + } + + protected override void OnStop() + { + //Service stopped. Close websockify. + websockify.Kill(); + } + } +} diff -Nru websockify-0.3.0/Windows/noVNC Websocket Service Project/Service1.Designer.cs websockify-0.5.1+dfsg1/Windows/noVNC Websocket Service Project/Service1.Designer.cs --- websockify-0.3.0/Windows/noVNC Websocket Service Project/Service1.Designer.cs 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/Windows/noVNC Websocket Service Project/Service1.Designer.cs 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,37 @@ +namespace 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 + } +} diff -Nru websockify-0.3.0/Windows/Windows Service Readme.txt websockify-0.5.1+dfsg1/Windows/Windows Service Readme.txt --- websockify-0.3.0/Windows/Windows Service Readme.txt 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/Windows/Windows Service Readme.txt 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,39 @@ +----------------------------------- +Windows noVNC Websockify Service +----------------------------------- + +The "noVNC Websocket Service.exe" file is a windows service wrapper created with Visual Studio 2010 to create a windows service to start stop the noVNC Websocket Server. All files used to create the wrapper can be found in 'noVNC Websocket Service Project' folder. + +To download the precompiled executables please grab the zip in the downloads section of websockify project: +https://github.com/kanaka/websockify + +--------------------------- +Installation +--------------------------- + +1. This service requires websockify.exe be in the same directory. Instructions on how to compile websockify python script as a windows executable can be found here: +https://github.com/kanaka/noVNC/wiki/Compiling-Websockify-to-Windows-Executable + +2.To add this service to a Windows PC you need to run the commandline as administrator and then run this line: + +sc create "noVNC Websocket Server" binPath= "PATH TO noVNC eg C:\noVNC\utils\Windows\Websocket Service.exe" DisplayName= "noVNC Websocket Server" + +3 .Once this is run you will be able to access the service via Control Panel > Admin Tools > Services. In here you can specify whether you want the service to run automatically and start at stop the service. + +--------------------------- +Configuration +--------------------------- +The file noVNCConfig.ini must be in the same directory as "noVNC Websocket Service.exe". + +This file contains a single line which is the websockify.exe statup arguements. An example is: +192.168.0.1:5901 192.168.0.1:5900 + +All websockify supported arguements will work if added here. + +--------------------------- +Deletion +--------------------------- + +You can delete the service at any time by running the commandline as admin and using this command: +sc delete "noVNC Websocket Server". + diff -Nru websockify-0.3.0/wsirc.html websockify-0.5.1+dfsg1/wsirc.html --- websockify-0.3.0/wsirc.html 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/wsirc.html 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,99 @@ + + + + IRC Client using WebSockets + + + + + + + + + + + + + + + + Host:   + Port:   + Encrypt:   + +
+ Nick:   +
+ Channel: #  + +

+ +
+ > + + + + + + + diff -Nru websockify-0.3.0/wstelnet.html websockify-0.5.1+dfsg1/wstelnet.html --- websockify-0.3.0/wstelnet.html 1970-01-01 00:00:00.000000000 +0000 +++ websockify-0.5.1+dfsg1/wstelnet.html 2013-09-12 14:43:43.000000000 +0000 @@ -0,0 +1,74 @@ + + + + Telnet client using WebSockets + + + + + + + + + + + + + + + + Host:   + Port:   + Encrypt:   +   + +

+ +

+
+        
+
+    
+
+