Remove all non-Python stuff from the tree

We're splitting the repository into multiple ones. This one will
only retain the Python stuff (and rebind, used by websocketproxy).

Only once license is needed after this, so use the standard COPYING
filename.
This commit is contained in:
Pierre Ossman 2018-09-11 16:15:35 +02:00
parent 60acf3cd3c
commit 368ec2c06e
35 changed files with 10 additions and 6553 deletions

4
.gitignore vendored
View File

@ -1,10 +1,6 @@
*.pyc
*.o
*.so
other/.lein-deps-sum
other/classes
other/lib
other/js/node_modules
.project
.pydevproject
target.cfg

View File

@ -1,14 +0,0 @@
websockify is licensed under the LGPL version 3 (see docs/LICENSE.GPL-3 and
docs/LICENSE.LGPL-3) with the following exceptions:
include/websock.js : MPL 2.0
include/des.js : Various BSD style licenses
include/web-socket-js/ : New BSD license (3-clause). Source code at
https://github.com/gimite/web-socket-js
other/kumina.c : Simplified BSD license (2 clause).
Original source at
https://github.com/kumina/wsproxy

View File

@ -63,25 +63,6 @@ intermediate(s) from the CA, etc. Point to this file with the `--cert` option
and then also to the key with `--key`. Finally, use `--ssl-only` as needed.
### 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.
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.
@ -123,12 +104,13 @@ These are not necessary for the basic operation.
options, where CLASS is usually one from token_plugins.py and ARG is
the plugin's configuration.
### Implementations of websockify
### Other 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).
several alternate implementations in other languages available in
our sister repositories [websockify-js](https://github.com/novnc/websockify-js)
(JavaScript/Node.js) and [websockify-other](https://github.com/novnc/websockify-other)
(C, Clojure, Ruby).
In addition there are several other external projects that implement
the websockify "protocol". See the alternate implementation [Feature
@ -169,12 +151,12 @@ the command:
`sudo ./run 2023 --wrap-mode=respawn -- telnetd -debug 2023`
The `wstelnet.html` page demonstrates a simple WebSockets based telnet
client (use 'localhost' and '2023' for the host and port
respectively).
The `wstelnet.html` page in the [websockify-js](https://github.com/novnc/websockify-js)
project demonstrates a simple WebSockets based telnet client (use
'localhost' and '2023' for the host and port respectively).
### Installing the Python implementation of websockify
### Installing websockify
Download one of the releases or the latest development version, extract
it and run `python setup.py install` as root in the directory where you

View File

@ -1,621 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS

View File

@ -1,373 +0,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.
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.

View File

@ -1,6 +0,0 @@
- 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

View File

@ -1,4 +0,0 @@
Manual setup:
DATA="echo \'<cross-domain-policy><allow-access-from domain=\\\"*\\\" to-ports=\\\"*\\\" /></cross-domain-policy>\'"
/usr/bin/socat -T 1 TCP-L:843,reuseaddr,fork,crlf SYSTEM:"$DATA"

View File

@ -1,4 +1,4 @@
- Update setup.py, CHANGES.txt and other/package.json and commit
- Update setup.py and CHANGES.txt and commit
- Create version tag and tarball from tag
WVER=0.1.0
git tag v${WVER}
@ -8,6 +8,3 @@
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

View File

@ -42,18 +42,6 @@ To encrypt the traffic using the WebSocket 'wss://' URI scheme you need to gener
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.

View File

@ -1,919 +0,0 @@
// VT100.js -- a text terminal emulator in JavaScript with a ncurses-like
// interface and a POSIX-like interface. (The POSIX-like calls are
// implemented on top of the ncurses-like calls, not the other way round.)
//
// Released under the GNU LGPL v2.1, by Frank Bi <bi@zompower.tk>
//
// 2007-08-12 - refresh():
// - factor out colour code to html_colours_()
// - fix handling of A_REVERSE | A_DIM
// - simplify initial <br /> output code
// - fix underlining colour
// - fix attron() not to turn off attributes
// - decouple A_STANDOUT and A_BOLD
// 2007-08-11 - getch() now calls refresh()
// 2007-08-06 - Safari compat fix -- turn '\r' into '\n' for onkeypress
// 2007-08-05 - Opera compat fixes for onkeypress
// 2007-07-30 - IE compat fixes:
// - change key handling code
// - add <br />...<br />&nbsp; so that 1st and last lines align
// 2007-07-28 - change wrapping behaviour -- writing at the right edge no
// longer causes the cursor to immediately wrap around
// - add <b>...</b> to output to make A_STANDOUT stand out more
// - add handling of backspace, tab, return keys
// - fix doc. of VT100() constructor
// - change from GPL to LGPL
// 2007-07-09 - initial release
//
// class VT100
// A_NORMAL, A_UNDERLINE, A_REVERSE, A_BLINK, A_DIM, A_BOLD, A_STANDOUT
// =class constants=
// Attribute constants.
// VT100(wd, ht, scr_id) =constructor=
// Creates a virtual terminal with width `wd', and
// height `ht'. The terminal will be displayed between
// <pre>...</pre> tags which have element ID `scr_id'.
// addch(ch [, attr])
// Writes out the character `ch'. If `attr' is given,
// it specifies the attributes for the character,
// otherwise the current attributes are used.
// addstr(stuff) Writes out the string `stuff' using the current
// attributes.
// attroff(mode) Turns off any current options given in mode.
// attron(mode) Turns on any options given in mode.
// attrset(mode) Sets the current options to mode.
// bkgdset(attr) Sets the background attributes to attr.
// clear() Clears the terminal using the background attributes,
// and homes the cursor.
// clrtobol() Clears the portion of the terminal from the cursor
// to the bottom.
// clrtoeol() Clears the portion of the current line after the
// cursor.
// curs_set(vis [, grab])
// If `vis' is 0, makes the cursor invisible; otherwise
// make it visible. If `grab' is given and true, starts
// capturing keyboard events (for `getch()'); if given
// and false, stops capturing events.
// echo() Causes key strokes to be automatically echoed on the
// terminal.
// erase() Same as `clear()'.
// getch(isr) Arranges to call `isr' when a key stroke is
// received. The received character and the terminal
// object are passed as arguments to `isr'.
// getmaxyx() Returns an associative array with the maximum row
// (`y') and column (`x') numbers for the terminal.
// getyx() Returns an associative array with the current row
// (`y') and column (`x') of the cursor.
// move(r, c) Moves the cursor to row `r', column `c'.
// noecho() Stops automatically echoing key strokes.
// refresh() Updates the display.
// scroll() Scrolls the terminal up one line.
// standend() Same as `attrset(VT100.A_NORMAL)'.
// standout() Same as `attron(VT100.A_STANDOUT)'.
// write(stuff) Writes `stuff' to the terminal and immediately
// updates the display; (some) escape sequences are
// interpreted and acted on.
// constructor
function VT100(wd, ht, scr_id)
{
var r;
var c;
var scr = document.getElementById(scr_id);
this.wd_ = wd;
this.ht_ = ht;
this.scrolled_ = 0;
this.bkgd_ = {
mode: VT100.A_NORMAL,
fg: VT100.COLOR_WHITE,
bg: VT100.COLOR_BLACK
};
this.c_attr_ = {
mode: VT100.A_NORMAL,
fg: VT100.COLOR_WHITE,
bg: VT100.COLOR_BLACK
};
this.text_ = new Array(ht);
this.attr_ = new Array(ht);
for (r = 0; r < ht; ++r) {
this.text_[r] = new Array(wd);
this.attr_[r] = new Array(wd);
}
this.scr_ = scr;
this.cursor_vis_ = true;
this.grab_events_ = false;
this.getch_isr_ = undefined;
this.key_buf_ = [];
this.echo_ = true;
this.esc_state_ = 0;
// Internal debug setting.
this.debug_ = 0;
this.clear();
this.refresh();
}
// public constants -- colours and colour pairs
VT100.COLOR_BLACK = 0;
VT100.COLOR_BLUE = 1;
VT100.COLOR_GREEN = 2;
VT100.COLOR_CYAN = 3;
VT100.COLOR_RED = 4;
VT100.COLOR_MAGENTA = 5;
VT100.COLOR_YELLOW = 6;
VT100.COLOR_WHITE = 7;
VT100.COLOR_PAIRS = 256;
VT100.COLORS = 8;
// public constants -- attributes
VT100.A_NORMAL = 0;
VT100.A_UNDERLINE = 1;
VT100.A_REVERSE = 2;
VT100.A_BLINK = 4;
VT100.A_DIM = 8;
VT100.A_BOLD = 16;
VT100.A_STANDOUT = 32;
VT100.A_PROTECT = VT100.A_INVIS = 0; // ?
// other public constants
VT100.TABSIZE = 8;
// private constants
VT100.ATTR_FLAGS_ = VT100.A_UNDERLINE | VT100.A_REVERSE | VT100.A_BLINK |
VT100.A_DIM | VT100.A_BOLD | VT100.A_STANDOUT |
VT100.A_PROTECT | VT100.A_INVIS;
VT100.COLOR_SHIFT_ = 6;
VT100.browser_ie_ = (navigator.appName.indexOf("Microsoft") != -1);
VT100.browser_opera_ = (navigator.appName.indexOf("Opera") != -1);
// class variables
VT100.the_vt_ = undefined;
// class methods
// this is actually an event handler
VT100.handle_onkeypress_ = function VT100_handle_onkeypress(event)
{
var vt = VT100.the_vt_, ch;
if (vt === undefined)
return true;
if (VT100.browser_ie_ || VT100.browser_opera_) {
ch = event.keyCode;
if (ch == 13)
ch = 10;
else if (ch > 255 || (ch < 32 && ch != 8))
return true;
ch = String.fromCharCode(ch);
} else {
ch = event.charCode;
//dump("ch: " + ch + "\n");
//dump("ctrl?: " + event.ctrlKey + "\n");
vt.debug("onkeypress:: keyCode: " + event.keyCode + ", ch: " + event.charCode);
if (ch) {
if (ch > 255)
return true;
if (event.ctrlKey && event.shiftKey) {
// Don't send the copy/paste commands.
var charStr = String.fromCharCode(ch);
if (charStr == 'C' || charStr == 'V') {
return false;
}
}
if (event.ctrlKey) {
ch = String.fromCharCode(ch - 96);
} else {
ch = String.fromCharCode(ch);
if (ch == '\r')
ch = '\n';
}
} else {
switch (event.keyCode) {
case event.DOM_VK_BACK_SPACE:
ch = '\b';
break;
case event.DOM_VK_TAB:
ch = '\t';
// Stop tab from moving to another element.
event.preventDefault();
break;
case event.DOM_VK_RETURN:
case event.DOM_VK_ENTER:
ch = '\n';
break;
case event.DOM_VK_UP:
ch = '\x1b[A';
break;
case event.DOM_VK_DOWN:
ch = '\x1b[B';
break;
case event.DOM_VK_RIGHT:
ch = '\x1b[C';
break;
case event.DOM_VK_LEFT:
ch = '\x1b[D';
break;
case event.DOM_VK_DELETE:
ch = '\x1b[3~';
break;
case event.DOM_VK_HOME:
ch = '\x1b[H';
break;
case event.DOM_VK_ESCAPE:
ch = '\x1bc';
break;
default:
return true;
}
}
}
vt.key_buf_.push(ch);
setTimeout(VT100.go_getch_, 0);
return false;
}
// this is actually an event handler
VT100.handle_onkeydown_ = function VT100_handle_onkeydown()
{
var vt = VT100.the_vt_, ch;
switch (event.keyCode) {
case 8:
ch = '\b'; break;
default:
return true;
}
vt.key_buf_.push(ch);
setTimeout(VT100.go_getch_, 0);
return false;
}
VT100.go_getch_ = function VT100_go_getch()
{
var vt = VT100.the_vt_;
if (vt === undefined)
return;
var isr = vt.getch_isr_;
vt.getch_isr_ = undefined;
if (isr === undefined)
return;
var ch = vt.key_buf_.shift();
if (ch === undefined) {
vt.getch_isr_ = isr;
return;
}
if (vt.echo_)
vt.addch(ch);
isr(ch, vt);
}
// object methods
VT100.prototype.may_scroll_ = function()
{
var ht = this.ht_, cr = this.row_;
while (cr >= ht) {
this.scroll();
--cr;
}
this.row_ = cr;
}
VT100.prototype.html_colours_ = function(attr)
{
var fg, bg, co0, co1;
fg = attr.fg;
bg = attr.bg;
switch (attr.mode & (VT100.A_REVERSE | VT100.A_DIM | VT100.A_BOLD)) {
case 0:
case VT100.A_DIM | VT100.A_BOLD:
co0 = '00'; co1 = 'c0';
break;
case VT100.A_BOLD:
co0 = '00'; co1 = 'ff';
break;
case VT100.A_DIM:
if (fg == VT100.COLOR_BLACK)
co0 = '40';
else
co0 = '00';
co1 = '40';
break;
case VT100.A_REVERSE:
case VT100.A_REVERSE | VT100.A_DIM | VT100.A_BOLD:
co0 = 'c0'; co1 = '40';
break;
case VT100.A_REVERSE | VT100.A_BOLD:
co0 = 'c0'; co1 = '00';
break;
default:
if (fg == VT100.COLOR_BLACK)
co0 = '80';
else
co0 = 'c0';
co1 = 'c0';
}
return {
f: '#' + (fg & 4 ? co1 : co0) +
(fg & 2 ? co1 : co0) +
(fg & 1 ? co1 : co0),
b: '#' + (bg & 4 ? co1 : co0) +
(bg & 2 ? co1 : co0) +
(bg & 1 ? co1 : co0)
};
}
VT100.prototype.addch = function(ch, attr)
{
var cc = this.col_;
this.debug("addch:: ch: " + ch + ", attr: " + attr);
switch (ch) {
case '\b':
if (cc != 0)
--cc;
break;
case '\n':
++this.row_;
cc = 0;
this.clrtoeol();
this.may_scroll_();
break;
case '\r':
this.may_scroll_();
cc = 0;
break;
case '\t':
this.may_scroll_();
cc += VT100.TABSIZE - cc % VT100.TABSIZE;
if (cc >= this.wd_) {
++this.row_;
cc -= this.wd_;
}
break;
default:
if (attr === undefined)
attr = this._cloneAttr(this.c_attr_);
if (cc >= this.wd_) {
++this.row_;
cc = 0;
}
this.may_scroll_();
this.text_[this.row_][cc] = ch;
this.attr_[this.row_][cc] = attr;
++cc;
}
this.col_ = cc;
}
VT100.prototype.addstr = function(stuff)
{
for (var i = 0; i < stuff.length; ++i)
this.addch(stuff.charAt(i));
}
VT100.prototype._cloneAttr = function VT100_cloneAttr(a)
{
return {
mode: a.mode,
fg: a.fg,
bg: a.bg
};
}
VT100.prototype.attroff = function(a)
{
//dump("attroff: " + a + "\n");
a &= VT100.ATTR_FLAGS_;
this.c_attr_.mode &= ~a;
}
VT100.prototype.attron = function(a)
{
//dump("attron: " + a + "\n");
a &= VT100.ATTR_FLAGS_;
this.c_attr_.mode |= a;
}
VT100.prototype.attrset = function(a)
{
//dump("attrset: " + a + "\n");
this.c_attr_.mode = a;
}
VT100.prototype.fgset = function(fg)
{
//dump("fgset: " + fg + "\n");
this.c_attr_.fg = fg;
}
VT100.prototype.bgset = function(bg)
{
//dump("bgset: " + bg + "\n");
if (bg !== 0) {
this.warn("bgset: " + bg + "\n");
}
this.c_attr_.bg = bg;
}
VT100.prototype.bkgdset = function(a)
{
this.bkgd_ = a;
}
VT100.prototype.clear = function()
{
this.debug("clear");
this.row_ = this.col_ = 0;
this.scrolled_ = 0;
for (r = 0; r < this.ht_; ++r) {
for (c = 0; c < this.wd_; ++c) {
this.text_[r][c] = ' ';
this.attr_[r][c] = this._cloneAttr(this.bkgd_);
}
}
}
VT100.prototype.clrtobot = function()
{
this.debug("clrtobot, row: " + this.row_);
var ht = this.ht_;
var wd = this.wd_;
this.clrtoeol();
for (var r = this.row_ + 1; r < ht; ++r) {
for (var c = 0; c < wd; ++c) {
this.text_[r][c] = ' ';
this.attr_[r][c] = this.bkgd_;
}
}
}
VT100.prototype.clrtoeol = function()
{
this.debug("clrtoeol, col: " + this.col_);
var r = this.row_;
if (r >= this.ht_)
return;
for (var c = this.col_; c < this.wd_; ++c) {
this.text_[r][c] = ' ';
this.attr_[r][c] = this.bkgd_;
}
}
VT100.prototype.clearpos = function(row, col)
{
this.debug("clearpos (" + row + ", " + col + ")");
if (row < 0 || row >= this.ht_)
return;
if (col < 0 || col >= this.wd_)
return;
this.text_[row][col] = ' ';
this.attr_[row][col] = this.bkgd_;
}
VT100.prototype.curs_set = function(vis, grab, eventist)
{
this.debug("curs_set:: vis: " + vis + ", grab: " + grab);
if (vis !== undefined)
this.cursor_vis_ = (vis > 0);
if (eventist === undefined)
eventist = window;
if (grab === true || grab === false) {
if (grab === this.grab_events_)
return;
if (grab) {
this.grab_events_ = true;
VT100.the_vt_ = this;
eventist.addEventListener("keypress", VT100.handle_onkeypress_, false);
if (VT100.browser_ie_)
document.onkeydown = VT100.handle_onkeydown_;
} else {
eventist.removeEventListener("keypress", VT100.handle_onkeypress_, false);
if (VT100.browser_ie_)
document.onkeydown = VT100.handle_onkeydown_;
this.grab_events_ = false;
VT100.the_vt_ = undefined;
}
}
}
VT100.prototype.echo = function()
{
this.debug("echo on");
this.echo_ = true;
}
VT100.prototype.erase = VT100.prototype.clear;
VT100.prototype.getch = function(isr)
{
this.debug("getch");
this.refresh();
this.getch_isr_ = isr;
setTimeout(VT100.go_getch_, 0);
}
VT100.prototype.getmaxyx = function()
{
return { y: this.ht_ - 1, x: this.wd_ - 1 };
}
VT100.prototype.getyx = function()
{
return { y: this.row_, x: this.col_ };
}
VT100.prototype.move = function(r, c)
{
this.debug("move: (" + r + ", " + c + ")");
if (r < 0)
r = 0;
else if (r >= this.ht_)
r = this.ht_ - 1;
if (c < 0)
c = 0;
else if (c >= this.wd_)
c = this.wd_ - 1;
this.row_ = r;
this.col_ = c;
}
VT100.prototype.noecho = function()
{
this.debug("echo off");
this.echo_ = false;
}
VT100.prototype.refresh = function()
{
this.debug("refresh");
var r, c, stuff = "", start_tag = "", end_tag = "", at = -1, n_at, ch,
pair, cr, cc, ht, wd, cv, added_end_tag;
ht = this.ht_;
wd = this.wd_;
cr = this.row_;
cc = this.col_;
cv = this.cursor_vis_;
var innerHTML = this.scr_.innerHTML;
if (cc >= wd)
cc = wd - 1;
for (r = 0; r < ht; ++r) {
if (r > 0) {
stuff += '\n';
}
for (c = 0; c < wd; ++c) {
added_end_tag = false;
n_at = this.attr_[r][c];
if (cv && r == cr && c == cc) {
// Draw the cursor here.
n_at = this._cloneAttr(n_at);
n_at.mode ^= VT100.A_REVERSE;
}
// If the attributes changed, make a new span.
if (n_at.mode != at.mode || n_at.fg != at.fg || n_at.bg != at.bg) {
if (c > 0) {
stuff += end_tag;
}
start_tag = "";
end_tag = "";
if (n_at.mode & VT100.A_BLINK) {
start_tag = "<blink>";
end_tag = "</blink>" + end_tag;
}
if (n_at.mode & VT100.A_STANDOUT)
n_at.mode |= VT100.A_BOLD;
pair = this.html_colours_(n_at);
start_tag += '<span style="color:' + pair.f +
';background-color:' + pair.b;
if (n_at.mode & VT100.A_UNDERLINE)
start_tag += ';text-decoration:underline';
start_tag += ';">';
stuff += start_tag;
end_tag = "</span>" + end_tag;
at = n_at;
added_end_tag = true;
} else if (c == 0) {
stuff += start_tag;
}
ch = this.text_[r][c];
switch (ch) {
case '&':
stuff += '&amp;'; break;
case '<':
stuff += '&lt;'; break;
case '>':
stuff += '&gt;'; break;
case ' ':
//stuff += '&nbsp;'; break;
stuff += ' '; break;
default:
stuff += ch;
}
}
if (!added_end_tag)
stuff += end_tag;
}
this.scr_.innerHTML = "<b>" + stuff + "</b>\n";
}
VT100.prototype.scroll = function()
{
this.scrolled_ += 1;
this.debug("scrolled: " + this.scrolled_);
var n_text = this.text_[0], n_attr = this.attr_[0],
ht = this.ht_, wd = this.wd_;
for (var r = 1; r < ht; ++r) {
this.text_[r - 1] = this.text_[r];
this.attr_[r - 1] = this.attr_[r];
}
this.text_[ht - 1] = n_text;
this.attr_[ht - 1] = n_attr;
for (var c = 0; c < wd; ++c) {
n_text[c] = ' ';
n_attr[c] = this.bkgd_;
}
}
VT100.prototype.standend = function()
{
//this.debug("standend");
this.attrset(0);
}
VT100.prototype.standout = function()
{
//this.debug("standout");
this.attron(VT100.A_STANDOUT);
}
VT100.prototype.write = function(stuff)
{
var ch, x, r, c, i, j, yx, myx;
for (i = 0; i < stuff.length; ++i) {
ch = stuff.charAt(i);
if (ch == '\x0D') {
this.debug("write:: ch: " + ch.charCodeAt(0) + ", '\\x0D'");
} else {
this.debug("write:: ch: " + ch.charCodeAt(0) + ", '" + (ch == '\x1b' ? "ESC" : ch) + "'");
}
//dump("ch: " + ch.charCodeAt(0) + ", '" + (ch == '\x1b' ? "ESC" : ch) + "'\n");
switch (ch) {
case '\x00':
case '\x7f':
case '\x07': /* bell, ignore it */
this.debug("write:: ignoring bell character: " + ch);
continue;
case '\a':
case '\b':
case '\t':
case '\r':
this.addch(ch);
continue;
case '\n':
case '\v':
case '\f': // what a mess
yx = this.getyx();
myx = this.getmaxyx();
if (yx.y >= myx.y) {
this.scroll();
this.move(myx.y, 0);
} else
this.move(yx.y + 1, 0);
continue;
case '\x18':
case '\x1a':
this.esc_state_ = 0;
this.debug("write:: set escape state: 0");
continue;
case '\x1b':
this.esc_state_ = 1;
this.debug("write:: set escape state: 1");
continue;
case '\x9b':
this.esc_state_ = 2;
this.debug("write:: set escape state: 2");
continue;
}
// not a recognized control character
switch (this.esc_state_) {
case 0: // not in escape sequence
this.addch(ch);
break;
case 1: // just saw ESC
switch (ch) {
case '[':
this.esc_state_ = 2;
this.debug("write:: set escape state: 2");
break;
case '=':
/* Set keypade mode (ignored) */
this.debug("write:: set keypade mode: ignored");
this.esc_state_ = 0;
break;
case '>':
/* Reset keypade mode (ignored) */
this.debug("write:: reset keypade mode: ignored");
this.esc_state_ = 0;
break;
case 'H':
/* Set tab at cursor column (ignored) */
this.debug("write:: set tab cursor column: ignored");
this.esc_state_ = 0;
break;
}
break;
case 2: // just saw CSI
switch (ch) {
case 'K':
/* Erase in Line */
this.esc_state_ = 0;
this.clrtoeol();
continue;
case 'H':
/* Move to (0,0). */
this.esc_state_ = 0;
this.move(0, 0);
continue;
case 'J':
/* Clear to the bottom. */
this.esc_state_ = 0;
this.clrtobot();
continue;
case '?':
/* Special VT100 mode handling. */
this.esc_state_ = 5;
this.debug("write:: special vt100 mode");
continue;
}
// Drop through to next case.
this.csi_parms_ = [0];
this.debug("write:: set escape state: 3");
this.esc_state_ = 3;
case 3: // saw CSI and parameters
switch (ch) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
x = this.csi_parms_.pop();
this.csi_parms_.push(x * 10 + ch * 1);
this.debug("csi_parms_: " + this.csi_parms_);
continue;
case ';':
if (this.csi_parms_.length < 17)
this.csi_parms_.push(0);
continue;
}
this.esc_state_ = 0;
switch (ch) {
case 'A':
// Cursor Up <ESC>[{COUNT}A
this.move(this.row_ - Math.max(1, this.csi_parms_[0]),
this.col_);
break;
case 'B':
// Cursor Down <ESC>[{COUNT}B
this.move(this.row_ + Math.max(1, this.csi_parms_[0]),
this.col_);
break;
case 'C':
// Cursor Forward <ESC>[{COUNT}C
this.move(this.row_,
this.col_ + Math.max(1, this.csi_parms_[0]));
break;
case 'c':
this.warn("write:: got TERM query");
break;
case 'D':
// Cursor Backward <ESC>[{COUNT}D
this.move(this.row_,
this.col_ - Math.max(1, this.csi_parms_[0]));
break;
case 'f':
case 'H':
// Cursor Home <ESC>[{ROW};{COLUMN}H
this.csi_parms_.push(0);
this.move(this.csi_parms_[0] - 1,
this.csi_parms_[1] - 1);
break;
case 'J':
switch (this.csi_parms_[0]) {
case 0:
this.clrtobot();
break;
case 2:
this.clear();
this.move(0, 0);
}
break;
case 'm':
for (j=0; j<this.csi_parms_.length; ++j) {
x = this.csi_parms_[j];
switch (x) {
case 0:
this.standend();
this.fgset(this.bkgd_.fg);
this.bgset(this.bkgd_.bg);
break;
case 1:
this.attron(VT100.A_BOLD);
break;
case 30:
this.fgset(VT100.COLOR_BLACK);
break;
case 31:
this.fgset(VT100.COLOR_RED);
break;
case 32:
this.fgset(VT100.COLOR_GREEN);
break;
case 33:
this.fgset(VT100.COLOR_YELLOW);
break;
case 34:
this.fgset(VT100.COLOR_BLUE);
break;
case 35:
this.fgset(VT100.COLOR_MAGENTA);
break;
case 36:
this.fgset(VT100.COLOR_CYAN);
break;
case 37:
this.fgset(VT100.COLOR_WHITE);
break;
case 40:
this.bgset(VT100.COLOR_BLACK);
break;
case 41:
this.bgset(VT100.COLOR_RED);
break;
case 42:
this.bgset(VT100.COLOR_GREEN);
break;
case 44:
this.bgset(VT100.COLOR_YELLOW);
break;
case 44:
this.bgset(VT100.COLOR_BLUE);
break;
case 45:
this.bgset(VT100.COLOR_MAGENTA);
break;
case 46:
this.bgset(VT100.COLOR_CYAN);
break;
case 47:
this.bgset(VT100.COLOR_WHITE);
break;
}
}
break;
case 'r':
// 1,24r - set scrolling region (ignored)
break;
case '[':
this.debug("write:: set escape state: 4");
this.esc_state_ = 4;
break;
case 'g':
// 0g: clear tab at cursor (ignored)
// 3g: clear all tabs (ignored)
break;
default:
this.warn("write:: unknown command: " + ch);
this.csi_parms_ = [];
break;
}
break;
case 4: // saw CSI [
this.esc_state_ = 0; // gobble char.
break;
case 5: // Special mode handling, saw <ESC>[?
// Expect a number - the reset type
this.csi_parms_ = [ch];
this.esc_state_ = 6;
break;
case 6: // Reset mode handling, saw <ESC>[?1
// Expect a letter - the mode target, example:
// <ESC>[?1l : cursor key mode = cursor
// <ESC>[?1h : save current screen, create new empty
// screen and position at 0,0
// <ESC>[?5l : White on blk
// XXX: Ignored for now.
//dump("Saw reset mode: <ESC>[?" + this.csi_parms_[0] + ch + "\n");
this.esc_state_ = 0;
this.debug("write:: set escape state: 0");
break;
}
}
this.refresh();
}
VT100.prototype.debug = function(message) {
if (this.debug_) {
dump(message + "\n");
}
}
VT100.prototype.warn = function(message) {
dump(message + "\n");
}

View File

@ -1,99 +0,0 @@
/*
* 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;
}

View File

@ -1,364 +0,0 @@
/*
* 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<files.length; f++) {
script = document.createElement('script');
script.type = 'text/javascript';
script.src = Util.get_include_uri() + files[f];
//console.log("loading script: " + script.src);
script.onload = script.onreadystatechange = function (e) {
while (ls.length > 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);
}

View File

@ -1,363 +0,0 @@
/*
* 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 with extra
* buffer handling.
*
* 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.
*/
/* [module]
* import Util from "./util";
*/
/*jslint browser: true, bitwise: true */
/*global Util*/
/* [module] export default */ function Websock() {
"use strict";
this._websocket = null; // WebSocket object
this._rQi = 0; // Receive queue index
this._rQlen = 0; // Next write position in the receive queue
this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB)
this._rQmax = this._rQbufferSize / 8;
// called in init: this._rQ = new Uint8Array(this._rQbufferSize);
this._rQ = null; // Receive queue
this._sQbufferSize = 1024 * 10; // 10 KiB
// called in init: this._sQ = new Uint8Array(this._sQbufferSize);
this._sQlen = 0;
this._sQ = null; // Send queue
this._eventHandlers = {
'message': function () {},
'open': function () {},
'close': function () {},
'error': function () {}
};
};
(function () {
"use strict";
// this has performance issues in some versions Chromium, and
// doesn't gain a tremendous amount of performance increase in Firefox
// at the moment. It may be valuable to turn it on in the future.
var ENABLE_COPYWITHIN = false;
var MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB
var typedArrayToString = (function () {
// This is only for PhantomJS, which doesn't like apply-ing
// with Typed Arrays
try {
var arr = new Uint8Array([1, 2, 3]);
String.fromCharCode.apply(null, arr);
return function (a) { return String.fromCharCode.apply(null, a); };
} catch (ex) {
return function (a) {
return String.fromCharCode.apply(
null, Array.prototype.slice.call(a));
};
}
})();
Websock.prototype = {
// Getters and Setters
get_sQ: function () {
return this._sQ;
},
get_rQ: function () {
return this._rQ;
},
get_rQi: function () {
return this._rQi;
},
set_rQi: function (val) {
this._rQi = val;
},
// Receive Queue
rQlen: function () {
return this._rQlen - this._rQi;
},
rQpeek8: function () {
return this._rQ[this._rQi];
},
rQshift8: function () {
return this._rQ[this._rQi++];
},
rQskip8: function () {
this._rQi++;
},
rQskipBytes: function (num) {
this._rQi += num;
},
// TODO(directxman12): test performance with these vs a DataView
rQshift16: function () {
return (this._rQ[this._rQi++] << 8) +
this._rQ[this._rQi++];
},
rQshift32: function () {
return (this._rQ[this._rQi++] << 24) +
(this._rQ[this._rQi++] << 16) +
(this._rQ[this._rQi++] << 8) +
this._rQ[this._rQi++];
},
rQshiftStr: function (len) {
if (typeof(len) === 'undefined') { len = this.rQlen(); }
var arr = new Uint8Array(this._rQ.buffer, this._rQi, len);
this._rQi += len;
return typedArrayToString(arr);
},
rQshiftBytes: function (len) {
if (typeof(len) === 'undefined') { len = this.rQlen(); }
this._rQi += len;
return new Uint8Array(this._rQ.buffer, this._rQi - len, len);
},
rQshiftTo: function (target, len) {
if (len === undefined) { len = this.rQlen(); }
// TODO: make this just use set with views when using a ArrayBuffer to store the rQ
target.set(new Uint8Array(this._rQ.buffer, this._rQi, len));
this._rQi += len;
},
rQwhole: function () {
return new Uint8Array(this._rQ.buffer, 0, this._rQlen);
},
rQslice: function (start, end) {
if (end) {
return new Uint8Array(this._rQ.buffer, this._rQi + start, end - start);
} else {
return new Uint8Array(this._rQ.buffer, this._rQi + start, this._rQlen - this._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.
rQwait: function (msg, num, goback) {
var rQlen = this._rQlen - this._rQi; // Skip rQlen() function call
if (rQlen < num) {
if (goback) {
if (this._rQi < goback) {
throw new Error("rQwait cannot backup " + goback + " bytes");
}
this._rQi -= goback;
}
return true; // true means need more data
}
return false;
},
// Send Queue
flush: function () {
if (this._websocket.bufferedAmount !== 0) {
Util.Debug("bufferedAmount: " + this._websocket.bufferedAmount);
}
if (this._sQlen > 0 && this._websocket.readyState === WebSocket.OPEN) {
this._websocket.send(this._encode_message());
this._sQlen = 0;
}
},
send: function (arr) {
this._sQ.set(arr, this._sQlen);
this._sQlen += arr.length;
this.flush();
},
send_string: function (str) {
this.send(str.split('').map(function (chr) {
return chr.charCodeAt(0);
}));
},
// Event Handlers
off: function (evt) {
this._eventHandlers[evt] = function () {};
},
on: function (evt, handler) {
this._eventHandlers[evt] = handler;
},
_allocate_buffers: function () {
this._rQ = new Uint8Array(this._rQbufferSize);
this._sQ = new Uint8Array(this._sQbufferSize);
},
init: function () {
this._allocate_buffers();
this._rQi = 0;
this._websocket = null;
},
open: function (uri, protocols) {
var ws_schema = uri.match(/^([a-z]+):\/\//)[1];
this.init();
// IE, Edge and Firefox misbehave when protocols is
// undefined, converting it to a string rather than
// treating it as if it wasn't specified
if (protocols) {
this._websocket = new WebSocket(uri, protocols);
} else {
this._websocket = new WebSocket(uri);
}
this._websocket.binaryType = 'arraybuffer';
this._websocket.onmessage = this._recv_message.bind(this);
this._websocket.onopen = (function () {
Util.Debug('>> WebSock.onopen');
if (this._websocket.protocol) {
Util.Info("Server choose sub-protocol: " + this._websocket.protocol);
}
this._eventHandlers.open();
Util.Debug("<< WebSock.onopen");
}).bind(this);
this._websocket.onclose = (function (e) {
Util.Debug(">> WebSock.onclose");
this._eventHandlers.close(e);
Util.Debug("<< WebSock.onclose");
}).bind(this);
this._websocket.onerror = (function (e) {
Util.Debug(">> WebSock.onerror: " + e);
this._eventHandlers.error(e);
Util.Debug("<< WebSock.onerror: " + e);
}).bind(this);
},
close: function () {
if (this._websocket) {
if ((this._websocket.readyState === WebSocket.OPEN) ||
(this._websocket.readyState === WebSocket.CONNECTING)) {
Util.Info("Closing WebSocket connection");
this._websocket.close();
}
this._websocket.onmessage = function (e) { return; };
}
},
// private methods
_encode_message: function () {
// Put in a binary arraybuffer
// according to the spec, you can send ArrayBufferViews with the send method
return new Uint8Array(this._sQ.buffer, 0, this._sQlen);
},
_expand_compact_rQ: function (min_fit) {
var resizeNeeded = min_fit || this._rQlen - this._rQi > this._rQbufferSize / 2;
if (resizeNeeded) {
if (!min_fit) {
// just double the size if we need to do compaction
this._rQbufferSize *= 2;
} else {
// otherwise, make sure we satisy rQlen - rQi + min_fit < rQbufferSize / 8
this._rQbufferSize = (this._rQlen - this._rQi + min_fit) * 8;
}
}
// we don't want to grow unboundedly
if (this._rQbufferSize > MAX_RQ_GROW_SIZE) {
this._rQbufferSize = MAX_RQ_GROW_SIZE;
if (this._rQbufferSize - this._rQlen - this._rQi < min_fit) {
throw new Exception("Receive Queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit");
}
}
if (resizeNeeded) {
var old_rQbuffer = this._rQ.buffer;
this._rQmax = this._rQbufferSize / 8;
this._rQ = new Uint8Array(this._rQbufferSize);
this._rQ.set(new Uint8Array(old_rQbuffer, this._rQi));
} else {
if (ENABLE_COPYWITHIN) {
this._rQ.copyWithin(0, this._rQi);
} else {
this._rQ.set(new Uint8Array(this._rQ.buffer, this._rQi));
}
}
this._rQlen = this._rQlen - this._rQi;
this._rQi = 0;
},
_decode_message: function (data) {
// push arraybuffer values onto the end
var u8 = new Uint8Array(data);
if (u8.length > this._rQbufferSize - this._rQlen) {
this._expand_compact_rQ(u8.length);
}
this._rQ.set(u8, this._rQlen);
this._rQlen += u8.length;
},
_recv_message: function (e) {
try {
this._decode_message(e.data);
if (this.rQlen() > 0) {
this._eventHandlers.message();
// Compact the receive queue
if (this._rQlen == this._rQi) {
this._rQlen = 0;
this._rQi = 0;
} else if (this._rQlen > this._rQmax) {
this._expand_compact_rQ();
}
} else {
Util.Debug("Ignoring empty message");
}
} catch (exc) {
var exception_str = "";
if (exc.name) {
exception_str += "\n name: " + exc.name + "\n";
exception_str += " message: " + exc.message + "\n";
}
if (typeof exc.description !== 'undefined') {
exception_str += " description: " + exc.description + "\n";
}
if (typeof exc.stack !== 'undefined') {
exception_str += exc.stack;
}
if (exception_str.length > 0) {
Util.Error("recv_message, caught exception: " + exception_str);
} else {
Util.Error("recv_message, caught exception: " + exc);
}
if (typeof exc.name !== 'undefined') {
this._eventHandlers.error(exc.name + ": " + exc.message);
} else {
this._eventHandlers.error(exc);
}
}
}
};
})();

View File

@ -1,216 +0,0 @@
/*
* 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;
};

View File

@ -1,235 +0,0 @@
/*
* 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()

View File

@ -1,337 +0,0 @@
/*
* 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 65289: // Tab
str = '\t'; 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()

View File

@ -1,14 +0,0 @@
TARGETS=websockify
CFLAGS += -fPIC
all: $(TARGETS)
websockify: websockify.o websocket.o
$(CC) $(LDFLAGS) $^ -lssl -lcrypto -o $@
websocket.o: websocket.c websocket.h
websockify.o: websockify.c websocket.h
clean:
rm -f websockify *.o

View File

@ -1,51 +0,0 @@
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.

View File

@ -1,7 +0,0 @@
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.

View File

@ -1,23 +0,0 @@
{
"author": "Joel Martin <github@martintribe.org> (http://github.com/kanaka)",
"name": "websockify",
"description": "websockify is a WebSocket-to-TCP proxy/bridge",
"license": "LGPL-3.0",
"version": "0.8.0",
"repository": {
"type": "git",
"url": "git://github.com/kanaka/websockify.git"
},
"files": ["../../docs/LICENSE.LGPL-3","websockify.js"],
"bin": {
"websockify": "./websockify.js"
},
"engines": {
"node": ">=0.8.9"
},
"dependencies": {
"ws": ">=0.4.27",
"optimist": "latest",
"mime-types" : "latest"
}
}

View File

@ -1,225 +0,0 @@
#!/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 and optimist
// npm install ws optimist
var argv = require('optimist').argv,
net = require('net'),
http = require('http'),
https = require('https'),
url = require('url'),
path = require('path'),
fs = require('fs'),
mime = require('mime-types'),
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, req) {
var clientAddr = client._socket.remoteAddress, log;
var start_time = new Date().getTime();
console.log(req ? req.url : client.upgradeReq.url);
log = function (msg) {
console.log(' ' + clientAddr + ': '+ msg);
};
log('WebSocket connection');
log('Version ' + client.protocolVersion + ', subprotocol: ' + client.protocol);
if (argv.record) {
var rs = fs.createWriteStream(argv.record + '/' + new Date().toISOString().replace(/:/g, "_"));
rs.write('var VNC_frame_data = [\n');
} else {
var rs = null;
}
var target = net.createConnection(target_port,target_host, function() {
log('connected to target');
});
target.on('data', function(data) {
//log("sending message: " + data);
if (rs) {
var tdelta = Math.floor(new Date().getTime()) - start_time;
var rsdata = '\'{' + tdelta + '{' + decodeBuffer(data) + '\',\n';
rs.write(rsdata);
}
try {
client.send(data);
} catch(e) {
log("Client closed, cleaning up target");
target.end();
}
});
target.on('end', function() {
log('target disconnected');
client.close();
if (rs) {
rs.end('\'EOF\'];\n');
}
});
target.on('error', function() {
log('target connection error');
target.end();
client.close();
if (rs) {
rs.end('\'EOF\'];\n');
}
});
client.on('message', function(msg) {
//log('got message: ' + msg);
if (rs) {
var rdelta = Math.floor(new Date().getTime()) - start_time;
var rsdata = ('\'}' + rdelta + '}' + decodeBuffer(msg) + '\',\n');
~ rs.write(rsdata);
}
target.write(msg);
});
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();
});
};
function decodeBuffer(buf) {
var returnString = '';
for (var i = 0; i < buf.length; i++) {
if (buf[i] >= 48 && buf[i] <= 90) {
returnString += String.fromCharCode(buf[i]);
} else if (buf[i] === 95) {
returnString += String.fromCharCode(buf[i]);
} else if (buf[i] >= 97 && buf[i] <= 122) {
returnString += String.fromCharCode(buf[i]);
} else {
var charToConvert = buf[i].toString(16);
if (charToConvert.length === 0) {
returnString += '\\x00';
} else if (charToConvert.length === 1) {
returnString += '\\x0' + charToConvert;
} else {
returnString += '\\x' + charToConvert;
}
}
}
return returnString;
}
// 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);
}
var headers = {};
var contentType = mime.contentType(path.extname(filename));
if (contentType !== false) {
headers['Content-Type'] = contentType;
}
response.writeHead(200, headers);
response.write(file, "binary");
response.end();
});
});
};
// parse source and target arguments into parts
try {
source_arg = argv._[0].toString();
target_arg = argv._[1].toString();
var idx;
idx = source_arg.indexOf(":");
if (idx >= 0) {
source_host = source_arg.slice(0, idx);
source_port = parseInt(source_arg.slice(idx+1), 10);
} else {
source_host = "";
source_port = parseInt(source_arg, 10);
}
idx = target_arg.indexOf(":");
if (idx < 0) {
throw("target must be host:port");
}
target_host = target_arg.slice(0, idx);
target_port = parseInt(target_arg.slice(idx+1), 10);
if (isNaN(source_port) || isNaN(target_port)) {
throw("illegal port");
}
} catch(e) {
console.error("websockify.js [--web web_dir] [--cert cert.pem [--key key.pem]] [--record dir] [source_addr:]source_port target_addr:target_port");
process.exit(2);
}
console.log("WebSocket settings: ");
console.log(" - proxying from " + source_host + ":" + source_port +
" to " + target_host + ":" + target_port);
if (argv.web) {
console.log(" - Web server active. Serving: " + argv.web);
}
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});
wsServer.on('connection', new_client);
});

View File

@ -1,118 +0,0 @@
#!/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}

View File

@ -1,13 +0,0 @@
(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
)

View File

@ -1,911 +0,0 @@
/*
* WebSocket lib with support for "wss://" encryption.
* Copyright 2010 Joel Martin
* Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3)
*
* You can make a cert/key with openssl using:
* openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem
* as taken from http://docs.python.org/dev/library/ssl.html#certificates
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <signal.h> // daemonizing
#include <fcntl.h> // daemonizing
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/bio.h> /* base64 encode/decode */
#include <openssl/md5.h> /* md5 hash */
#include <openssl/sha.h> /* sha1 hash */
#include "websocket.h"
/*
* Global state
*
* Warning: not thread safe
*/
int ssl_initialized = 0;
int pipe_error = 0;
settings_t settings;
void traffic(const 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;
}
void 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;
return ctx;
}
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_chain_file(ctx->ssl_ctx, certfile) <= 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;
}
void 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 ws_b64_ntop(const unsigned char const * src, size_t srclen, char * dst, size_t dstlen) {
int len = 0;
int total_len = 0;
BIO *buff, *b64f;
BUF_MEM *ptr;
b64f = BIO_new(BIO_f_base64());
buff = BIO_new(BIO_s_mem());
buff = BIO_push(b64f, buff);
BIO_set_flags(buff, BIO_FLAGS_BASE64_NO_NL);
BIO_set_close(buff, BIO_CLOSE);
do {
len = BIO_write(buff, src + total_len, srclen - total_len);
if (len > 0)
total_len += len;
} while (len && BIO_should_retry(buff));
BIO_flush(buff);
BIO_get_mem_ptr(buff, &ptr);
len = ptr->length;
memcpy(dst, ptr->data, dstlen < len ? dstlen : len);
dst[dstlen < len ? dstlen : len] = '\0';
BIO_free_all(buff);
if (dstlen < len)
return -1;
return len;
}
int ws_b64_pton(const char const * src, unsigned char * dst, size_t dstlen) {
int len = 0;
int total_len = 0;
int pending = 0;
BIO *buff, *b64f;
b64f = BIO_new(BIO_f_base64());
buff = BIO_new_mem_buf(src, -1);
buff = BIO_push(b64f, buff);
BIO_set_flags(buff, BIO_FLAGS_BASE64_NO_NL);
BIO_set_close(buff, BIO_CLOSE);
do {
len = BIO_read(buff, dst + total_len, dstlen - total_len);
if (len > 0)
total_len += len;
} while (len && BIO_should_retry(buff));
dst[total_len] = '\0';
pending = BIO_ctrl_pending(buff);
BIO_free_all(buff);
if (pending)
return -1;
return len;
}
/* ------------------------------------------------------- */
int encode_hixie(u_char const *src, size_t srclength,
char *target, size_t targsize) {
int sz = 0, len = 0;
target[sz++] = '\x00';
len = ws_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 = ws_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 payload_offset = 2;
int len = 0;
if (opcode != OPCODE_TEXT && opcode != OPCODE_BINARY) {
handler_emsg("Invalid opcode. Opcode must be 0x01 for text mode, or 0x02 for binary mode.\n");
return -1;
}
target[0] = (char)((opcode & 0x0F) | 0x80);
if ((int)srclength <= 0) {
return 0;
}
if (opcode & OPCODE_TEXT) {
len = ((srclength - 1) / 3) * 4 + 4;
} else {
len = srclength;
}
if (len <= 125) {
target[1] = (char) len;
payload_offset = 2;
} else if ((len > 125) && (len < 65536)) {
target[1] = (char) 126;
*(u_short*)&(target[2]) = htons(len);
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;
}
if (opcode & OPCODE_TEXT) {
len = ws_b64_ntop(src, srclength, target+payload_offset, targsize-payload_offset);
} else {
memcpy(target+payload_offset, src, srclength);
len = srclength;
}
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;
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 != OPCODE_TEXT && *opcode != OPCODE_BINARY) {
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];
}
if (*opcode & OPCODE_TEXT) {
// base64 decode the data
len = ws_b64_pton((const char*)payload, target+target_offset, targsize);
} else {
memcpy(target+target_offset, payload, payload_length);
len = payload_length;
}
// 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 = ws_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;
char *response_protocol;
// 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, "\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++) {
/* (offset + 1): reserve one byte for the trailing '\0' */
if (0 > (len = ws_recv(ws_ctx, handshake + offset, sizeof(handshake) - (offset + 1)))) {
handler_emsg("Read error during handshake: %m\n");
free_ws_ctx(ws_ctx);
return NULL;
} else if (0 == len) {
handler_emsg("Client closed during handshake\n");
free_ws_ctx(ws_ctx);
return NULL;
}
offset += len;
handshake[offset] = 0;
if (strstr(handshake, "\r\n\r\n")) {
break;
} else if (sizeof(handshake) <= (size_t)(offset + 1)) {
handler_emsg("Oversized handshake\n");
free_ws_ctx(ws_ctx);
return NULL;
} else if (9 == i) {
handler_emsg("Incomplete handshake\n");
free_ws_ctx(ws_ctx);
return NULL;
}
usleep(10);
}
//handler_msg("handshake: %s\n", handshake);
if (!parse_handshake(ws_ctx, handshake)) {
handler_emsg("Invalid WS request\n");
free_ws_ctx(ws_ctx);
return NULL;
}
headers = ws_ctx->headers;
response_protocol = strtok(headers->protocols, ",");
if (!response_protocol || !strlen(response_protocol)) {
ws_ctx->opcode = OPCODE_BINARY;
response_protocol = "null";
} else if (!strcmp(response_protocol, "base64")) {
ws_ctx->opcode = OPCODE_TEXT;
} else {
ws_ctx->opcode = OPCODE_BINARY;
}
if (ws_ctx->hybi > 0) {
handler_msg("using protocol HyBi/IETF 6455 %d\n", ws_ctx->hybi);
gen_sha1(headers, sha1);
snprintf(response, sizeof(response), SERVER_HANDSHAKE_HYBI, sha1, response_protocol);
} 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 = "";
}
snprintf(response, sizeof(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(int 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, sopt = 1, i;
struct sockaddr_in serv_addr, cli_addr;
socklen_t clilen;
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;
close(csock);
}
}
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");
}
}

View File

@ -1,104 +0,0 @@
#include <openssl/ssl.h>
#define BUFSIZE 65536
#define DBUFSIZE (BUFSIZE * 3) / 4 - 20
#define SERVER_HANDSHAKE_HIXIE "HTTP/1.1 101 Web Socket Protocol Handshake\r\n\
Upgrade: WebSocket\r\n\
Connection: Upgrade\r\n\
%sWebSocket-Origin: %s\r\n\
%sWebSocket-Location: %s://%s%s\r\n\
%sWebSocket-Protocol: %s\r\n\
\r\n%s"
#define SERVER_HANDSHAKE_HYBI "HTTP/1.1 101 Switching Protocols\r\n\
Upgrade: websocket\r\n\
Connection: Upgrade\r\n\
Sec-WebSocket-Accept: %s\r\n\
Sec-WebSocket-Protocol: %s\r\n\
\r\n"
#define HYBI_GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
#define HYBI10_ACCEPTHDRLEN 29
#define HIXIE_MD5_DIGEST_LENGTH 16
#define POLICY_RESPONSE "<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\" /></cross-domain-policy>\n"
#define OPCODE_TEXT 0x01
#define OPCODE_BINARY 0x02
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;
int opcode;
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;
int resolve_host(struct in_addr *sin_addr, const char *hostname);
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__);
void traffic(const char * token);
int encode_hixie(u_char const *src, size_t srclength,
char *target, size_t targsize);
int decode_hixie(char *src, size_t srclength,
u_char *target, size_t targsize,
unsigned int *opcode, unsigned int *left);
int encode_hybi(u_char const *src, size_t srclength,
char *target, size_t targsize, unsigned int opcode);
int decode_hybi(unsigned char *src, size_t srclength,
u_char *target, size_t targsize,
unsigned int *opcode, unsigned int *left);
void start_server();

View File

@ -1,434 +0,0 @@
# Python WebSocket library with support for "wss://" encryption.
# Copyright 2011 Joel Martin
# Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3)
#
# Supports following protocol versions:
# - http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75
# - http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76
# - http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10
require 'gserver'
require 'openssl'
require 'stringio'
require 'digest/md5'
require 'digest/sha1'
unless OpenSSL::SSL::SSLSocket.instance_methods.index("read_nonblock")
module OpenSSL
module SSL
class SSLSocket
alias :read_nonblock :readpartial
end
end
end
end
class EClose < Exception
end
class WebSocketServer < GServer
@@Buffer_size = 65536
#
# WebSocket constants
#
@@Server_handshake_hixie = "HTTP/1.1 101 Web Socket Protocol Handshake\r
Upgrade: WebSocket\r
Connection: Upgrade\r
%sWebSocket-Origin: %s\r
%sWebSocket-Location: %s://%s%s\r
"
@@Server_handshake_hybi = "HTTP/1.1 101 Switching Protocols\r
Upgrade: websocket\r
Connection: Upgrade\r
Sec-WebSocket-Accept: %s\r
"
@@GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
def initialize(opts)
vmsg "in WebSocketServer.initialize"
port = opts['listen_port']
host = opts['listen_host'] || GServer::DEFAULT_HOST
super(port, host)
msg opts.inspect
if opts['server_cert']
msg "creating ssl context"
@sslContext = OpenSSL::SSL::SSLContext.new
@sslContext.cert = OpenSSL::X509::Certificate.new(File.open(opts['server_cert']))
@sslContext.key = OpenSSL::PKey::RSA.new(File.open(opts['server_key']))
@sslContext.ca_file = opts['server_cert']
@sslContext.verify_mode = OpenSSL::SSL::VERIFY_NONE
@sslContext.verify_depth = 0
end
@@client_id = 0 # Track client number total on class
@verbose = opts['verbose']
@opts = opts
end
def serve(io)
@@client_id += 1
msg self.inspect
if @sslContext
msg "Enabling SSL context"
ssl = OpenSSL::SSL::SSLSocket.new(io, @sslContext)
#ssl.sync_close = true
#ssl.sync = true
msg "SSL accepting"
ssl.accept
io = ssl # replace the unencrypted handle with the encrypted one
end
msg "initializing thread"
# Initialize per thread state
t = Thread.current
t[:my_client_id] = @@client_id
t[:send_parts] = []
t[:recv_part] = nil
puts "in serve, client: #{t[:my_client_id].inspect}"
begin
t[:client] = do_handshake(io)
new_websocket_client(t[:client])
rescue EClose => e
msg "Client closed: #{e.message}"
return
rescue Exception => e
msg "Uncaught exception: #{e.message}"
msg "Trace: #{e.backtrace}"
return
end
msg "Client disconnected"
end
#
# WebSocketServer logging/output functions
#
def traffic(token)
if @verbose then print token; STDOUT.flush; end
end
def msg(m)
printf("% 3d: %s\n", Thread.current[:my_client_id] || 0, m)
end
def vmsg(m)
if @verbose then msg(m) end
end
#
# WebSocketServer general support routines
#
def gen_md5(h)
key1 = h['sec-websocket-key1']
key2 = h['sec-websocket-key2']
key3 = h['key3']
spaces1 = key1.count(" ")
spaces2 = key2.count(" ")
num1 = key1.scan(/[0-9]/).join('').to_i / spaces1
num2 = key2.scan(/[0-9]/).join('').to_i / spaces2
return Digest::MD5.digest([num1, num2, key3].pack('NNa8'))
end
def unmask(buf, hlen, length)
pstart = hlen + 4
mask = buf[hlen...hlen+4].each_byte.map{|b|b}
data = buf[pstart...pstart+length]
#data = data.bytes.zip(mask.bytes.cycle(length)).map { |d,m| d^m }
i=-1
data = data.each_byte.map{|b| i+=1; (b ^ mask[i % 4]).chr}.join("")
return data
end
def encode_hybi(buf, opcode)
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)
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
# 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")
encbuf, lenhead, lentail = encode_hybi(
buf, opcode=2)
else
encbuf, lenhead, lentail = encode_hixie(buf)
end
t[:send_parts] << encbuf
end
end
while t[:send_parts].length > 0
buf = t[:send_parts].shift
sent = t[:client].write(buf)
if sent == buf.length
traffic "<"
else
traffic "<."
t[:send_parts].unshift(buf[sent...buf.length])
end
end
return t[:send_parts].length
end
# Receive and decode Websocket frames
# Returns: [bufs_list, closed_string]
def recv_frames()
t = Thread.current
closed = false
bufs = []
buf = t[:client].read_nonblock(@@Buffer_size)
if buf.length == 0
return bufs, "Client closed abrubtly"
end
if t[:recv_part]
buf = t[:recv_part] + buf
t[:recv_part] = nil
end
while buf.length > 0
if t[:version].start_with?("hybi")
frame = decode_hybi(buf)
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)
t[:client].write(buf)
elsif t[:version] == "hixie-76"
buf = "\xff\x00"
t[:client].write(buf)
end
end
def do_handshake(sock)
t = Thread.current
stype = ""
if !IO.select([sock], nil, nil, 3)
raise EClose, "ignoring socket not ready"
end
handshake = ""
msg "About to read from sock [#{sock.inspect}]"
handshake = sock.read_nonblock(1024)
msg "Handshake [#{handshake.inspect}]"
if handshake == nil or handshake == ""
raise(EClose, "ignoring empty handshake")
else
stype = "Plain non-SSL (ws://)"
scheme = "ws"
if sock.class == OpenSSL::SSL::SSLSocket
stype = "SSL (wss://)"
scheme = "wss"
end
retsock = sock
end
h = t[:headers] = {}
hlines = handshake.split("\r\n")
req_split = hlines.shift.match(/^(\w+) (\/[^\s]*) HTTP\/1\.1$/)
t[:path] = req_split[2].strip
hlines.each do |hline|
break if hline == ""
hsplit = hline.match(/^([^:]+):\s*(.+)$/)
h[hsplit[1].strip.downcase] = hsplit[2]
end
puts "Headers: #{h.inspect}"
unless h.has_key?('upgrade') &&
h['upgrade'].downcase == 'websocket'
raise EClose, "Non-WebSocket connection"
end
protocols = h.fetch("sec-websocket-protocol", h["websocket-protocol"])
ver = h.fetch('sec-websocket-version', nil)
# 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
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]
response += "\r\n"
msg "%s WebSocket connection" % [stype]
msg "Version %s" % [t[:version]]
if t[:path] then msg "Path: '%s'" % [t[:path]] end
#puts "sending reponse #{response.inspect}"
retsock.write(response)
# Return the WebSocket socket which may be SSL wrapped
return retsock
end
end
# vim: sw=2

View File

@ -1,388 +0,0 @@
/*
* A WebSocket to TCP socket proxy with support for "wss://" encryption.
* Copyright 2010 Joel Martin
* Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3)
*
* You can make a cert/key with openssl using:
* openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem
* as taken from http://docs.python.org/dev/library/ssl.html#certificates
*/
#include <stdio.h>
#include <errno.h>
#include <limits.h>
#include <getopt.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/select.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include "websocket.h"
char traffic_legend[] = "\n\
Traffic Legend:\n\
} - Client receive\n\
}. - Client receive partial\n\
{ - Target receive\n\
\n\
> - Target send\n\
>. - Target send partial\n\
< - Client send\n\
<. - Client send partial\n\
";
char USAGE[] = "Usage: [options] " \
"[source_addr:]source_port target_addr:target_port\n\n" \
" --verbose|-v verbose messages and per frame traffic\n" \
" --daemon|-D become a daemon (background process)\n" \
" --run-once handle a single WebSocket connection and exit\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 int 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, ws_ctx->opcode);
} 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_msg("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();
}

View File

@ -1,233 +0,0 @@
(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)

View File

@ -1,171 +0,0 @@
#!/usr/bin/env ruby
# A WebSocket to TCP socket proxy
# Copyright 2011 Joel Martin
# Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3)
require 'socket'
$: << "other"
$: << "../other"
require 'websocket'
require 'optparse'
# Proxy traffic to and from a WebSockets client to a normal TCP
# socket server target. All traffic to/from the client is base64
# encoded/decoded to allow binary data to be sent/received to/from
# the target.
class WebSocketProxy < WebSocketServer
@@Traffic_legend = "
Traffic Legend:
} - Client receive
}. - Client receive partial
{ - Target receive
> - Target send
>. - Target send partial
< - Client send
<. - Client send partial
"
def initialize(opts)
vmsg "in WebSocketProxy.initialize"
super(opts)
@target_host = opts["target_host"]
@target_port = opts["target_port"]
end
# Echo back whatever is received
def new_websocket_client(client)
msg "connecting to: %s:%s" % [@target_host, @target_port]
tsock = TCPSocket.open(@target_host, @target_port)
if @verbose then puts @@Traffic_legend end
begin
do_proxy(client, tsock)
rescue
tsock.shutdown(Socket::SHUT_RDWR)
tsock.close
raise
end
end
# Proxy client WebSocket to normal target socket.
def do_proxy(client, target)
cqueue = []
c_pend = 0
tqueue = []
rlist = [client, target]
loop do
wlist = []
if tqueue.length > 0
wlist << target
end
if cqueue.length > 0 || c_pend > 0
wlist << client
end
ins, outs, excepts = IO.select(rlist, wlist, nil, 0.001)
if excepts && excepts.length > 0
raise Exception, "Socket exception"
end
# Send queued client data to the target
if outs && outs.include?(target)
dat = tqueue.shift
sent = target.send(dat, 0)
if sent == dat.length
traffic ">"
else
tqueue.unshift(dat[sent...dat.length])
traffic ".>"
end
end
# Receive target data and queue for the client
if ins && ins.include?(target)
buf = target.recv(@@Buffer_size)
if buf.length == 0
raise EClose, "Target closed"
end
cqueue << buf
traffic "{"
end
# Encode and send queued data to the client
if outs && outs.include?(client)
c_pend = send_frames(cqueue)
cqueue = []
end
# Receive client data, decode it, and send it back
if ins && ins.include?(client)
frames, closed = recv_frames
tqueue += frames
if closed
send_close
raise EClose, closed
end
end
end # loop
end
end
# Parse parameters
opts = {}
parser = OptionParser.new do |o|
o.on('--verbose', '-v') { |b| opts['verbose'] = b }
o.parse!
end
if ARGV.length < 2
puts "Too few arguments"
exit 2
end
# Parse host:port and convert ports to numbers
if ARGV[0].count(":") > 0
opts['listen_host'], _, opts['listen_port'] = ARGV[0].rpartition(':')
else
opts['listen_host'], opts['listen_port'] = nil, ARGV[0]
end
begin
opts['listen_port'] = opts['listen_port'].to_i
rescue
puts "Error parsing listen port"
exit 2
end
if ARGV[1].count(":") > 0
opts['target_host'], _, opts['target_port'] = ARGV[1].rpartition(':')
else
puts "Error parsing target"
exit 2
end
begin
opts['target_port'] = opts['target_port'].to_i
rescue
puts "Error parsing target port"
exit 2
end
puts "Starting server on #{opts['listen_host']}:#{opts['listen_port']}"
server = WebSocketProxy.new(opts)
server.start(100)
server.join
puts "Server has been terminated"
# vim: sw=2

View File

@ -1,22 +0,0 @@
#!/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 "${@}"

View File

@ -1,69 +0,0 @@
#!/usr/bin/env ruby
# A WebSocket server that echos back whatever it receives from the client.
# Copyright 2011 Joel Martin
# Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3)
require 'socket'
$: << "other"
$: << "../other"
require 'websocket'
class WebSocketEcho < WebSocketServer
# Echo back whatever is received
def new_websocket_client(client)
cqueue = []
c_pend = 0
rlist = [client]
loop do
wlist = []
if cqueue.length > 0 or c_pend
wlist << client
end
ins, outs, excepts = IO.select(rlist, wlist, nil, 1)
if excepts.length > 0
raise Exception, "Socket exception"
end
if outs.include?(client)
# Send queued data to the client
c_pend = send_frames(cqueue)
cqueue = []
end
if ins.include?(client)
# Receive client data, decode it, and send it back
frames, closed = recv_frames
cqueue += frames
if closed
raise EClose, closed
end
end
end # loop
end
end
port = ARGV[0].to_i || 8080
puts "Starting server on port #{port}"
server_cert = nil
server_key = nil
if ARGV.length > 2
server_cert = ARGV[1]
server_key = ARGV[2]
end
server = WebSocketEcho.new('listen_port' => port, 'verbose' => true,
'server_cert' => server_cert, 'server_key' => server_key)
server.start
server.join
puts "Server has been terminated"
# vim: sw=2

View File

@ -1 +0,0 @@
../include

View File

@ -1,98 +0,0 @@
<html>
<head>
<title>IRC Client using WebSockets</title>
<script src="include/websock.js"></script>
<script src="include/util.js"></script>
<script src="include/webutil.js"></script>
<script src="include/keysym.js"></script>
<script src="include/VT100.js"></script>
<script src="include/wsirc.js"></script>
<!-- Uncomment to activate firebug lite -->
<!--
<script type='text/javascript'
src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>
-->
</head>
<body>
Host: <input id='host' style='width:100'>&nbsp;
Port: <input id='port' style='width:50'>&nbsp;
Encrypt: <input id='encrypt' type='checkbox'>&nbsp;
<input id='connectButton' type='button' value='Connect' style='width:100px'>
<br>
Nick: <input id='nick' style='width:120'>&nbsp;
<br>
Channel: #<input id='channel' style='width:70'>&nbsp;
<br><br>
<div><pre id="irc"></pre></div>
&gt;
<input id="msg" type="text" size=80 onkeypress="sendMsg();">
<script>
var irc;
function sendMsg() {
if (event.keyCode === 13) {
var msg = $D('msg').value;
$D('msg').value = "";
Util.Debug("calling sendMsg('" + msg + "')");
irc.sendMsg(msg);
}
}
function connect() {
var ret;
ret = irc.connect($D('host').value,
$D('port').value,
$D('encrypt').checked,
$D('nick').value,
$D('channel').value);
if (! ret) { return false; }
$D('connectButton').disabled = true;
$D('connectButton').value = "Connecting";
}
function disconnect() {
$D('connectButton').disabled = true;
$D('connectButton').value = "Disconnecting";
irc.disconnect();
}
function connected() {
$D('msg').disabled = false;
$D('connectButton').disabled = false;
$D('connectButton').value = "Disconnect";
$D('connectButton').onclick = disconnect;
}
function disconnected() {
$D('msg').disabled = true;
$D('connectButton').disabled = false;
$D('connectButton').value = "Connect";
$D('connectButton').onclick = connect;
}
window.onload = function() {
console.log("onload");
var url = document.location.href;
$D('host').value = (url.match(/host=([^&#]*)/) || ['',''])[1];
$D('port').value = (url.match(/port=([^&#]*)/) || ['',''])[1];
$D('nick').value = (url.match(/nick=([^&#]*)/) || ['',''])[1];
$D('channel').value = (url.match(/channel=([^&#]*)/) || ['',''])[1];
disconnected();
irc = IRC('irc', connected, disconnected);
}
</script>
</body>
</html>

View File

@ -1,73 +0,0 @@
<html>
<head>
<title>Telnet client using WebSockets</title>
<script src="include/util.js"></script>
<script src="include/websock.js"></script>
<script src="include/webutil.js"></script>
<script src="include/keysym.js"></script>
<script src="include/VT100.js"></script>
<script src="include/wstelnet.js"></script>
<!-- Uncomment to activate firebug lite -->
<!--
<script type='text/javascript'
src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>
-->
</head>
<body>
Host: <input id='host' style='width:100'>&nbsp;
Port: <input id='port' style='width:50'>&nbsp;
Encrypt: <input id='encrypt' type='checkbox'>&nbsp;
<input id='connectButton' type='button' value='Connect' style='width:100px'
onclick="connect();">&nbsp;
<br><br>
<pre id="terminal"></pre>
<script>
var telnet;
function connect() {
telnet.connect($D('host').value,
$D('port').value,
$D('encrypt').checked);
$D('connectButton').disabled = true;
$D('connectButton').value = "Connecting";
}
function disconnect() {
$D('connectButton').disabled = true;
$D('connectButton').value = "Disconnecting";
telnet.disconnect();
}
function connected() {
$D('connectButton').disabled = false;
$D('connectButton').value = "Disconnect";
$D('connectButton').onclick = disconnect;
}
function disconnected() {
$D('connectButton').disabled = false;
$D('connectButton').value = "Connect";
$D('connectButton').onclick = connect;
}
window.onload = function() {
console.log("onload");
var url = document.location.href;
$D('host').value = (url.match(/host=([^&#]*)/) || ['',''])[1];
$D('port').value = (url.match(/port=([^&#]*)/) || ['',''])[1];
telnet = Telnet('terminal', connected, disconnected);
}
</script>
</body>
</html>