sandboxos => tildefriends

git-svn-id: https://www.unprompted.com/svn/projects/tildefriends/trunk@3157 ed5197a5-7fde-0310-b194-c3ffbd925b24
This commit is contained in:
Cory McWilliams 2016-03-12 18:50:43 +00:00
commit 7c6a377c0b
94 changed files with 27121 additions and 0 deletions

46
COPYING Normal file
View File

@ -0,0 +1,46 @@
sandboxos - An operating system for the web.
Copyright (C) 2014 Cory McWilliams <cory@unprompted.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or combining it
with V8 (or a modified version of that library), containing parts covered by
the terms of the New BSD License, the licensors of this Program grant you
additional permission to convey the resulting work. {Corresponding Source for
a non-source form of such a combination shall include the source code for the
parts of V8 used as well as that of the covered work.}
If you modify this Program, or any covered work, by linking or combining it
with libuv (or a modified version of that library), containing parts covered by
the terms of the MIT License, the licensors of this Program grant you
additional permission to convey the resulting work. {Corresponding Source for
a non-source form of such a combination shall include the source code for the
parts of libuv used as well as that of the covered work.}
If you modify this Program, or any covered work, by linking or combining it
with liblmdb (or a modified version of that library), containing parts covered
by the terms of the OpenLDAP Public License, the licensors of this Program
grant you additional permission to convey the resulting work. {Corresponding
Source for a non-source form of such a combination shall include the source
code for the parts of liblmdb used as well as that of the covered work.}
If you modify this Program, or any covered work, by linking or combining it
with javascript-bcrypt (or a modified version of that library), containing
parts covered by the terms of the New BSD License, the licensors of this
Program grant you additional permission to convey the resulting work.
{Corresponding Source for a non-source form of such a combination shall include
the source code for the parts of javascript-bcrypt used as well as that of the
covered work.}

661
LICENSE Normal file
View File

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.

32
README.md Normal file
View File

@ -0,0 +1,32 @@
# SandboxOS
SandboxOS is a program that aims to securely host pure JavaScript web applications.
## Goals
1. Make it easy to run all sorts of servers and web applications.
2. Provide a security model that is easy to understand and protects your data.
3. Make creating and sharing web applications accessible to anyone from a web interface.
## Building
SandboxOS is [routinely](https://www.unprompted.com/projects/build/sandboxos) built on Linux, Windows, and OS X.
1. Get and build [Google V8](https://code.google.com/p/v8-wiki/wiki/UsingGit) (latest 3.30).
2. Get and build [libuv](https://github.com/libuv/libuv) (latest 1.0).
3. Run:
```
scons uv=path/to/libuv v8=path/to/v8
```
## Running
Running the built sandbox executable will start a web server. This is a good starting point: <http://localhost:12345/tasks>.
To grant users administrator privileges, create a JSON file named data/auth/permissions.js containing a list of users and their permissions, like this:
```
{
"cory": ["administrator"]
}
```
This is a work in progress. Everything else can be managed entirely from the web interface.
## License
All code unless otherwise noted in [COPYING](https://github.com/unprompted/sandboxos/blob/master/COPYING) is provided under the [Affero GPL 3.0](https://github.com/unprompted/sandboxos/blob/master/LICENSE) license.

102
SConstruct Normal file
View File

@ -0,0 +1,102 @@
#!/usr/bin/python
import os
import sys
options = Variables('options.cache', ARGUMENTS)
options.AddVariables(PathVariable('uv', 'Location of libuv', '../sys/libuv'))
options.AddVariables(PathVariable('v8', 'Location of v8', '../sys/v8'))
options.AddVariables(BoolVariable('package', 'Build a package', False))
VariantDir('build/src', 'src', duplicate=0)
VariantDir('build/deps', 'deps', duplicate=0)
kwargs = {}
if sys.platform == 'darwin':
kwargs['CXX'] = 'clang++'
env = Environment(options=options, tools=['default', 'packaging'], **kwargs)
options.Save('options.cache', env)
Help(options.GenerateHelpText(env))
v8 = env['v8']
uv = env['uv']
env.Append(CPPPATH=[
os.path.join(v8, 'include'),
v8,
os.path.join(uv, 'include'),
os.path.join('deps', 'liblmdb'),
])
if sys.platform == 'win32':
env.Append(LIBS=['v8_base_0', 'v8_base_1', 'v8_base_2', 'v8_base_3', 'v8_libbase', 'v8_libplatform', 'v8_nosnapshot', 'icui18n', 'icuuc', 'libuv', 'advapi32', 'winmm', 'wsock32', 'ws2_32', 'psapi', 'iphlpapi'])
env.Append(CXXFLAGS=['/EHsc', '/MT', '/Zi', '/Gy'])
env.Append(CFLAGS=['/EHsc', '/MT', '/Zi', '/Gy'])
env.Append(LIBPATH=[
os.path.join(v8, 'build/Release/lib'),
os.path.join(uv, 'Release/lib'),
])
env.Append(LINKFLAGS=['/RELEASE', '/OPT:REF', '/OPT:ICF'])
elif sys.platform == 'darwin':
env.Append(LIBS=['v8_base', 'v8_libbase', 'v8_libplatform', 'v8_nosnapshot', 'icui18n', 'icuuc', 'icudata', 'pthread', 'uv'])
env.Append(CXXFLAGS=['--std=c++11', '-g', '-Wall', '-stdlib=libstdc++'])
env.Append(CFLAGS=['-g', '-Wall'])
env.Append(LINKFLAGS=['-g', '-stdlib=libstdc++'])
env.Append(LIBPATH=[
os.path.join(v8, 'xcodebuild/Release'),
os.path.join(uv, 'build/Release'),
])
else:
env.Append(LIBS=['v8_base', 'v8_libbase', 'v8_libplatform', 'v8_nosnapshot', 'icui18n', 'icuuc', 'icudata', 'pthread', 'uv', 'rt', 'dl'])
env.Append(CXXFLAGS=['--std=c++0x', '-g', '-Wall'])
env.Append(CFLAGS=['-g', '-Wall'])
env.Append(LINKFLAGS=['-g'])
env.Append(LIBPATH=[
os.path.join(v8, 'out/native/obj.target/third_party/icu'),
os.path.join(v8, 'out/native/obj.target/tools/gyp'),
os.path.join(uv, 'out/Debug/obj.target'),
])
ldapEnv = env.Clone()
if sys.platform == 'win32':
ldapEnv.Append(CPPPATH=['deps/win32'])
lmdb = ldapEnv.Library('build/lmdb', [
'build/deps/liblmdb/mdb.c',
'build/deps/liblmdb/midl.c',
])
env.Append(LIBS=[lmdb])
if sys.platform == 'linux2':
env.Append(LIBS=['crypto', 'ssl'])
source = [s for s in Glob('build/src/*.cpp') if not os.path.basename(str(s)).startswith("SecureSocket_")]
if sys.platform == 'darwin':
env.Append(FRAMEWORKS=['CoreFoundation', 'Security'])
elif sys.platform == 'win32':
env.Append(LIBS=['Crypt32'])
env.Program('sandboxos', source)
def listAllFiles(root):
for root, dirs, files in os.walk(root):
for f in files:
if not f.startswith('.'):
yield os.path.join(root, f)
hidden = [d for d in dirs if d.startswith('.')]
for d in hidden:
dirs.remove(d)
if env['package'] and sys.platform == 'win32':
files = [
'COPYING',
'LICENSE',
'SConstruct',
'sandboxos.exe',
]
files += listAllFiles('src')
files += listAllFiles('packages')
files += listAllFiles('core')
env.Package(
NAME='SandboxOS',
target='dist/SandboxOS-win32.zip',
PACKAGETYPE='zip',
PACKAGEROOT='SandboxOS-win32',
source=files
)

BIN
core/agplv3-88x31.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

17
core/auth.html Normal file
View File

@ -0,0 +1,17 @@
<html>
<head>
<title>Auth</title>
<script>
function showHideConfirm() {
document.getElementById("confirmPassword").style.display = document.getElementById("register").checked ? "block" : "none";
}
</script>
<link type="text/css" rel="stylesheet" href="/terminal/style.css"></link>
<link type="image/png" rel="shortcut icon" href="/terminal/favicon.png"></link>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Login</h1>
<div id="content">$(SESSION)</div>
</body>
</html>

209
core/auth.js Normal file
View File

@ -0,0 +1,209 @@
"use strict";
var kAccountsFile = "data/auth/accounts.json";
var gAccounts = {};
var gTokens = {};
var bCryptLib = require('bCrypt');
bCrypt = new bCryptLib.bCrypt();
var form = require('form');
File.makeDirectory("data");
File.makeDirectory("data/auth");
File.makeDirectory("data/auth/db");
var gDatabase = new Database("data/auth/db");
try {
gAccounts = JSON.parse(File.readFile(kAccountsFile));
} catch (error) {
}
function readSession(session) {
var result = session ? gDatabase.get("session_" + session) : null;
if (result) {
result = JSON.parse(result);
let kRefreshInterval = 1 * 60 * 60 * 1000;
let now = Date.now();
if (!result.lastAccess || result.lastAccess < now - kRefreshInterval) {
result.lastAccess = now;
writeSession(session, result);
}
}
return result;
}
function writeSession(session, value) {
gDatabase.set("session_" + session, JSON.stringify(value));
}
function removeSession(session, value) {
gDatabase.remove("session_" + session);
}
function newSession() {
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var result = "";
for (var i = 0; i < 32; i++) {
result += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
}
return result;
}
function verifyPassword(password, hash) {
return bCrypt.hashpw(password, hash) == hash;
}
function hashPassword(password) {
var salt = bCrypt.gensalt(12);
return bCrypt.hashpw(password, salt);
}
function noAdministrator() {
return !gGlobalSettings || !gGlobalSettings.permissions || !Object.keys(gGlobalSettings.permissions).some(function(name) {
return gGlobalSettings.permissions[name].indexOf("administration") != -1;
});
}
function makeAdministrator(name) {
if (!gGlobalSettings.permissions) {
gGlobalSettings.permissions = {};
}
if (!gGlobalSettings.permissions[name]) {
gGlobalSettings.permissions[name] = [];
}
if (gGlobalSettings.permissions[name].indexOf("administration") == -1) {
gGlobalSettings.permissions[name].push("administration");
}
setGlobalSettings(gGlobalSettings);
}
function authHandler(request, response) {
var session = getCookies(request.headers).session;
if (request.uri == "/login") {
var sessionIsNew = false;
var loginError;
var formData = form.decodeForm(request.query);
if (request.method == "POST" || formData.submit) {
session = newSession();
sessionIsNew = true;
formData = form.decodeForm(request.body, formData);
if (formData.submit == "Login") {
if (formData.register == "1") {
if (!gAccounts[formData.name] &&
formData.password == formData.confirm) {
gAccounts[formData.name] = {password: hashPassword(formData.password)};
writeSession(session, {name: formData.name});
File.writeFile(kAccountsFile, JSON.stringify(gAccounts));
if (noAdministrator()) {
makeAdministrator(formData.name);
}
} else {
loginError = "Error registering account.";
}
} else {
if (gAccounts[formData.name] &&
verifyPassword(formData.password, gAccounts[formData.name].password)) {
writeSession(session, {name: formData.name});
if (noAdministrator()) {
makeAdministrator(formData.name);
}
} else {
loginError = "Invalid username or password.";
}
}
} else {
// Proceed as Guest
writeSession(session, {name: "guest"});
}
}
var cookie = "session=" + session + "; path=/; Max-Age=604800";
var entry = readSession(session);
if (entry && formData.return) {
response.writeHead(303, {"Location": formData.return, "Set-Cookie": cookie});
response.end();
} else {
var html = File.readFile("core/auth.html");
var contents = "";
if (entry) {
if (sessionIsNew) {
contents += '<div>Welcome back, ' + entry.name + '.</div>\n';
} else {
contents += '<div>You are already logged in, ' + entry.name + '.</div>\n';
}
contents += '<div><a href="/login/logout">Logout</a></div>\n';
} else {
contents += '<form method="POST">\n';
if (loginError) {
contents += "<p>" + loginError + "</p>\n";
}
contents += '<div id="auth_greeting"><b>Halt. Who goes there?</b></div>\n'
contents += '<div id="auth">\n';
contents += '<div id="auth_login">\n'
if (noAdministrator()) {
contents += '<div class="notice">There is currently no administrator. You will be made administrator.</div>\n';
}
contents += '<div><label for="name">Name:</label> <input type="text" id="name" name="name" value=""></input></div>\n';
contents += '<div><label for="password">Password:</label> <input type="password" id="password" name="password" value=""></input></div>\n';
contents += '<div id="confirmPassword" style="display: none"><label for="confirm">Confirm:</label> <input type="password" id="confirm" name="confirm" value=""></input></div>\n';
contents += '<div><input type="checkbox" id="register" name="register" value="1" onchange="showHideConfirm()"></input> <label for="register">Register a new account</label></div>\n';
contents += '<div><input id="loginButton" type="submit" name="submit" value="Login"></input></div>\n';
contents += '</div>';
contents += '<div id="auth_or"> - or - </div>';
contents += '<div id="auth_guest">\n';
contents += '<input id="guestButton" type="submit" name="submit" value="Proceeed as Guest"></input>\n';
contents += '</div>\n';
contents += '</div>\n';
contents += '</form>';
}
var text = html.replace("$(SESSION)", contents);
response.writeHead(200, {"Content-Type": "text/html; charset=utf-6", "Set-Cookie": cookie, "Content-Length": text.length});
response.end(text);
}
} else if (request.uri == "/login/logout") {
removeSession(session);
response.writeHead(303, {"Set-Cookie": "session=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT", "Location": "/login" + (request.query ? "?" + request.query : "")});
response.end();
} else {
response.writeHead(200, {"Content-Type": "text/plain; charset=utf-8", "Connection": "close"});
response.end("Hello, " + request.client.peerName + ".");
}
}
function getPermissions(session) {
var permissions;
var entry = readSession(session);
if (entry) {
permissions = getPermissionsForUser(entry.name);
permissions.authenticated = entry.name !== "guest";
}
return permissions || {};
}
function getPermissionsForUser(userName) {
var permissions = {};
if (gGlobalSettings && gGlobalSettings.permissions && gGlobalSettings.permissions[userName]) {
for (var i in gGlobalSettings.permissions[userName]) {
permissions[gGlobalSettings.permissions[userName][i]] = true;
}
}
return permissions;
}
function query(headers) {
var session = getCookies(headers).session;
var entry;
if (entry = readSession(session)) {
return {session: entry, permissions: getPermissions(session)};
}
}
exports.handler = authHandler;
exports.query = query;

533
core/bCrypt.js Normal file
View File

@ -0,0 +1,533 @@
var isaac = require('isaac');
function bCrypt() {
this.GENSALT_DEFAULT_LOG2_ROUNDS = 10;
this.BCRYPT_SALT_LEN = 16;
this.BLOWFISH_NUM_ROUNDS = 16;
this.MAX_EXECUTION_TIME = 100;
this.P_orig = [0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822,
0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377,
0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5,
0xb5470917, 0x9216d5d9, 0x8979fb1b];
this.S_orig = [0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed,
0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7,
0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3,
0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023,
0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,
0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda,
0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af,
0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6,
0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381,
0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d,
0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5,
0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a,
0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c,
0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,
0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3,
0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724,
0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b,
0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd,
0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f,
0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd,
0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39,
0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df,
0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,
0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e,
0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98,
0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565,
0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341,
0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0,
0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64,
0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191,
0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0,
0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,
0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5,
0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b,
0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f,
0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968,
0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5,
0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6,
0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799,
0x6e85076a, 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71,
0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29,
0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6,
0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f,
0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286,
0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec,
0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9,
0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,
0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e,
0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290,
0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810,
0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6,
0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847,
0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451,
0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6,
0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570,
0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,
0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978,
0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708,
0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883,
0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185,
0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830,
0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239,
0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab,
0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19,
0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,
0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1,
0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef,
0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3,
0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15,
0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2,
0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492,
0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174,
0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759,
0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,
0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc,
0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465,
0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a,
0xe6e39f2b, 0xdb83adf7, 0xe93d5a68, 0x948140f7, 0xf64c261c,
0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e,
0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,
0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0,
0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462,
0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c,
0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399,
0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74,
0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397,
0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7,
0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802,
0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,
0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4,
0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2,
0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1,
0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c,
0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341,
0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8,
0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b,
0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88,
0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,
0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc,
0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659,
0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f,
0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8,
0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be,
0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2,
0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255,
0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1,
0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,
0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025,
0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01,
0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641,
0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa,
0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409,
0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9,
0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3,
0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234,
0x92638212, 0x670efa8e, 0x406000e0, 0x3a39ce37, 0xd3faf5cf,
0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740,
0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f,
0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d,
0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8,
0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba,
0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,
0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69,
0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a,
0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b,
0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd,
0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4,
0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2,
0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb,
0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751,
0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,
0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369,
0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd,
0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45,
0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae,
0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08,
0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d,
0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b,
0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e,
0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,
0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c,
0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361,
0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c,
0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be,
0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d,
0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891,
0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5,
0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292,
0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,
0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2,
0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c,
0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8,
0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4,
0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6];
this.bf_crypt_ciphertext = [0x4f727068, 0x65616e42, 0x65686f6c, 0x64657253,
0x63727944, 0x6f756274];
this.base64_code = ['.', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9'];
this.index_64 = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1,
54, 55, 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, -1, -1, -1,
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1, -1, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, 52, 53, -1, -1, -1, -1, -1];
this.P;
this.S;
this.lr;
this.offp;
};
bCrypt.prototype.getByte = function(c) {
var ret = 0;
try {
var b = c.charCodeAt(0);
} catch (err) {
b = c;
}
if (b > 127) {
return -128 + (b % 128);
} else {
return b;
}
};
bCrypt.prototype.encode_base64 = function(d, len) {
var off = 0;
var rs = [];
var c1;
var c2;
if (len <= 0 || len > d.length)
throw "Invalid len";
while (off < len) {
c1 = d[off++] & 0xff;
rs.push(this.base64_code[(c1 >> 2) & 0x3f]);
c1 = (c1 & 0x03) << 4;
if (off >= len) {
rs.push(this.base64_code[c1 & 0x3f]);
break;
}
c2 = d[off++] & 0xff;
c1 |= (c2 >> 4) & 0x0f;
rs.push(this.base64_code[c1 & 0x3f]);
c1 = (c2 & 0x0f) << 2;
if (off >= len) {
rs.push(this.base64_code[c1 & 0x3f]);
break;
}
c2 = d[off++] & 0xff;
c1 |= (c2 >> 6) & 0x03;
rs.push(this.base64_code[c1 & 0x3f]);
rs.push(this.base64_code[c2 & 0x3f]);
}
return rs.join('');
};
bCrypt.prototype.char64 = function(x) {
var code = x.charCodeAt(0);
if (code < 0 || code > this.index_64.length) {
return -1;
}
return this.index_64[code];
};
bCrypt.prototype.decode_base64 = function(s, maxolen) {
var off = 0;
var slen = s.length;
var olen = 0;
var rs = [];
var c1, c2, c3, c4, o;
if (maxolen <= 0)
throw "Invalid maxolen";
while (off < slen - 1 && olen < maxolen) {
c1 = this.char64(s.charAt(off++));
c2 = this.char64(s.charAt(off++));
if (c1 == -1 || c2 == -1) {
break;
}
o = this.getByte(c1 << 2);
o |= (c2 & 0x30) >> 4;
rs.push(String.fromCharCode(o));
if (++olen >= maxolen || off >= slen) {
break;
}
c3 = this.char64(s.charAt(off++));
if (c3 == -1) {
break;
}
o = this.getByte((c2 & 0x0f) << 4);
o |= (c3 & 0x3c) >> 2;
rs.push(String.fromCharCode(o));
if (++olen >= maxolen || off >= slen) {
break;
}
c4 = this.char64(s.charAt(off++));
o = this.getByte((c3 & 0x03) << 6);
o |= c4;
rs.push(String.fromCharCode(o));
++olen;
}
var ret = [];
for (off = 0; off < olen; off++) {
ret.push(this.getByte(rs[off]));
}
return ret;
};
bCrypt.prototype.encipher = function(lr, off) {
var i;
var n;
var l = lr[off];
var r = lr[off + 1];
l ^= this.P[0];
for (i = 0; i <= this.BLOWFISH_NUM_ROUNDS - 2;) {
// Feistel substitution on left word
n = this.S[(l >> 24) & 0xff];
n += this.S[0x100 | ((l >> 16) & 0xff)];
n ^= this.S[0x200 | ((l >> 8) & 0xff)];
n += this.S[0x300 | (l & 0xff)];
r ^= n ^ this.P[++i];
// Feistel substitution on right word
n = this.S[(r >> 24) & 0xff];
n += this.S[0x100 | ((r >> 16) & 0xff)];
n ^= this.S[0x200 | ((r >> 8) & 0xff)];
n += this.S[0x300 | (r & 0xff)];
l ^= n ^ this.P[++i];
}
lr[off] = r ^ this.P[this.BLOWFISH_NUM_ROUNDS + 1];
lr[off + 1] = l;
};
bCrypt.prototype.streamtoword = function(data, offp) {
var i;
var word = 0;
var off = offp;
for (i = 0; i < 4; i++) {
word = (word << 8) | (data[off] & 0xff);
off = (off + 1) % data.length;
}
this.offp = off;
return word;
};
bCrypt.prototype.init_key = function() {
this.P = this.P_orig.slice();
this.S = this.S_orig.slice();
};
bCrypt.prototype.key = function(key) {
var i;
this.offp = 0;
var lr = new Array(0x00000000, 0x00000000);
var plen = this.P.length;
var slen = this.S.length;
for (i = 0; i < plen; i++) {
this.P[i] = this.P[i] ^ this.streamtoword(key, this.offp);
}
for (i = 0; i < plen; i += 2) {
this.encipher(lr, 0);
this.P[i] = lr[0];
this.P[i + 1] = lr[1];
}
for (i = 0; i < slen; i += 2) {
this.encipher(lr, 0);
this.S[i] = lr[0];
this.S[i + 1] = lr[1];
}
};
bCrypt.prototype.ekskey = function(data, key) {
var i;
this.offp = 0;
var lr = new Array(0x00000000, 0x00000000);
var plen = this.P.length;
var slen = this.S.length;
for (i = 0; i < plen; i++)
this.P[i] = this.P[i] ^ this.streamtoword(key, this.offp);
this.offp = 0;
for (i = 0; i < plen; i += 2) {
lr[0] ^= this.streamtoword(data, this.offp);
lr[1] ^= this.streamtoword(data, this.offp);
this.encipher(lr, 0);
this.P[i] = lr[0];
this.P[i + 1] = lr[1];
}
for (i = 0; i < slen; i += 2) {
lr[0] ^= this.streamtoword(data, this.offp);
lr[1] ^= this.streamtoword(data, this.offp);
this.encipher(lr, 0);
this.S[i] = lr[0];
this.S[i + 1] = lr[1];
}
};
bCrypt.prototype.crypt_raw = function(password, salt, log_rounds) {
var rounds;
var j;
var cdata = this.bf_crypt_ciphertext.slice();
var clen = cdata.length;
var one_percent;
if (log_rounds < 4 || log_rounds > 31)
throw "Bad number of rounds";
if (salt.length != this.BCRYPT_SALT_LEN)
throw "Bad salt length";
rounds = 1 << log_rounds;
one_percent = Math.floor(rounds / 100) + 1;
this.init_key();
this.ekskey(salt, password);
var obj = this;
var i = 0;
for (; i < rounds;) {
i = i + 1;
obj.key(password);
obj.key(salt);
}
for (i = 0; i < 64; i++) {
for (j = 0; j < (clen >> 1); j++) {
obj.encipher(cdata, j << 1);
}
}
var ret = [];
for (i = 0; i < clen; i++) {
ret.push(obj.getByte((cdata[i] >> 24) & 0xff));
ret.push(obj.getByte((cdata[i] >> 16) & 0xff));
ret.push(obj.getByte((cdata[i] >> 8) & 0xff));
ret.push(obj.getByte(cdata[i] & 0xff));
}
return ret;
}
bCrypt.prototype.hashpw = function(password, salt) {
var real_salt;
var passwordb = [];
var saltb = [];
var hashed = [];
var minor = String.fromCharCode(0);
var rounds = 0;
var off = 0;
if (!progress){
var progress = function() {};
}
if (salt.charAt(0) != '$' || salt.charAt(1) != '2')
throw "Invalid salt version";
if (salt.charAt(2) == '$')
off = 3;
else {
minor = salt.charAt(2);
if (minor != 'a' || salt.charAt(3) != '$')
throw "Invalid salt revision";
off = 4;
}
// Extract number of rounds
if (salt.charAt(off + 2) > '$')
throw "Missing salt rounds";
var r1 = parseInt(salt.substring(off, off + 1)) * 10;
var r2 = parseInt(salt.substring(off + 1, off + 2));
rounds = r1 + r2;
real_salt = salt.substring(off + 3, off + 25);
password = password + (minor >= 'a' ? "\000" : "");
for (var r = 0; r < password.length; r++) {
passwordb.push(this.getByte(password.charAt(r)));
}
saltb = this.decode_base64(real_salt, this.BCRYPT_SALT_LEN);
var obj = this;
var hashed = this.crypt_raw(passwordb, saltb, rounds);
var rs = [];
rs.push("$2");
if (minor >= 'a')
rs.push(minor);
rs.push("$");
if (rounds < 10)
rs.push("0");
rs.push(rounds.toString());
rs.push("$");
rs.push(obj.encode_base64(saltb, saltb.length));
rs.push(obj.encode_base64(hashed, obj.bf_crypt_ciphertext.length * 4 - 1));
return rs.join('');
};
bCrypt.prototype.gensalt = function(rounds) {
var iteration_count = rounds;
if (iteration_count < 4 || iteration_count > 31) {
iteration_count = this.GENSALT_DEFAULT_LOG2_ROUNDS;
}
var output = [];
output.push("$2a$");
if (iteration_count < 10)
output.push("0");
output.push(iteration_count.toString());
output.push('$');
var s1 = [];
for (var r = 0; r < this.BCRYPT_SALT_LEN; r++){
s1.push(Math.abs(isaac.rand()));
}
output.push(this.encode_base64(s1,this.BCRYPT_SALT_LEN))
return output.join('');
};
bCrypt.prototype.ready = function(){
return true;
};
exports.bCrypt = bCrypt;

403
core/client.js Normal file
View File

@ -0,0 +1,403 @@
"use strict";
var gHaveIndex = -1;
var gSessionId;
var gCredentials;
var gErrorCount = 0;
function enter(event) {
if (event.keyCode == 13) {
send();
event.preventDefault();
} else if (event.keyCode == 186
&& !event.metaKey
&& !event.altKey
&& !event.ctrlKey
&& !event.shiftKey) {
var value = $("#input").val();
if (value && value[value.length - 1] == '\\') {
$("#input").val(value.substring(0, value.length - 1) + ";");
event.preventDefault();
} else {
storeTarget(value);
$("#input").val("");
event.preventDefault();
}
}
}
function url() {
var hash = window.location.href.indexOf('#');
var question = window.location.href.indexOf('?');
var end = hash != -1 ? hash : question;
return end != -1 ? window.location.href.substring(0, end) : window.location.href;
}
function storeTarget(target) {
$("#target").text(target || "");
}
function split(container, children) {
if (container) {
while (container.firstChild) {
container.removeChild(container.firstChild);
}
}
if (children) {
for (var i = 0; i < children.length; i++) {
if (children[i].name) {
var node = document.createElement("div");
node.setAttribute("id", "terminal_" + children[i].name);
var grow = children[i].grow || "1";
var shrink = children[i].shrink || "1";
var basis = children[i].basis || "auto";
node.setAttribute("style", "flex: " + grow + " " + shrink + " " + basis);
node.setAttribute("class", "terminal");
container.appendChild(node);
} else if (children[i].type) {
node = document.createElement("div");
if (children[i].type == "horizontal") {
node.setAttribute("class", "hbox");
} else if (children[i].type == "vertical") {
node.setAttribute("class", "vbox");
}
container.appendChild(node);
split(node, children[i].children);
}
}
}
}
function receive() {
$.ajax({
url: url() + "/receive?sessionId=" + gSessionId,
method: "POST",
data: gHaveIndex.toString(),
dataType: "json",
}).then(function(data) {
for (var i in data.lines) {
var line = data.lines[i];
var target = document.getElementsByClassName("terminal")[0].id;
if (line && line.terminal) {
if (document.getElementById("terminal_" + line.terminal)) {
target = "terminal_" + line.terminal;
}
line = line.value;
}
if (line && line.action == "ping") {
// PONG
} else if (line && line.action == "session") {
gSessionId = line.session.sessionId;
gCredentials = line.session.credentials;
updateLogin();
} else if (line && line[0] && line[0].action == "ready") {
if (window.location.hash) {
send({event: "hashChange", hash: window.location.hash});
}
} else if (line && line[0] && line[0].action == "notify") {
new Notification(line[0].title, line[0].options);
} else if (line && line[0] && line[0].action == "title") {
window.document.title = line[0].value;
} else if (line && line[0] && line[0].action == "prompt") {
var prompt = document.getElementById("prompt");
while (prompt.firstChild) {
prompt.removeChild(prompt.firstChild);
}
prompt.appendChild(document.createTextNode(line[0].value));
} else if (line && line[0] && line[0].action == "password") {
var prompt = document.getElementById("input");
prompt.setAttribute("type", line[0].value ? "password" : "text");
} else if (line && line[0] && line[0].action == "hash") {
window.location.hash = line[0].value;
} else if (line && line[0] && line[0].action == "update") {
document.getElementById("update").setAttribute("Style", "display: inline");
} else if (line && line[0] && line[0].action == "split") {
split(document.getElementById("terminals"), line[0].options);
} else if (line && line[0] && line[0].action == "postMessageToIframe") {
var iframe = document.getElementById("iframe_" + line[0].name);
if (iframe) {
iframe.contentWindow.postMessage(line[0].message, "*");
}
} else {
print(document.getElementById(target), line);
}
}
if ("index" in data) {
gHaveIndex = data.index;
}
receive();
if (gErrorCount) {
document.getElementById("status").setAttribute("style", "display: none");
}
gErrorCount = 0;
}).fail(function(xhr, message, error) {
var node = document.getElementById("status");
while (node.firstChild) {
node.removeChild(node.firstChild);
}
node.appendChild(document.createTextNode("ERROR: " + JSON.stringify([message, error])));
node.setAttribute("style", "display: inline; color: #dc322f");
if (gErrorCount < 60) {
setTimeout(receive, 1000);
} else {
setTimeout(receive, 60 * 1000);
}
gErrorCount++;
});
}
function autoNewLine(terminal) {
terminal.appendChild(document.createElement("br"));
}
function print(terminal, data) {
autoNewLine(terminal);
printStructured(terminal, data);
autoScroll(terminal);
}
function printStructured(container, data) {
if (typeof data == "string") {
container.appendChild(document.createTextNode(data));
} else if (data && data[0] !== undefined) {
for (var i in data) {
printStructured(container, data[i]);
}
} else if (data && data.action == "clear") {
while (container.firstChild) {
container.removeChild(container.firstChild);
}
} else if (data) {
var node;
if (data.href) {
node = document.createElement("a");
node.setAttribute("href", data.href);
node.setAttribute("target", "_blank");
} else if (data.iframe) {
node = document.createElement("iframe");
node.setAttribute("srcdoc", data.iframe);
node.setAttribute("sandbox", "allow-forms allow-scripts");
node.setAttribute("width", data.width || 320);
node.setAttribute("height", data.height || 240);
if (data.name) {
node.setAttribute("id", "iframe_" + data.name);
}
} else if (data.image) {
node = document.createElement("img");
node.setAttribute("src", data.image);
} else {
node = document.createElement("span");
}
if (data.style) {
node.setAttribute("style", data.style);
}
if (data.class) {
node.setAttribute("class", data.class);
}
var value = data.value || data.href || data.command || "";
if (!value && data.message && data.stackTrace) {
printStructured(node, data.message);
node.appendChild(document.createElement("br"));
printStructured(node, data.fileName + ":" + data.lineNumber + ":");
node.appendChild(document.createElement("br"));
if (data.stackTrace.length) {
for (var i = 0; i < data.stackTrace.length; i++) {
printStructured(node, data.stackTrace[i]);
node.appendChild(document.createElement("br"));
}
} else {
printStructured(node, data.sourceLine);
}
} else if (value === undefined) {
printStructured(node, JSON.stringify(value));
} else {
printStructured(node, value);
}
if (data.command) {
node.dataset.command = data.command;
node.onclick = commandClick;
node.setAttribute("class", "command");
}
container.appendChild(node);
} else {
printStructured(container, JSON.stringify(data));
}
}
function commandClick() {
send(this.dataset.command);
$("#input").focus();
}
function autoScroll(terminal) {
terminal.scrollTop = terminal.scrollHeight - terminal.clientHeight;
}
function send(command) {
var value = command;
if (!command) {
var target = $("#target").text();
var prefix = target ? target + " " : "";
value = prefix + $("#input").val();
$("#input").val("");
}
$.ajax({
url: url() + "/send?sessionId=" + gSessionId,
method: "POST",
data: JSON.stringify(value),
dataType: "text",
}).fail(function(xhr, status, error) {
var node = document.getElementById("status");
while (node.firstChild) {
node.removeChild(node.firstChild);
}
node.appendChild(document.createTextNode("Send failed: " + JSON.stringify([status, error])));
node.setAttribute("style", "display: inline; color: #dc322f");
});
}
function updateLogin() {
var login = document.getElementById("login");
while (login.firstChild) {
login.removeChild(login.firstChild);
}
var a = document.createElement("a");
if (gCredentials && gCredentials.session) {
a.appendChild(document.createTextNode("logout " + gCredentials.session.name));
a.setAttribute("href", "/login/logout?return=" + encodeURIComponent(url()));
} else if (window.location.href.indexOf("?guest=1") != -1) {
window.location.href = "/login?submit=Proceed+as+Guest&return=" + encodeURIComponent(url());
} else {
window.location.href = "/login?return=" + encodeURIComponent(url());
}
login.appendChild(a);
}
var gOriginalInput;
function dragHover(event) {
event.stopPropagation();
event.preventDefault();
if (event.type == "dragover") {
if (!$("#input").hasClass("drop")) {
$("#input").addClass("drop");
gOriginalInput = $("#input").val();
$("#input").val("drop file to upload");
}
} else {
$("#input").removeClass("drop");
$("#input").val(gOriginalInput);
}
}
function fixImage(sourceData, maxWidth, maxHeight, callback) {
var result = sourceData;
var image = new Image();
image.crossOrigin = "anonymous";
image.referrerPolicy = "no-referrer";
image.onload = function() {
if (image.width > maxWidth || image.height > maxHeight) {
var downScale = Math.min(maxWidth / image.width, maxHeight / image.height);
var canvas = document.createElement("canvas");
canvas.width = image.width * downScale;
canvas.height = image.height * downScale;
var context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
image.width = canvas.width;
image.height = canvas.height;
context.drawImage(image, 0, 0, image.width, image.height);
result = canvas.toDataURL();
}
callback(result);
};
image.src = sourceData;
}
function sendImage(image) {
fixImage(image, 320, 240, function(result) {
send({image: result});
});
}
function fileDropRead(event) {
sendImage(event.target.result);
}
function fileDrop(event) {
dragHover(event);
var done = false;
if (!done) {
var files = event.target.files || event.dataTransfer.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (file.type.substring(0, "image/".length) == "image/") {
var reader = new FileReader();
reader.onloadend = fileDropRead;
reader.readAsDataURL(file);
done = true;
}
}
}
if (!done) {
var html = event.dataTransfer.getData("text/html");
var match = /<img.*src="([^"]+)"/.exec(html);
if (match) {
sendImage(match[1]);
done = true;
}
}
if (!done) {
var text = event.dataTransfer.getData("text/plain");
if (text) {
send(text);
done = true;
}
}
}
function enableDragDrop() {
var body = document.body;
body.addEventListener("dragover", dragHover);
body.addEventListener("dragleave", dragHover);
body.addEventListener("drop", fileDrop);
}
function hashChange() {
send({event: 'hashChange', hash: window.location.hash});
}
function focus() {
send({event: "focus"});
}
function blur() {
send({event: "blur"});
}
function onMessage(event) {
send({event: "onWindowMessage", message: event.data});
}
$(document).ready(function() {
if (Notification) {
Notification.requestPermission();
}
$("#input").keydown(enter);
$("#input").focus();
window.addEventListener("hashchange", hashChange);
window.addEventListener("focus", focus);
window.addEventListener("blur", blur);
window.addEventListener("message", onMessage, false);
enableDragDrop();
});
$(window).load(function() {
setTimeout(function() {
receive();
}, 0);
});

413
core/core.js Normal file
View File

@ -0,0 +1,413 @@
"use strict";
var terminal = require("terminal");
var auth = require("auth");
var network = require("network");
var gProcessIndex = 0;
var gProcesses = {};
var gGlobalSettings = {
index: "/~cory/index",
};
var kGlobalSettingsFile = "data/global/settings.json";
var kPingInterval = 60 * 1000;
function getCookies(headers) {
var cookies = {};
if (headers.cookie) {
var parts = headers.cookie.split(/,|;/);
for (var i in parts) {
var equals = parts[i].indexOf("=");
var name = parts[i].substring(0, equals).trim();
var value = parts[i].substring(equals + 1).trim();
cookies[name] = value;
}
}
return cookies;
}
function makeSessionId() {
var id = "";
for (var i = 0; i < 64; i++) {
id += (Math.floor(Math.random() * 16)).toString(16);
}
return id;
}
function printError(out, error) {
if (error.stackTrace) {
out.print(error.fileName + ":" + error.lineNumber + ": " + error.message);
out.print(error.stackTrace);
} else {
for (var i in error) {
out.print(i);
}
out.print(error.toString());
}
}
function broadcastEvent(eventName, argv) {
var promises = [];
for (var i in gProcesses) {
var process = gProcesses[i];
promises.push(invoke(process.eventHandlers[eventName], argv));
}
return Promise.all(promises);
}
function broadcast(message) {
var sender = this;
var promises = [];
for (var i in gProcesses) {
var process = gProcesses[i];
if (process != sender
&& process.packageOwner == sender.packageOwner
&& process.packageName == sender.packageName) {
var from = getUser(process, sender);
promises.push(postMessageInternal(from, process, message));
}
}
return Promise.all(promises);
}
function getDatabase(process) {
if (!process.database) {
File.makeDirectory("data");
File.makeDirectory("data/" + process.packageOwner);
File.makeDirectory("data/" + process.packageOwner + "/" + process.packageName);
File.makeDirectory("data/" + process.packageOwner + "/" + process.packageName + "/db");
process.database = new Database("data/" + process.packageOwner + "/" + process.packageName + "/db");
}
return process.database;
}
function databaseGet(key) {
return getDatabase(this).get(key);
}
function databaseSet(key, value) {
return getDatabase(this).set(key, value);
}
function databaseRemove(key) {
return getDatabase(this).remove(key);
}
function databaseGetAll() {
return getDatabase(this).getAll();
}
function getPackages() {
var packages = [];
var packageOwners = File.readDirectory("packages/");
for (var i = 0; i < packageOwners.length; i++) {
if (packageOwners[i].charAt(0) != ".") {
var packageNames = File.readDirectory("packages/" + packageOwners[i] + "/");
for (var j = 0; j < packageNames.length; j++) {
if (packageNames[j].charAt(0) != ".") {
packages.push({owner: packageOwners[i], name: packageNames[j]});
}
}
}
}
return packages;
}
function getUser(caller, process) {
return {
name: process.userName,
index: process.index,
packageOwner: process.packageOwner,
packageName: process.packageName,
credentials: process.credentials,
postMessage: postMessageInternal.bind(caller, caller, process),
};
}
function getUsers(packageOwner, packageName) {
var result = [];
for (var key in gProcesses) {
var process = gProcesses[key];
if ((!packageOwner || process.packageOwner == packageOwner)
&& (!packageName || process.packageName == packageName)) {
result.push(getUser(this, process));
}
}
return result;
}
function ping() {
var process = this;
var now = Date.now();
var again = true;
if (now - process.lastActive < process.timeout) {
// Active.
} else if (process.lastPing > process.lastActive) {
// We lost them.
process.task.kill();
again = false;
} else {
// Idle. Ping them.
process.terminal.ping();
process.lastPing = now;
}
if (again) {
setTimeout(ping.bind(process), process.timeout);
}
}
function postMessageInternal(from, to, message) {
return invoke(to.eventHandlers['onMessage'], [getUser(from, from), message]);
}
function getService(service) {
var process = this;
var serviceProcess = getServiceProcess(process.packageOwner, process.packageName, service);
return serviceProcess.ready.then(function() {
return {
postMessage: postMessageInternal.bind(process, process, serviceProcess),
}
});
}
function getSessionProcess(packageOwner, packageName, session, options) {
var actualOptions = {terminal: true, timeout: kPingInterval};
if (options) {
for (var i in options) {
actualOptions[i] = options[i];
}
}
return getProcess(packageOwner, packageName, 'session_' + session, actualOptions);
}
function getServiceProcess(packageOwner, packageName, service, options) {
return getProcess(packageOwner, packageName, 'service_' + packageOwner + '_' + packageName + '_' + service, options || {});
}
function badName(name) {
var bad = false;
if (name) {
for (var i = 0; i < name.length; i++) {
if ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890-_".indexOf(name.charAt(i)) == -1) {
bad = true;
break;
}
}
}
return bad;
}
function getManifest(fileName) {
var manifest = [];
var lines = File.readFile(fileName).split("\n").map(x => x.trimRight());
for (var i = 0; i < lines.length; i++) {
if (lines[i].substring(0, 4) == "//! ") {
manifest.push(lines[i].substring(4));
}
}
return manifest.length ? JSON.parse(manifest.join("\n")) : null;
}
function getProcess(packageOwner, packageName, key, options) {
var process = gProcesses[key];
if (!process
&& !(options && "create" in options && !options.create)
&& !badName(packageOwner)
&& !badName(packageName)) {
try {
print("Creating task for " + packageName + " " + key);
var fileName = "packages/" + packageOwner + "/" + packageName + "/" + packageName + ".js";
var manifest = getManifest(fileName);
process = {};
process.key = key;
process.index = gProcessIndex++;
process.userName = options.userName || ('user' + process.index);
process.credentials = options.credentials || {};
process.task = new Task();
process.eventHandlers = {};
process.packageOwner = packageOwner;
process.packageName = packageName;
if (options.terminal) {
process.terminal = new Terminal();
}
process.database = null;
process.lastActive = Date.now();
process.lastPing = null;
process.timeout = options.timeout;
process.connections = [];
var resolveReady;
var rejectReady;
process.ready = new Promise(function(resolve, reject) {
resolveReady = resolve;
rejectReady = reject;
});
gProcesses[key] = process;
process.task.onExit = function(exitCode, terminationSignal) {
broadcastEvent('onSessionEnd', [getUser(process, process)]);
if (process.terminal) {
if (terminationSignal) {
process.terminal.print("Process terminated with signal " + terminationSignal + ".");
} else {
process.terminal.print("Process ended with exit code " + exitCode + ".");
}
}
for (let i = 0; i < process.connections.length; i++) {
process.connections[i].close();
}
process.connections.length = 0;
delete gProcesses[key];
};
if (process.timeout > 0) {
setTimeout(ping.bind(process), process.timeout);
}
var imports = {
'core': {
'broadcast': broadcast.bind(process),
'getService': getService.bind(process),
'getPackages': getPackages.bind(process),
'getUsers': getUsers.bind(process),
'register': function(eventName, handler) {
if (!process.eventHandlers[eventName]) {
process.eventHandlers[eventName] = [];
}
process.eventHandlers[eventName].push(handler);
},
'getUser': getUser.bind(null, process, process),
'user': getUser(process, process),
},
'database': {
'get': databaseGet.bind(process),
'set': databaseSet.bind(process),
'remove': databaseRemove.bind(process),
'getAll': databaseGetAll.bind(process),
},
};
if (options.terminal) {
imports.terminal = {
'print': process.terminal.print.bind(process.terminal),
'clear': process.terminal.clear.bind(process.terminal),
'readLine': process.terminal.readLine.bind(process.terminal),
'notify': process.terminal.notify.bind(process.terminal),
'setEcho': process.terminal.setEcho.bind(process.terminal),
'setTitle': process.terminal.setTitle.bind(process.terminal),
'setPrompt': process.terminal.setPrompt.bind(process.terminal),
'setPassword': process.terminal.setPassword.bind(process.terminal),
'setHash': process.terminal.setHash.bind(process.terminal),
'split': process.terminal.split.bind(process.terminal),
'select': process.terminal.select.bind(process.terminal),
'postMessageToIframe': process.terminal.postMessageToIframe.bind(process.terminal),
};
}
if (manifest
&& manifest.permissions
&& manifest.permissions.indexOf("administration") != -1) {
if (getPermissionsForUser(packageOwner).administration) {
imports.administration = {
'setGlobalSettings': setGlobalSettings.bind(process),
'getGlobalSettings': getGlobalSettings.bind(process),
'getStatistics': function() { return statistics; },
};
} else {
throw new Error(packageOwner + " does not have right to permission 'administration'.");
}
}
if (manifest
&& manifest.permissions
&& manifest.permissions.indexOf("network") != -1) {
if (getPermissionsForUser(packageOwner).network) {
imports.network = {
'newConnection': newConnection.bind(process),
};
} else {
throw new Error(packageOwner + " does not have right to permission 'network'.");
}
}
process.task.setImports(imports);
print("Activating task");
process.task.activate();
print("Executing task");
process.task.execute(fileName).then(function() {
print("Task ready");
broadcastEvent('onSessionBegin', [getUser(process, process)]);
resolveReady(process);
}).catch(function(error) {
printError(process.terminal, error);
rejectReady();
});
} catch (error) {
printError(process.terminal, error);
rejectReady();
}
}
return process;
}
function updateProcesses(packageOwner, packageName) {
for (var i in gProcesses) {
var process = gProcesses[i];
if (process.packageOwner == packageOwner
&& process.packageName == packageName) {
if (process.terminal) {
process.terminal.notifyUpdate();
} else {
process.task.kill();
}
}
}
}
function makeDirectoryForFile(fileName) {
var parts = fileName.split("/");
var path = "";
for (var i = 0; i < parts.length - 1; i++) {
path += parts[i];
File.makeDirectory(path);
path += "/";
}
}
function getGlobalSettings() {
return gGlobalSettings;
}
function setGlobalSettings(settings) {
makeDirectoryForFile(kGlobalSettingsFile);
if (!File.writeFile(kGlobalSettingsFile, JSON.stringify(settings))) {
gGlobalSettings = settings;
} else {
throw new Error("Unable to save settings.");
}
}
try {
gGlobalSettings = JSON.parse(File.readFile(kGlobalSettingsFile));
} catch (error) {
print("Error loading settings from " + kGlobalSettingsFile + ": " + error);
}
var kIgnore = ["/favicon.ico"];
var auth = require("auth");
var httpd = require("httpd");
httpd.all("/login", auth.handler);
httpd.all("", function(request, response) {
var match;
if (request.uri === "/" || request.uri === "") {
response.writeHead(303, {"Location": gGlobalSettings.index, "Content-Length": "0"});
return response.end();
} else if (match = /^\/terminal(\/.*)/.exec(request.uri)) {
return terminal.handler(request, response, null, null, match[1]);
} else if (match = /^\/\~([^\/]+)\/([^\/]+)(.*)/.exec(request.uri)) {
return terminal.handler(request, response, match[1], match[2], match[3]);
} else {
var data = "File not found.";
response.writeHead(404, {"Content-Type": "text/plain; charset=utf-8", "Content-Length": data.length.toString()});
return response.end(data);
}
});

28
core/edit.html Normal file
View File

@ -0,0 +1,28 @@
<html>
<head>
<title>Web Terminal</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.12.0/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.12.0/addon/edit/trailingspace.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.12.0/codemirror.min.css"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.12.0/theme/base16-dark.min.css"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.12.0/mode/javascript/javascript.min.js"></script>
<link type ="text/css" rel="stylesheet" href="/terminal/style.css"></link>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link type="image/png" rel="shortcut icon" href="/terminal/favicon.png"></link>
</head>
<body>
<div id="body">
<div>
<input type="button" id="back" name="back" value="Back" onclick="back()">
<input type="button" id="save" name="save" value="Save" onclick="save()">
<input type="button" id="saveAs" name="saveAs" value="Save As" onclick="saveAs()">
<input type="checkbox" id="run" name="run" checked><label for="run">Run after Saving</label>
<input type="button" id="revert" name="revert" value="Revert to Saved" onclick="revert()">
<button onclick="addLicense()"><img src="/terminal/agplv3-88x31.png" width="34" height="12"> Add License Header</button>
</div>
<textarea id="editor" class="main">$(SOURCE)</textarea>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="/terminal/editor.js"></script>
</div>
</body>
</html>

92
core/editor.js Normal file
View File

@ -0,0 +1,92 @@
var gBackup;
var gEditor;
$(document).ready(function() {
gEditor = CodeMirror.fromTextArea(document.getElementById("editor"), {
'theme': 'base16-dark',
'lineNumbers': true,
'tabSize': 4,
'indentUnit': 4,
'indentWithTabs': true,
'showTrailingSpace': true,
});
gBackup = gEditor.getValue();
});
function explodePath() {
return /^\/~([^\/]+)\/([^\/]+)(.*)/.exec(window.location.pathname);
}
function packageOwner() {
return explodePath()[1];
}
function packageName() {
return explodePath()[2];
}
function back(uri) {
if (uri) {
window.location.pathname = uri;
} else {
window.location.pathname = "/~" + packageOwner() + "/" + packageName();
}
}
function save(newName) {
document.getElementById("save").disabled = true;
document.getElementById("saveAs").disabled = true;
var contents = gEditor.getValue();
var run = document.getElementById("run").checked;
return $.ajax({
type: "POST",
url: newName ? "../" + newName + "/save" : "save",
data: contents,
dataType: "text",
}).done(function(uri) {
gBackup = contents;
if (run) {
back(uri);
}
}).fail(function(xhr, status, error) {
alert("Unable to save: " + xhr.responseText);
}).always(function() {
document.getElementById("save").disabled = false;
document.getElementById("saveAs").disabled = false;
});
}
function saveAs() {
var newName = prompt("Save as:", packageName());
if (newName) {
save(newName);
}
}
function revert() {
gEditor.setValue(gBackup);
}
function addLicense() {
var contents = "/*\n" +
"<one line to give the program's name and a brief idea of what it does.>\n" +
"Copyright (C) <year> <name of author>\n".replace("<year>", new Date().getFullYear()) +
"\n" +
"This program is free software: you can redistribute it and/or modify\n" +
"it under the terms of the GNU Affero General Public License as published by\n" +
"the Free Software Foundation, either version 3 of the License, or\n" +
"(at your option) any later version.\n" +
"\n" +
"This program is distributed in the hope that it will be useful,\n" +
"but WITHOUT ANY WARRANTY; without even the implied warranty of\n" +
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" +
"GNU Affero General Public License for more details.\n" +
"\n" +
"You should have received a copy of the GNU Affero General Public License\n" +
"along with this program. If not, see <http://www.gnu.org/licenses/>.\n" +
"*/\n\n" +
gEditor.getValue();
gEditor.setValue(contents);
}

BIN
core/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 320 B

33
core/form.js Normal file
View File

@ -0,0 +1,33 @@
function decode(encoded) {
var result = "";
for (var i = 0; i < encoded.length; i++) {
var c = encoded[i];
if (c == "+") {
result += " ";
} else if (c == "%") {
result += String.fromCharCode(parseInt(encoded.slice(i + 1, i + 3), 16));
i += 2;
} else {
result += c;
}
}
return result;
}
function decodeForm(encoded, initial) {
var result = initial || {};
if (encoded) {
encoded = encoded.trim();
var items = encoded.split('&');
for (var i = 0; i < items.length; i++) {
var item = items[i];
var equals = item.indexOf('=');
var key = decode(item.slice(0, equals));
var value = decode(item.slice(equals + 1));
result[key] = value;
}
}
return result;
}
exports.decodeForm = decodeForm;

286
core/httpd.js Normal file
View File

@ -0,0 +1,286 @@
var gHandlers = [];
function logError(error) {
print("ERROR " + error);
}
function addHandler(handler) {
var added = false;
for (var i in gHandlers) {
if (gHandlers[i].path == handler.path) {
gHandlers[i] = handler;
added = true;
break;
}
}
if (!added) {
gHandlers.push(handler);
added = true;
}
}
function all(prefix, handler) {
addHandler({
owner: this,
path: prefix,
invoke: handler,
});
}
function Request(method, uri, version, headers, body, client) {
this.method = method;
var index = uri.indexOf("?");
if (index != -1) {
this.uri = uri.slice(0, index);
this.query = uri.slice(index + 1);
} else {
this.uri = uri;
this.query = undefined;
}
this.version = version;
this.headers = headers;
this.client = {peerName: client.peerName};
this.body = body;
return this;
}
function findHandler(request) {
var matchedHandler = null;
for (var name in gHandlers) {
var handler = gHandlers[name];
if (request.uri == handler.path || request.uri.slice(0, handler.path.length + 1) == handler.path + '/') {
matchedHandler = handler;
break;
}
}
return matchedHandler;
}
function Response(request, client) {
var kStatusText = {
200: 'OK',
303: 'See other',
404: 'File not found',
500: 'Internal server error',
};
var _started = false;
var _finished = false;
var _keepAlive = false;
var _chunked = false;
return {
writeHead: function(status) {
if (_started) {
throw new Error("Response.writeHead called multiple times.");
}
var reason;
var headers;
if (arguments.length == 3) {
reason = arguments[1];
headers = arguments[2];
} else {
reason = kStatusText[status];
headers = arguments[1];
}
var lowerHeaders = {};
var requestVersion = request.version.split("/")[1].split(".");
var responseVersion = (requestVersion[0] >= 1 && requestVersion[0] >= 1) ? "1.1" : "1.0";
var headerString = "HTTP/" + responseVersion + " " + status + " " + reason + "\r\n";
for (var i in headers) {
headerString += i + ": " + headers[i] + "\r\n";
lowerHeaders[i.toLowerCase()] = headers[i];
}
if ("connection" in lowerHeaders) {
_keepAlive = lowerHeaders["connection"].toLowerCase() == "keep-alive";
} else {
_keepAlive = ((request.version == "HTTP/1.0" && ("connection" in lowerHeaders && lowerHeaders["connection"].toLowerCase() == "keep-alive")) ||
(request.version == "HTTP/1.1" && (!("connection" in lowerHeaders) || lowerHeaders["connection"].toLowerCase() != "close")));
headerString += "Connection: " + (_keepAlive ? "keep-alive" : "close") + "\r\n";
}
_chunked = _keepAlive && !("content-length" in lowerHeaders);
if (_chunked) {
headerString += "Transfer-Encoding: chunked\r\n";
}
headerString += "\r\n";
_started = true;
client.write(headerString);
},
end: function(data) {
if (_finished) {
throw new Error("Response.end called multiple times.");
}
if (data) {
if (_chunked) {
client.write(data.length.toString(16) + "\r\n" + data + "\r\n" + "0\r\n\r\n");
} else {
client.write(data);
}
} else if (_chunked) {
client.write("0\r\n\r\n");
}
_finished = true;
if (!_keepAlive) {
client.shutdown();
}
},
reportError: function(error) {
if (!_started) {
client.write("HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n");
}
if (!_finished) {
client.write("500 Internal Server Error\r\n\r\n" + error.stackTrace);
client.shutdown();
}
logError(client.peerName + " - - [" + new Date() + "] " + error);
},
isConnected: function() { return client.isConnected; },
};
}
function handleRequest(request, response) {
var handler = findHandler(request);
print(request.client.peerName + " - - [" + new Date() + "] " + request.method + " " + request.uri + " " + request.version + " \"" + request.headers["user-agent"] + "\"");
if (handler) {
try {
handler.invoke(request, response);
} catch (error) {
response.reportError(error);
}
} else {
response.writeHead(200, {"Content-Type": "text/plain; charset=utf-8"});
response.end("No handler found for request: " + request.uri);
}
}
function handleConnection(client) {
var inputBuffer = "";
var request;
var headers = {};
var lineByLine = true;
var bodyToRead = -1;
var body;
function reset() {
inputBuffer = "";
request = undefined;
headers = {};
lineByLine = true;
bodyToRead = -1;
body = undefined;
}
function finish() {
try {
var requestObject = new Request(request[0], request[1], request[2], headers, body, client);
var response = new Response(requestObject, client);
handleRequest(requestObject, response)
if (client.isConnected) {
reset();
}
} catch (error) {
response.reportError(error);
}
}
function handleLine(line, length) {
if (bodyToRead == -1) {
if (!request) {
request = line.split(' ');
return true;
} else if (line) {
var colon = line.indexOf(':');
var key = line.slice(0, colon).trim();
var value = line.slice(colon + 1).trim();
headers[key.toLowerCase()] = value;
return true;
} else {
if (headers["content-length"] != undefined) {
bodyToRead = parseInt(headers["content-length"]);
lineByLine = false;
body = "";
return true;
} else {
finish();
return false;
}
}
} else {
body += line;
bodyToRead -= length;
if (bodyToRead <= 0) {
finish();
}
}
}
client.onError(function(error) {
logError(client.peerName + " - - [" + new Date() + "] " + error);
});
client.read(function(data) {
if (data) {
inputBuffer += data;
var more = true;
while (more) {
if (lineByLine) {
more = false;
var end = inputBuffer.indexOf('\n');
var realEnd = end;
if (end > 0 && inputBuffer[end - 1] == '\r') {
--end;
}
if (end != -1) {
var line = inputBuffer.slice(0, end);
inputBuffer = inputBuffer.slice(realEnd + 1);
more = handleLine(line, realEnd + 1);
}
} else {
more = handleLine(inputBuffer, inputBuffer.length);
inputBuffer = "";
}
}
}
});
}
var kBacklog = 8;
var kHost = "0.0.0.0"
var kHttpPort = gGlobalSettings.httpPort || 12345;
var kHttpsPort = gGlobalSettings.httpsPort || 12346;
var socket = new Socket();
socket.bind(kHost, kHttpPort).then(function() {
var listenResult = socket.listen(kBacklog, function() {
socket.accept().then(handleConnection).catch(function(error) {
logError("[" + new Date() + "] " + error);
});
});
}).catch(function(error) {
logError("[" + new Date() + "] " + error);
});
var privateKey = File.readFile("data/httpd/privatekey.pem");
var certificate = File.readFile("data/httpd/certificate.pem");
if (privateKey && certificate) {
var tls = new TlsContext();
tls.setPrivateKey(privateKey);
tls.setCertificate(certificate);
var secureSocket = new Socket();
secureSocket.bind(kHost, kHttpsPort).then(function() {
secureSocket.listen(kBacklog, function() {
secureSocket.accept().then(function(client) {
handleConnection(client);
client.startTls(tls).catch(function(error) {
logError("[" + new Date() + "] [" + client.peerName + "] " + error);
});
}).catch(function(error) {
logError("[" + new Date() + "] " + error);
});
});
});
}
exports.all = all;

31
core/index.html Normal file
View File

@ -0,0 +1,31 @@
<html>
<head>
<title>Tilde Friends</title>
<link type="text/css" rel="stylesheet" href="/terminal/style.css"></link>
<link type="image/png" rel="shortcut icon" href="/terminal/favicon.png"></link>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="body">
<div class="navigation">
<span>~😎</span>
<span id="title">Tilde Friends</span>
<a href="/">home</a>
<a href="$(EDIT_SOURCE)">edit</a>
<a href="$(VIEW_SOURCE)">view source</a>
<a href="/~cory/about">about</a>
<span id="status"></span>
<span id="update">update available! <a href="">refresh</a> to update</span>
<span id="login"></span>
</div>
<div id="terminals" class="vbox"><div id="terminal_" class="terminal"></div></div>
<div class="input">
<span id="target"></span>
<span id="prompt">&gt;</span>
<input type='text' id='input'></input>
</div>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="/terminal/client.js"></script>
</div>
</body>
</html>

239
core/isaac.js Normal file
View File

@ -0,0 +1,239 @@
/* ----------------------------------------------------------------------
* Copyright (c) 2012 Yves-Marie K. Rinquin
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* ----------------------------------------------------------------------
*
* ISAAC is a cryptographically secure pseudo-random number generator
* (or CSPRNG for short) designed by Robert J. Jenkins Jr. in 1996 and
* based on RC4. It is designed for speed and security.
*
* ISAAC's informations & analysis:
* http://burtleburtle.net/bob/rand/isaac.html
* ISAAC's implementation details:
* http://burtleburtle.net/bob/rand/isaacafa.html
*
* ISAAC succesfully passed TestU01
*
* ----------------------------------------------------------------------
*
* Usage:
* <script src="isaac.js"></script>
* var random_number = isaac.random();
*
* Output: [ 0x00000000; 0xffffffff]
* [-2147483648; 2147483647]
*
*/
/* js string (ucs-2/utf16) to a 32-bit integer (utf-8 chars, little-endian) array */
String.prototype.toIntArray = function() {
var w1, w2, u, r4 = [], r = [], i = 0;
var s = this + '\0\0\0'; // pad string to avoid discarding last chars
var l = s.length - 1;
while(i < l) {
w1 = s.charCodeAt(i++);
w2 = s.charCodeAt(i+1);
if (w1 < 0x0080) {
// 0x0000 - 0x007f code point: basic ascii
r4.push(w1);
} else if(w1 < 0x0800) {
// 0x0080 - 0x07ff code point
r4.push(((w1 >>> 6) & 0x1f) | 0xc0);
r4.push(((w1 >>> 0) & 0x3f) | 0x80);
} else if((w1 & 0xf800) != 0xd800) {
// 0x0800 - 0xd7ff / 0xe000 - 0xffff code point
r4.push(((w1 >>> 12) & 0x0f) | 0xe0);
r4.push(((w1 >>> 6) & 0x3f) | 0x80);
r4.push(((w1 >>> 0) & 0x3f) | 0x80);
} else if(((w1 & 0xfc00) == 0xd800)
&& ((w2 & 0xfc00) == 0xdc00)) {
// 0xd800 - 0xdfff surrogate / 0x10ffff - 0x10000 code point
u = ((w2 & 0x3f) | ((w1 & 0x3f) << 10)) + 0x10000;
r4.push(((u >>> 18) & 0x07) | 0xf0);
r4.push(((u >>> 12) & 0x3f) | 0x80);
r4.push(((u >>> 6) & 0x3f) | 0x80);
r4.push(((u >>> 0) & 0x3f) | 0x80);
i++;
} else {
// invalid char
}
/* add integer (four utf-8 value) to array */
if(r4.length > 3) {
// little endian
r.push((r4.shift() << 0) | (r4.shift() << 8) |
(r4.shift() << 16) | (r4.shift() << 24));
}
}
return r;
}
/* isaac module pattern */
var isaac = (function(){
/* private: internal states */
var m = Array(256), // internal memory
acc = 0, // accumulator
brs = 0, // last result
cnt = 0, // counter
r = Array(256), // result array
gnt = 0; // generation counter
seed(Math.random() * 0xffffffff);
/* private: 32-bit integer safe adder */
function add(x, y) {
var lsb = (x & 0xffff) + (y & 0xffff);
var msb = (x >>> 16) + (y >>> 16) + (lsb >>> 16);
return (msb << 16) | (lsb & 0xffff);
}
/* public: initialisation */
function reset() {
acc = brs = cnt = 0;
for(var i = 0; i < 256; ++i)
m[i] = r[i] = 0;
gnt = 0;
}
/* public: seeding function */
function seed(s) {
var a, b, c, d, e, f, g, h, i;
/* seeding the seeds of love */
a = b = c = d =
e = f = g = h = 0x9e3779b9; /* the golden ratio */
if(s && typeof(s) === 'string')
s = s.toIntArray();
if(s && typeof(s) === 'number') {
s = [s];
}
if(s instanceof Array) {
reset();
for(i = 0; i < s.length; i++)
r[i & 0xff] += (typeof(s[i]) === 'number') ? s[i] : 0;
}
/* private: seed mixer */
function seed_mix() {
a ^= b << 11; d = add(d, a); b = add(b, c);
b ^= c >>> 2; e = add(e, b); c = add(c, d);
c ^= d << 8; f = add(f, c); d = add(d, e);
d ^= e >>> 16; g = add(g, d); e = add(e, f);
e ^= f << 10; h = add(h, e); f = add(f, g);
f ^= g >>> 4; a = add(a, f); g = add(g, h);
g ^= h << 8; b = add(b, g); h = add(h, a);
h ^= a >>> 9; c = add(c, h); a = add(a, b);
}
for(i = 0; i < 4; i++) /* scramble it */
seed_mix();
for(i = 0; i < 256; i += 8) {
if(s) { /* use all the information in the seed */
a = add(a, r[i + 0]); b = add(b, r[i + 1]);
c = add(c, r[i + 2]); d = add(d, r[i + 3]);
e = add(e, r[i + 4]); f = add(f, r[i + 5]);
g = add(g, r[i + 6]); h = add(h, r[i + 7]);
}
seed_mix();
/* fill in m[] with messy stuff */
m[i + 0] = a; m[i + 1] = b; m[i + 2] = c; m[i + 3] = d;
m[i + 4] = e; m[i + 5] = f; m[i + 6] = g; m[i + 7] = h;
}
if(s) {
/* do a second pass to make all of the seed affect all of m[] */
for(i = 0; i < 256; i += 8) {
a = add(a, m[i + 0]); b = add(b, m[i + 1]);
c = add(c, m[i + 2]); d = add(d, m[i + 3]);
e = add(e, m[i + 4]); f = add(f, m[i + 5]);
g = add(g, m[i + 6]); h = add(h, m[i + 7]);
seed_mix();
/* fill in m[] with messy stuff (again) */
m[i + 0] = a; m[i + 1] = b; m[i + 2] = c; m[i + 3] = d;
m[i + 4] = e; m[i + 5] = f; m[i + 6] = g; m[i + 7] = h;
}
}
prng(); /* fill in the first set of results */
gnt = 256; /* prepare to use the first set of results */;
}
/* public: isaac generator, n = number of run */
function prng(n){
var i, x, y;
n = (n && typeof(n) === 'number')
? Math.abs(Math.floor(n)) : 1;
while(n--) {
cnt = add(cnt, 1);
brs = add(brs, cnt);
for(i = 0; i < 256; i++) {
switch(i & 3) {
case 0: acc ^= acc << 13; break;
case 1: acc ^= acc >>> 6; break;
case 2: acc ^= acc << 2; break;
case 3: acc ^= acc >>> 16; break;
}
acc = add(m[(i + 128) & 0xff], acc); x = m[i];
m[i] = y = add(m[(x >>> 2) & 0xff], add(acc, brs));
r[i] = brs = add(m[(y >>> 10) & 0xff], x);
}
}
}
/* public: return a random number between */
function rand() {
if(!gnt--) {
prng(); gnt = 255;
}
return r[gnt];
}
/* public: return internals in an object*/
function internals(){
return {a: acc, b: brs, c: cnt, m: m, r: r};
}
/* return class object */
return {
'reset': reset,
'seed': seed,
'prng': prng,
'rand': rand,
'internals': internals
};
})(); /* declare and execute */
/* public: output*/
isaac.random = function() {
return 0.5 + this.rand() * 2.3283064365386963e-10; // 2^-32
}
exports.rand = isaac.rand;

102
core/network.js Normal file
View File

@ -0,0 +1,102 @@
"use strict";
function Connection() {
this.socket = null;
this.buffer = null;
this.onReadCallback = null;
this.onErrorCallback = null;
this.tlsContext = null;
this._exported = null;
return this;
}
Connection.prototype.connect = function(host, port) {
let connection = this;
connection.close();
connection.socket = new Socket();
return connection.socket.connect(host, port).then(function() {
connection.buffer = "";
return Promise.all([
connection.socket.onError(function(error) {
if (connection.onErrorCallback) {
connection.onErrorCallback(error);
}
connection.close();
}),
connection.socket.read(function(data) {
if (connection.onReadCallback) {
connection.onReadCallback(data);
} else {
connection.buffer += data;
}
}),
]);
});
};
Connection.prototype.isConnected = function() {
return this.socket && this.socket.isConnected;
};
Connection.prototype.read = function(callback) {
this.onReadCallback = callback;
if (this.buffer) {
callback(this.buffer);
}
this.buffer = "";
};
Connection.prototype.onError = function(callback) {
this.onErrorCallback = callback;
};
Connection.prototype.write = function(data) {
return this.socket.write(data);
};
Connection.prototype.close = function() {
let socket = this.socket;
this.socket = null;
if (socket) {
return socket.close();
}
};
Connection.prototype.startTls = function() {
return this.socket.startTls(this.tlsContext);
};
Connection.prototype.getPeerCertificate = function() {
return this.socket.peerCertificate;
};
Connection.prototype.addTrustedCertificate = function(certificate) {
if (!this.tlsContext) {
this.tlsContext = new TlsContext();
}
return this.tlsContext.addTrustedCertificate(certificate);
};
Connection.prototype.exported = function() {
if (!this._exported) {
this._exported = {
isConnected: this.isConnected.bind(this),
connect: this.connect.bind(this),
startTls: this.startTls.bind(this),
write: this.write.bind(this),
read: this.read.bind(this),
onError: this.onError.bind(this),
close: this.close.bind(this),
getPeerCertificate: this.getPeerCertificate.bind(this),
addTrustedCertificate: this.addTrustedCertificate.bind(this),
};
}
return this._exported;
};
function newConnection() {
let process = this;
let connection = new Connection();
process.connections.push(connection);
return connection.exported();
}

181
core/style.css Normal file
View File

@ -0,0 +1,181 @@
body {
font-family: monospace;
background-color: #002b36;
color: #eee8d5;
}
#body {
display: flex;
flex-flow: column;
width: 100%;
height: 100%;
}
.navigation {
height: auto;
width: 100%;
}
#terminals {
flex: 1;
flex-flow: column;
}
#logo {
vertical-align: middle;
}
.terminal {
outline: none;
white-space: pre-wrap;
resize: none;
overflow: auto;
height: auto;
width: auto;
}
.hbox {
display: flex;
flex-direction: row;
}
.vbox {
display: flex;
flex-direction: column;
}
.terminal > img {
vertical-align: middle;
}
a:link, .command {
color: #268bd2;
cursor: pointer;
}
a:visited, .command:visited {
color: #6c71c4;
cursor: pointer;
}
a:hover, .command:hover {
color: #2aa198;
cursor: pointer;
}
a:active, .command:active {
color: #dc322f;
cursor: pointer;
}
.input {
display: flex;
flex-flow: row;
}
#prompt {
padding-right: 0.5em;
color: #eee8d5;
}
#input {
flex: 1;
border: 0;
outline: none;
font-family: monospace;
background-color: #002b36;
color: #eee8d5;
}
#input.drop {
border: 2px solid;
color: #cb4b16;
}
.CodeMirror {
height: 100%;
padding: 0;
}
.CodeMirror-scroll {
height: 100%;
padding: 0;
}
.cm-tab {
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAMCAYAAAAkuj5RAAAAAXNSR0IArs4c6QAAAGFJREFUSMft1LsRQFAQheHPowAKoACx3IgEKtaEHujDjORSgWTH/ZOdnZOcM/sgk/kFFWY0qV8foQwS4MKBCS3qR6ixBJvElOobYAtivseIE120FaowJPN75GMu8j/LfMwNjh4HUpwg4LUAAAAASUVORK5CYII=);
background-position: right;
background-repeat: no-repeat;
-webkit-filter: invert(100%);
filter: invert(100%);
}
.cm-trailingspace {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAACCAYAAAB/qH1jAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QUXCToH00Y1UgAAACFJREFUCNdjPMDBUc/AwNDAAAFMTAwMDA0OP34wQgX/AQBYgwYEx4f9lQAAAABJRU5ErkJggg==);
background-position: bottom left;
background-repeat: repeat-x;
}
#status {
display: none;
}
#update {
display: none;
}
#login {
float: right;
}
#auth_greeting {
text-align: center;
}
#auth {
display: flex;
flex-flow: row;
align-content: center;
align-items: center;
text-align: center;
justify-content: center;
}
#auth_login {
flex: 0 1 auto;
text-align: right;
}
#auth_or {
flex: 0 1 auto;
padding: 1em;
}
#auth_guest {
flex: 0 1 auto;
}
.notice {
color: #cb4b16;
margin: 1em;
padding: 1em;
border: 1px solid #cb4b16;
}
/* Solarized Color Scheme Colors */
.base03 { color: #002b36; }
.base02 { color: #073642; }
.base01 { color: #586e75; }
.base00 { color: #657b83; }
.base0 { color: #839496; }
.base1 { color: #93a1a1; }
.base2 { color: #eee8d5; }
.base3 { color: #fdf6e3; }
.yellow { color: #b58900; }
.orange { color: #cb4b16; }
.red { color: #dc322f; }
.magenta { color: #d33682; }
.violet { color: #6c71c4; }
.blue { color: #268bd2; }
.cyan { color: #2aa198; }
.green { color: #859900; }

290
core/terminal.js Normal file
View File

@ -0,0 +1,290 @@
"use strict";
var kStaticFiles = [
{uri: '', path: 'index.html', type: 'text/html; charset=utf-8'},
{uri: '/edit', path: 'edit.html', type: 'text/html; charset=utf-8'},
{uri: '/style.css', path: 'style.css', type: 'text/css; charset=utf-8'},
{uri: '/favicon.png', path: 'favicon.png', type: 'image/png'},
{uri: '/client.js', path: 'client.js', type: 'text/javascript; charset=utf-8'},
{uri: '/editor.js', path: 'editor.js', type: 'text/javascript; charset=utf-8'},
{uri: '/agplv3-88x31.png', path: 'agplv3-88x31.png', type: 'image/png'},
];
var auth = require('auth');
var form = require('form');
function Terminal() {
this._waiting = [];
this._index = 0;
this._firstLine = 0;
this._lines = [];
this._lastRead = null;
this._lastWrite = null;
this._echo = true;
this._readLine = null;
this._selected = null;
return this;
}
Terminal.kBacklog = 64;
Terminal.prototype.dispatch = function(data) {
for (var i in this._waiting) {
this._waiting[i](data);
}
this._waiting.length = 0;
}
Terminal.prototype.print = function() {
var data = arguments;
if (this._selected) {
data = {
terminal: this._selected,
value: data
};
}
this._lines.push(data);
this._index++;
if (this._lines.length >= Terminal.kBacklog * 2) {
this._firstLine = this._index - Terminal.kBacklog;
this._lines = this._lines.slice(this._lines.length - Terminal.kBacklog);
}
this.dispatch({index: this._index - 1, lines: [data]});
this._lastWrite = new Date();
}
Terminal.prototype.notify = function(title, options) {
this.print({action: "notify", title: title, options: options});
}
Terminal.prototype.setTitle = function(value) {
this.print({action: "title", value: value});
}
Terminal.prototype.setPrompt = function(value) {
this.print({action: "prompt", value: value});
}
Terminal.prototype.setPassword = function(value) {
this.print({action: "password", value: value});
}
Terminal.prototype.setHash = function(value) {
this.print({action: "hash", value: value});
}
Terminal.prototype.notifyUpdate = function() {
this.print({action: "update"});
}
Terminal.prototype.split = function(options) {
this.print({action: "split", options: options});
}
Terminal.prototype.select = function(name) {
this._selected = name;
}
Terminal.prototype.postMessageToIframe = function(name, message) {
this.print({action: "postMessageToIframe", name: name, message: message});
}
Terminal.prototype.clear = function() {
//this._lines.length = 0;
//this._firstLine = this._index;
this.print({action: "clear"});
}
Terminal.prototype.ping = function() {
this.dispatch({index: this._index - 1, lines: [{action: "ping"}]});
}
Terminal.prototype.getOutput = function(haveIndex) {
var terminal = this;
terminal._lastRead = new Date();
return new Promise(function(resolve) {
if (haveIndex < terminal._index - 1) {
resolve({index: terminal._index - 1, lines: terminal._lines.slice(Math.max(0, haveIndex + 1 - terminal._firstLine))});
} else {
terminal._waiting.push(resolve);
}
});
}
Terminal.prototype.setEcho = function(echo) {
this._echo = echo;
}
Terminal.prototype.readLine = function() {
var self = this;
if (self._readLine) {
self._readLine[1]();
}
return new Promise(function(resolve, reject) {
self._readLine = [resolve, reject];
});
}
function invoke(handlers, argv) {
var promises = [];
if (handlers) {
for (var i = 0; i < handlers.length; ++i) {
promises.push(handlers[i].apply({}, argv));
}
}
return Promise.all(promises);
}
function handler(request, response, packageOwner, packageName, uri) {
var found = false;
if (badName(packageOwner) || badName(packageName)) {
var data = "File not found";
response.writeHead(404, {"Content-Type": "text/plain; charset=utf-8", "Content-Length": data.length});
response.end(data);
found = true;
}
if (!found) {
for (var i in kStaticFiles) {
if (uri === kStaticFiles[i].uri) {
found = true;
var data = File.readFile("core/" + kStaticFiles[i].path);
if (kStaticFiles[i].uri == "") {
data = data.replace("$(VIEW_SOURCE)", "/~" + packageOwner + "/" + packageName + "/view");
data = data.replace("$(EDIT_SOURCE)", "/~" + packageOwner + "/" + packageName + "/edit");
} else if (kStaticFiles[i].uri == "/edit") {
var source = File.readFile("packages/" + packageOwner + "/" + packageName + "/" + packageName + ".js") || "";
source = source.replace(/([&<>"])/g, function(x, item) {
return {'&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;'}[item];
});
data = data.replace("$(SOURCE)", source);
}
response.writeHead(200, {"Content-Type": kStaticFiles[i].type, "Content-Length": data.length});
response.end(data);
break;
}
}
}
if (!found) {
var process;
if (uri === "/view") {
var data = File.readFile("packages/" + packageOwner + "/" + packageName + "/" + packageName + ".js");
response.writeHead(200, {"Content-Type": "text/javascript; charset=utf-8", "Content-Length": data.length});
response.end(data);
} else if (uri == "/save") {
var credentials = auth.query(request.headers);
var userName = credentials && credentials.session && credentials.session.name ? credentials.session.name : "guest";
if (badName(packageName)) {
response.writeHead(403, {"Content-Type": "text/plain; charset=utf-8"});
response.end("Invalid package name: " + packageName);
} else if (badName(userName)) {
response.writeHead(403, {"Content-Type": "text/plain; charset=utf-8"});
response.end("Invalid user name: " + userName);
} else {
File.makeDirectory("packages/" + userName);
File.makeDirectory("packages/" + userName + "/" + packageName);
if (!File.writeFile("packages/" + userName + "/" + packageName + "/" + packageName + ".js", request.body || "")) {
response.writeHead(200, {"Content-Type": "text/plain; charset=utf-8"});
response.end("/~" + userName + "/" + packageName);
updateProcesses(userName, packageName);
} else {
response.writeHead(500, {"Content-Type": "text/plain; charset=utf-8"});
response.end("Problem saving: " + packageName);
}
}
} else {
var options = {};
var credentials = auth.query(request.headers);
if (credentials && credentials.session) {
options.userName = credentials.session.name;
}
options.credentials = credentials;
var sessionId = form.decodeForm(request.query).sessionId;
var isNewSession = false;
if (!getSessionProcess(packageOwner, packageName, sessionId, {create: false})) {
sessionId = makeSessionId();
isNewSession = true;
}
process = getSessionProcess(packageOwner, packageName, sessionId, options);
process.lastActive = Date.now();
if (uri === "/send") {
if (isNewSession) {
response.writeHead(403, {"Content-Type": "text/plain; charset=utf-8"});
response.end("Too soon.");
} else {
var command = JSON.parse(request.body);
var eventName = 'unknown';
if (typeof command == "string") {
if (process.terminal._echo) {
process.terminal.print("> " + command);
}
if (process.terminal._readLine) {
let promise = process.terminal._readLine;
process.terminal._readLine = null;
promise[0](command);
}
eventName = 'onInput';
} else if (command.event) {
eventName = command.event;
}
return invoke(process.eventHandlers[eventName], [command]).then(function() {
response.writeHead(200, {
"Content-Type": "text/plain; charset=utf-8",
"Content-Length": "0",
"Cache-Control": "no-cache, no-store, must-revalidate",
"Pragma": "no-cache",
"Expires": "0",
});
response.end("");
}).catch(function(error) {
process.terminal.print(error);
});
}
} else if (uri === "/receive") {
if (isNewSession) {
var data = JSON.stringify({
lines: [
{
action: "session",
session: {
sessionId: sessionId,
credentials: credentials,
}
},
]
});
response.writeHead(200, {
"Content-Type": "text/plain; charset=utf-8",
"Content-Length": data.length.toString(),
"Cache-Control": "no-cache, no-store, must-revalidate",
"Pragma": "no-cache",
"Expires": "0",
});
process.ready.then(function() {
process.terminal.print({action: "ready", ready: true});
}).catch(function(error) {
process.terminal.print({action: "ready", error: error});
});
response.end(data);
} else {
return process.terminal.getOutput(parseInt(request.body)).then(function(output) {
var data = JSON.stringify(output);
response.writeHead(200, {
"Content-Type": "text/plain; charset=utf-8",
"Content-Length": data.length.toString(),
"Cache-Control": "no-cache, no-store, must-revalidate",
"Pragma": "no-cache",
"Expires": "0",
});
response.end(data);
});
}
}
}
}
}
exports.handler = handler;

62
data/wiki/development Normal file
View File

@ -0,0 +1,62 @@
= SandboxOS App Development Guide =
This is a brief introduction on developing SandboxOS apps targeted at people who are already familiar with web development.
== Packages ==
A package is a directory of files. '''package.json''' is the only file with special meaning.
Here is an example package.json:
{{{
#!json
{
"name": "chat",
"start": "backend.js",
"imports": ["auth", "httpd", "filesystem"],
"href": "/chat",
"description": "A basic multi-user chat example."
}
}}}
* '''name''': identifies the package. If it is not unique, any existing installed package of the same name will be replaced when installing the package.
* '''start''': specifies the JavaScript file which is the entry point of the task. When a new process is started for this package, this script is executed within it.
* '''imports''': list of package/task names which this package wants to be able to access.
* '''href''': link to the task's entry page used by [/tasks /tasks].
* '''description''': human-readable description of the package, displayed by [/tasks /tasks].
== Promises ==
JavaScript promises are used heavily. Invoking any method on another task will return a Promise object. Execution will return immediately but go asynchronous. That usually looks like this:
{{{
#!javascript
imports.email.sendMessage(message).then(function(result) {
// When sendMessage completes, result is the return value.
}).catch(function(error) {
// If sendMessage fails (or calling it somehow fails), error is the reason.
});
// sendMessage returns immediately and execution continues on.
}}}
This is a completely inadequate explanation of the nuances involved, but it's a starting point. Promises can be created and chained and combined in interesting ways.
== Inter-Task Communication ==
Tasks have access to the exported functions on any task declared in their package imports.
In addition, functions passed between tasks can be called by the receiving task or passed along further.
Here is an untested, made-up example with two hypothetical tasks, '''math''' and '''test''':
'''math.js''':
{{{
#!javascript
exports = {
sum: function(a, b) { return a + b; },
multiply: function(a, b) { return a * b; },
};
}}}
'''test.js''':
{{{
#!javascript
imports.math.sum(4, 5).then(function(result) {
// result === 9
});
}}}

65
data/wiki/index Normal file
View File

@ -0,0 +1,65 @@
= SandboxOS =
I embedded a JavaScript engine in a C++ application and used it to make some webapps. I made a wiki with it. That is what you are looking at. It's not especially good, but the interesting part is that you, as a visitor to this web site, have the power to rewrite the wiki webapp itself into something better.
== Goals ==
I've tried writing lofty descriptions about why I think this is cool, but I'm bad at that part.
Goals include:
=== 1. Make it easy to run servers. ===
* SandboxOS can be made to run on lots of platforms.
* SandboxOS can be made trivial to install. I want to put it in app stores.
* SandboxOS is an app store in itself, so think "installing blogging software == installing a mobile game". And then think of a webapp that is 10x better than that.
=== 2. Make a thing that is by default pretty secure. ===
* Actual access to most system resources (filesystem + network, currently) is restricted to a few apps that hand it out in very limited ways.
* Apps will only get access to resources when granted by the user. Think iOS or Android.
* The idea is that it can be made as secure as Google Chrome. It currently uses V8 and process isolation, but there's a lot more to do. In the end I want to trust installing random apps as much as or more than I trust visiting shady web sites.
* But security is nothing if you can't do cool stuff. I want to make weird social music players and things to manipulate photos on my phone from my desktop.
=== 3. Free software idealism ===
* This is Wikipedia but for apps?
* Make distributed versions of things that Google/Apple/Facebook dominate?
* Something about software architecture and making small tools that fit together to do neat things.
=== 4. Fun ===
* I get a kick out of making all of this stuff from scratch. The stack is getting pretty high, and it's just getting started.
* This hopefully lowers the barrier to entry to making little webapps, since you can use my server and make something with ~2 files that you edited like something on Google Docs.
== How to Get Started ==
{{{
#!html
<ol>
<li>Visit the <a href="/tasks">/tasks</a> page.</li>
<li>Pick a task (hint: consider <b>helloworld</b>, <b>wiki</b>, or <b>chat</b>). Click edit. You will probably have to log in at this point.</li>
<li>Make modifications.</li>
<li>Click install.</li>
<li>Visit your updated task's URL and see it updated.</li>
<li>Ask questions. Either stick them here on the wiki somewhere, or email <a href="mailto:sandbox@unprompted.com">Cory</a>.</li>
</ol>
}}}
It should be difficult to do anything too disruptive, and there are backups if you do. '''Don't worry about breaking things.'''
It's easy to make things fail silently. I'm starting to improve that. '''Use the log task.'''
There are probably ways to do bad things if you try hard. '''Please don't be mean.'''
== TODO ==
In no particular order:
* Set limits for everything. n anonymous users can each make m tasks with p MB of storage and can make q HTTP request per second.
* Make some sort of TODO / bug tracker to replace this task list.
* Establish some conventions for non-webapp tasks. Maybe make a shell that lets you run code from any task that exposes it.
* Establish some conventions for HTML fragments. Include a persistent HTML header in every page or something like that.
* Make an app store. Not too important until we have multiple installs but pretty important.
* Lots of the API exposed from C++ isn't async but should be.
* Pick a name for this thing.
* ~~Set up an [https://www.unprompted.com/projects/build/sandboxos automated build].~~
* Feedback is really bad or missing. If you break a task, it might just stop responding to web requests. I have the benefit of being able to see console output, but that's really noisy and bad. There might be times where it is necessary to restart the whole process. Ultimately there should be a way to see feedback when you've broken something, and things should be hardened so that you can't take down the whole system without abusing administrative rights.
* Security here is not good at the moment. I'm essentially trusting you to please don't do bad things. I've taken some steps to harden this thing, but it has a long way to go.
* ~~Inter-task messaging is really awkward to type. And the way you need to respond to httpd requests is even weirder. I will work on this. It should be possible to get most things close to being first-class function calls, except asynchronous.~~
* ~~Make this wiki actually use some sort of wiki syntax. HTML is too 90s.~~
* ~~The C++ program needs to use separate processes for each task in order to prevent OOM situations in one task from taking down the whole process.~~
* ~~The C++ program needs to build and run on Windows.~~ It needs to do so as transparently in the background as possible while still being trivial to acquire and start (Windows service / system tray icon).
* ~~Need to implement a real security model. I was thinking once this has an authentication task, everything can use that to enforce that nobody but administrators changed the core tasks and that anonymous and untrusted users don't do anything too malicious.~~
* ~~Be able to marshal functions across task boundaries so that the httpd task can return a request object that has the same API as node.js. I think this will greatly simplify the client code for webapps.~~
* ~~Need to implement something like proper javascript requires() and package dependencies for code sharing.~~

23
deps/liblmdb/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
mtest
mtest[23456]
testdb
mdb_copy
mdb_stat
mdb_dump
mdb_load
*.lo
*.[ao]
*.so
*.exe
*[~#]
*.bak
*.orig
*.rej
*.gcov
*.gcda
*.gcno
core
core.*
valgrind.*
man/
html/

182
deps/liblmdb/CHANGES vendored Normal file
View File

@ -0,0 +1,182 @@
LMDB 0.9 Change Log
LMDB 0.9.17 Release (2015/11/30)
Fix ITS#7377 catch calloc failure
Fix ITS#8237 regression from ITS#7589
Fix ITS#8238 page_split for DUPFIXED pages
Fix ITS#8221 MDB_PAGE_FULL on delete/rebalance
Fix ITS#8258 rebalance/split assert
Fix ITS#8263 cursor_put cursor tracking
Fix ITS#8264 cursor_del cursor tracking
Fix ITS#8310 cursor_del cursor tracking
Fix ITS#8299 mdb_del cursor tracking
Fix ITS#8300 mdb_del cursor tracking
Fix ITS#8304 mdb_del cursor tracking
Fix ITS#7771 fakepage cursor tracking
Fix ITS#7789 ensure mapsize >= pages in use
Fix ITS#7971 mdb_txn_renew0() new reader slots
Fix ITS#7969 use __sync_synchronize on non-x86
Fix ITS#8311 page_split from update_key
Fix ITS#8312 loose pages in nested txn
Fix ITS#8313 mdb_rebalance dummy cursor
Fix ITS#8315 dirty_room in nested txn
Fix ITS#8323 dirty_list in nested txn
Fix ITS#8316 page_merge cursor tracking
Fix ITS#8321 cursor tracking
Fix ITS#8319 mdb_load error messages
Fix ITS#8320 mdb_load plaintext input
Added mdb_txn_id() (ITS#7994)
Added robust mutex support
Miscellaneous cleanup/simplification
Build
Create install dirs if needed (ITS#8256)
Fix ThreadProc decl on Win32/MSVC (ITS#8270)
Added ssize_t typedef for MSVC (ITS#8067)
Use ANSI apis on Windows (ITS#8069)
Use O_SYNC if O_DSYNC,MDB_DSYNC are not defined (ITS#7209)
Allow passing AR to make (ITS#8168)
Allow passing mandir to make install (ITS#8169)
LMDB 0.9.16 Release (2015/08/14)
Fix cursor EOF bug (ITS#8190)
Fix handling of subDB records (ITS#8181)
Fix mdb_midl_shrink() usage (ITS#8200)
LMDB 0.9.15 Release (2015/06/19)
Fix txn init (ITS#7961,#7987)
Fix MDB_PREV_DUP (ITS#7955,#7671)
Fix compact of empty env (ITS#7956)
Fix mdb_copy file mode
Fix mdb_env_close() after failed mdb_env_open()
Fix mdb_rebalance collapsing root (ITS#8062)
Fix mdb_load with large values (ITS#8066)
Fix to retry writes on EINTR (ITS#8106)
Fix mdb_cursor_del on empty DB (ITS#8109)
Fix MDB_INTEGERDUP key compare (ITS#8117)
Fix error handling (ITS#7959,#8157,etc.)
Fix race conditions (ITS#7969,7970)
Added workaround for fdatasync bug in ext3fs
Build
Don't use -fPIC for static lib
Update .gitignore (ITS#7952,#7953)
Cleanup for "make test" (ITS#7841), "make clean", mtest*.c
Misc. Android/Windows cleanup
Documentation
Fix MDB_APPEND doc
Fix MDB_MAXKEYSIZE doc (ITS#8156)
Fix mdb_cursor_put,mdb_cursor_del EACCES description
Fix mdb_env_sync(MDB_RDONLY env) doc (ITS#8021)
Clarify MDB_WRITEMAP doc (ITS#8021)
Clarify mdb_env_open doc
Clarify mdb_dbi_open doc
LMDB 0.9.14 Release (2014/09/20)
Fix to support 64K page size (ITS#7713)
Fix to persist decreased as well as increased mapsizes (ITS#7789)
Fix cursor bug when deleting last node of a DUPSORT key
Fix mdb_env_info to return FIXEDMAP address
Fix ambiguous error code from writing to closed DBI (ITS#7825)
Fix mdb_copy copying past end of file (ITS#7886)
Fix cursor bugs from page_merge/rebalance
Fix to dirty fewer pages in deletes (mdb_page_loose())
Fix mdb_dbi_open creating subDBs (ITS#7917)
Fix mdb_cursor_get(_DUP) with single value (ITS#7913)
Fix Windows compat issues in mtests (ITS#7879)
Add compacting variant of mdb_copy
Add BigEndian integer key compare code
Add mdb_dump/mdb_load utilities
LMDB 0.9.13 Release (2014/06/18)
Fix mdb_page_alloc unlimited overflow page search
Documentation
Re-fix MDB_CURRENT doc (ITS#7793)
Fix MDB_GET_MULTIPLE/MDB_NEXT_MULTIPLE doc
LMDB 0.9.12 Release (2014/06/13)
Fix MDB_GET_BOTH regression (ITS#7875,#7681)
Fix MDB_MULTIPLE writing multiple keys (ITS#7834)
Fix mdb_rebalance (ITS#7829)
Fix mdb_page_split (ITS#7815)
Fix md_entries count (ITS#7861,#7828,#7793)
Fix MDB_CURRENT (ITS#7793)
Fix possible crash on Windows DLL detach
Misc code cleanup
Documentation
mdb_cursor_put: cursor moves on error (ITS#7771)
LMDB 0.9.11 Release (2014/01/15)
Add mdb_env_set_assert() (ITS#7775)
Fix: invalidate txn on page allocation errors (ITS#7377)
Fix xcursor tracking in mdb_cursor_del0() (ITS#7771)
Fix corruption from deletes (ITS#7756)
Fix Windows/MSVC build issues
Raise safe limit of max MDB_MAXKEYSIZE
Misc code cleanup
Documentation
Remove spurious note about non-overlapping flags (ITS#7665)
LMDB 0.9.10 Release (2013/11/12)
Add MDB_NOMEMINIT option
Fix mdb_page_split() again (ITS#7589)
Fix MDB_NORDAHEAD definition (ITS#7734)
Fix mdb_cursor_del() positioning (ITS#7733)
Partial fix for larger page sizes (ITS#7713)
Fix Windows64/MSVC build issues
LMDB 0.9.9 Release (2013/10/24)
Add mdb_env_get_fd()
Add MDB_NORDAHEAD option
Add MDB_NOLOCK option
Avoid wasting space in mdb_page_split() (ITS#7589)
Fix mdb_page_merge() cursor fixup (ITS#7722)
Fix mdb_cursor_del() on last delete (ITS#7718)
Fix adding WRITEMAP on existing env (ITS#7715)
Fix nested txns (ITS#7515)
Fix mdb_env_copy() O_DIRECT bug (ITS#7682)
Fix mdb_cursor_set(SET_RANGE) return code (ITS#7681)
Fix mdb_rebalance() cursor fixup (ITS#7701)
Misc code cleanup
Documentation
Note that by default, readers need write access
LMDB 0.9.8 Release (2013/09/09)
Allow mdb_env_set_mapsize() on an open environment
Fix mdb_dbi_flags() (ITS#7672)
Fix mdb_page_unspill() in nested txns
Fix mdb_cursor_get(CURRENT|NEXT) after a delete
Fix mdb_cursor_get(DUP) to always return key (ITS#7671)
Fix mdb_cursor_del() to always advance to next item (ITS#7670)
Fix mdb_cursor_set(SET_RANGE) for tree with single page (ITS#7681)
Fix mdb_env_copy() retry open if O_DIRECT fails (ITS#7682)
Tweak mdb_page_spill() to be less aggressive
Documentation
Update caveats since mdb_reader_check() added in 0.9.7
LMDB 0.9.7 Release (2013/08/17)
Don't leave stale lockfile on failed RDONLY open (ITS#7664)
Fix mdb_page_split() ref beyond cursor depth
Fix read txn data race (ITS#7635)
Fix mdb_rebalance (ITS#7536, #7538)
Fix mdb_drop() (ITS#7561)
Misc DEBUG macro fixes
Add MDB_NOTLS envflag
Add mdb_env_copyfd()
Add mdb_txn_env() (ITS#7660)
Add mdb_dbi_flags() (ITS#7661)
Add mdb_env_get_maxkeysize()
Add mdb_env_reader_list()/mdb_env_reader_check()
Add mdb_page_spill/unspill, remove hard txn size limit
Use shorter names for semaphores (ITS#7615)
Build
Fix install target (ITS#7656)
Documentation
Misc updates for cursors, DB handles, data lifetime
LMDB 0.9.6 Release (2013/02/25)
Many fixes/enhancements
LMDB 0.9.5 Release (2012/11/30)
Renamed from libmdb to liblmdb
Many fixes/enhancements

20
deps/liblmdb/COPYRIGHT vendored Normal file
View File

@ -0,0 +1,20 @@
Copyright 2011-2015 Howard Chu, Symas Corp.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted only as authorized by the OpenLDAP
Public License.
A copy of this license is available in the file LICENSE in the
top-level directory of the distribution or, alternatively, at
<http://www.OpenLDAP.org/license.html>.
OpenLDAP is a registered trademark of the OpenLDAP Foundation.
Individual files and/or contributed packages may be copyright by
other parties and/or subject to additional restrictions.
This work also contains materials derived from public sources.
Additional information about OpenLDAP can be obtained at
<http://www.openldap.org/>.

1631
deps/liblmdb/Doxyfile vendored Normal file

File diff suppressed because it is too large Load Diff

47
deps/liblmdb/LICENSE vendored Normal file
View File

@ -0,0 +1,47 @@
The OpenLDAP Public License
Version 2.8, 17 August 2003
Redistribution and use of this software and associated documentation
("Software"), with or without modification, are permitted provided
that the following conditions are met:
1. Redistributions in source form must retain copyright statements
and notices,
2. Redistributions in binary form must reproduce applicable copyright
statements and notices, this list of conditions, and the following
disclaimer in the documentation and/or other materials provided
with the distribution, and
3. Redistributions must contain a verbatim copy of this document.
The OpenLDAP Foundation may revise this license from time to time.
Each revision is distinguished by a version number. You may use
this Software under terms of this license revision or under the
terms of any subsequent revision of the license.
THIS SOFTWARE IS PROVIDED BY THE OPENLDAP FOUNDATION AND ITS
CONTRIBUTORS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE OPENLDAP FOUNDATION, ITS CONTRIBUTORS, OR THE AUTHOR(S)
OR OWNER(S) OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
The names of the authors and copyright holders must not be used in
advertising or otherwise to promote the sale, use or other dealing
in this Software without specific, written prior permission. Title
to copyright in this Software shall at all times remain with copyright
holders.
OpenLDAP is a registered trademark of the OpenLDAP Foundation.
Copyright 1999-2003 The OpenLDAP Foundation, Redwood City,
California, USA. All Rights Reserved. Permission to copy and
distribute verbatim copies of this document is granted.

111
deps/liblmdb/Makefile vendored Normal file
View File

@ -0,0 +1,111 @@
# Makefile for liblmdb (Lightning memory-mapped database library).
########################################################################
# Configuration. The compiler options must enable threaded compilation.
#
# Preprocessor macros (for CPPFLAGS) of interest...
# Note that the defaults should already be correct for most
# platforms; you should not need to change any of these.
# Read their descriptions in mdb.c if you do:
#
# - MDB_USE_POSIX_SEM
# - MDB_DSYNC
# - MDB_FDATASYNC
# - MDB_FDATASYNC_WORKS
# - MDB_USE_PWRITEV
# - MDB_USE_ROBUST
#
# There may be other macros in mdb.c of interest. You should
# read mdb.c before changing any of them.
#
CC = gcc
AR = ar
W = -W -Wall -Wno-unused-parameter -Wbad-function-cast -Wuninitialized
THREADS = -pthread
OPT = -O2 -g
CFLAGS = $(THREADS) $(OPT) $(W) $(XCFLAGS)
LDLIBS =
SOLIBS =
prefix = /usr/local
mandir = $(prefix)/man
########################################################################
IHDRS = lmdb.h
ILIBS = liblmdb.a liblmdb.so
IPROGS = mdb_stat mdb_copy mdb_dump mdb_load
IDOCS = mdb_stat.1 mdb_copy.1 mdb_dump.1 mdb_load.1
PROGS = $(IPROGS) mtest mtest2 mtest3 mtest4 mtest5
all: $(ILIBS) $(PROGS)
install: $(ILIBS) $(IPROGS) $(IHDRS)
mkdir -p $(DESTDIR)$(prefix)/bin
mkdir -p $(DESTDIR)$(prefix)/lib
mkdir -p $(DESTDIR)$(prefix)/include
mkdir -p $(DESTDIR)$(prefix)/man/man1
for f in $(IPROGS); do cp $$f $(DESTDIR)$(prefix)/bin; done
for f in $(ILIBS); do cp $$f $(DESTDIR)$(prefix)/lib; done
for f in $(IHDRS); do cp $$f $(DESTDIR)$(prefix)/include; done
for f in $(IDOCS); do cp $$f $(DESTDIR)$(mandir)/man1; done
clean:
rm -rf $(PROGS) *.[ao] *.[ls]o *~ testdb
test: all
rm -rf testdb && mkdir testdb
./mtest && ./mdb_stat testdb
liblmdb.a: mdb.o midl.o
$(AR) rs $@ mdb.o midl.o
liblmdb.so: mdb.lo midl.lo
# $(CC) $(LDFLAGS) -pthread -shared -Wl,-Bsymbolic -o $@ mdb.o midl.o $(SOLIBS)
$(CC) $(LDFLAGS) -pthread -shared -o $@ mdb.lo midl.lo $(SOLIBS)
mdb_stat: mdb_stat.o liblmdb.a
mdb_copy: mdb_copy.o liblmdb.a
mdb_dump: mdb_dump.o liblmdb.a
mdb_load: mdb_load.o liblmdb.a
mtest: mtest.o liblmdb.a
mtest2: mtest2.o liblmdb.a
mtest3: mtest3.o liblmdb.a
mtest4: mtest4.o liblmdb.a
mtest5: mtest5.o liblmdb.a
mtest6: mtest6.o liblmdb.a
mdb.o: mdb.c lmdb.h midl.h
$(CC) $(CFLAGS) $(CPPFLAGS) -c mdb.c
midl.o: midl.c midl.h
$(CC) $(CFLAGS) $(CPPFLAGS) -c midl.c
mdb.lo: mdb.c lmdb.h midl.h
$(CC) $(CFLAGS) -fPIC $(CPPFLAGS) -c mdb.c -o $@
midl.lo: midl.c midl.h
$(CC) $(CFLAGS) -fPIC $(CPPFLAGS) -c midl.c -o $@
%: %.o
$(CC) $(CFLAGS) $(LDFLAGS) $^ $(LDLIBS) -o $@
%.o: %.c lmdb.h
$(CC) $(CFLAGS) $(CPPFLAGS) -c $<
COV_FLAGS=-fprofile-arcs -ftest-coverage
COV_OBJS=xmdb.o xmidl.o
coverage: xmtest
for i in mtest*.c [0-9]*.c; do j=`basename \$$i .c`; $(MAKE) $$j.o; \
gcc -o x$$j $$j.o $(COV_OBJS) -pthread $(COV_FLAGS); \
rm -rf testdb; mkdir testdb; ./x$$j; done
gcov xmdb.c
gcov xmidl.c
xmtest: mtest.o xmdb.o xmidl.o
gcc -o xmtest mtest.o xmdb.o xmidl.o -pthread $(COV_FLAGS)
xmdb.o: mdb.c lmdb.h midl.h
$(CC) $(CFLAGS) -fPIC $(CPPFLAGS) -O0 $(COV_FLAGS) -c mdb.c -o $@
xmidl.o: midl.c midl.h
$(CC) $(CFLAGS) -fPIC $(CPPFLAGS) -O0 $(COV_FLAGS) -c midl.c -o $@

1584
deps/liblmdb/lmdb.h vendored Normal file

File diff suppressed because it is too large Load Diff

10011
deps/liblmdb/mdb.c vendored Normal file

File diff suppressed because it is too large Load Diff

54
deps/liblmdb/mdb_copy.1 vendored Normal file
View File

@ -0,0 +1,54 @@
.TH MDB_COPY 1 "2014/06/20" "LMDB 0.9.14"
.\" Copyright 2012-2015 Howard Chu, Symas Corp. All Rights Reserved.
.\" Copying restrictions apply. See COPYRIGHT/LICENSE.
.SH NAME
mdb_copy \- LMDB environment copy tool
.SH SYNOPSIS
.B mdb_copy
[\c
.BR \-V ]
[\c
.BR \-c ]
[\c
.BR \-n ]
.B srcpath
[\c
.BR dstpath ]
.SH DESCRIPTION
The
.B mdb_copy
utility copies an LMDB environment. The environment can
be copied regardless of whether it is currently in use.
No lockfile is created, since it gets recreated at need.
If
.I dstpath
is specified it must be the path of an empty directory
for storing the backup. Otherwise, the backup will be
written to stdout.
.SH OPTIONS
.TP
.BR \-V
Write the library version number to the standard output, and exit.
.TP
.BR \-c
Compact while copying. Only current data pages will be copied; freed
or unused pages will be omitted from the copy. This option will
slow down the backup process as it is more CPU-intensive.
.TP
.BR \-n
Open LDMB environment(s) which do not use subdirectories.
.SH DIAGNOSTICS
Exit status is zero if no errors occur.
Errors result in a non-zero exit status and
a diagnostic message being written to standard error.
.SH CAVEATS
This utility can trigger significant file size growth if run
in parallel with write transactions, because pages which they
free during copying cannot be reused until the copy is done.
.SH "SEE ALSO"
.BR mdb_stat (1)
.SH AUTHOR
Howard Chu of Symas Corporation <http://www.symas.com>

82
deps/liblmdb/mdb_copy.c vendored Normal file
View File

@ -0,0 +1,82 @@
/* mdb_copy.c - memory-mapped database backup tool */
/*
* Copyright 2012-2015 Howard Chu, Symas Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
#ifdef _WIN32
#include <windows.h>
#define MDB_STDOUT GetStdHandle(STD_OUTPUT_HANDLE)
#else
#define MDB_STDOUT 1
#endif
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include "lmdb.h"
static void
sighandle(int sig)
{
}
int main(int argc,char * argv[])
{
int rc;
MDB_env *env;
const char *progname = argv[0], *act;
unsigned flags = MDB_RDONLY;
unsigned cpflags = 0;
for (; argc > 1 && argv[1][0] == '-'; argc--, argv++) {
if (argv[1][1] == 'n' && argv[1][2] == '\0')
flags |= MDB_NOSUBDIR;
else if (argv[1][1] == 'c' && argv[1][2] == '\0')
cpflags |= MDB_CP_COMPACT;
else if (argv[1][1] == 'V' && argv[1][2] == '\0') {
printf("%s\n", MDB_VERSION_STRING);
exit(0);
} else
argc = 0;
}
if (argc<2 || argc>3) {
fprintf(stderr, "usage: %s [-V] [-c] [-n] srcpath [dstpath]\n", progname);
exit(EXIT_FAILURE);
}
#ifdef SIGPIPE
signal(SIGPIPE, sighandle);
#endif
#ifdef SIGHUP
signal(SIGHUP, sighandle);
#endif
signal(SIGINT, sighandle);
signal(SIGTERM, sighandle);
act = "opening environment";
rc = mdb_env_create(&env);
if (rc == MDB_SUCCESS) {
rc = mdb_env_open(env, argv[1], flags, 0600);
}
if (rc == MDB_SUCCESS) {
act = "copying";
if (argc == 2)
rc = mdb_env_copyfd2(env, MDB_STDOUT, cpflags);
else
rc = mdb_env_copy2(env, argv[2], cpflags);
}
if (rc)
fprintf(stderr, "%s: %s failed, error %d (%s)\n",
progname, act, rc, mdb_strerror(rc));
mdb_env_close(env);
return rc ? EXIT_FAILURE : EXIT_SUCCESS;
}

75
deps/liblmdb/mdb_dump.1 vendored Normal file
View File

@ -0,0 +1,75 @@
.TH MDB_DUMP 1 "2014/06/20" "LMDB 0.9.14"
.\" Copyright 2014-2015 Howard Chu, Symas Corp. All Rights Reserved.
.\" Copying restrictions apply. See COPYRIGHT/LICENSE.
.SH NAME
mdb_dump \- LMDB environment export tool
.SH SYNOPSIS
.B mdb_dump
[\c
.BR \-V ]
[\c
.BI \-f \ file\fR]
[\c
.BR \-l ]
[\c
.BR \-n ]
[\c
.BR \-p ]
[\c
.BR \-a \ |
.BI \-s \ subdb\fR]
.BR \ envpath
.SH DESCRIPTION
The
.B mdb_dump
utility reads a database and writes its contents to the
standard output using a portable flat-text format
understood by the
.BR mdb_load (1)
utility.
.SH OPTIONS
.TP
.BR \-V
Write the library version number to the standard output, and exit.
.TP
.BR \-f \ file
Write to the specified file instead of to the standard output.
.TP
.BR \-l
List the databases stored in the environment. Just the
names will be listed, no data will be output.
.TP
.BR \-n
Dump an LMDB database which does not use subdirectories.
.TP
.BR \-p
If characters in either the key or data items are printing characters (as
defined by isprint(3)), output them directly. This option permits users to
use standard text editors and tools to modify the contents of databases.
Note: different systems may have different notions about what characters
are considered printing characters, and databases dumped in this manner may
be less portable to external systems.
.TP
.BR \-a
Dump all of the subdatabases in the environment.
.TP
.BR \-s \ subdb
Dump a specific subdatabase. If no database is specified, only the main database is dumped.
.SH DIAGNOSTICS
Exit status is zero if no errors occur.
Errors result in a non-zero exit status and
a diagnostic message being written to standard error.
Dumping and reloading databases that use user-defined comparison functions
will result in new databases that use the default comparison functions.
\fBIn this case it is quite likely that the reloaded database will be
damaged beyond repair permitting neither record storage nor retrieval.\fP
The only available workaround is to modify the source for the
.BR mdb_load (1)
utility to load the database using the correct comparison functions.
.SH "SEE ALSO"
.BR mdb_load (1)
.SH AUTHOR
Howard Chu of Symas Corporation <http://www.symas.com>

317
deps/liblmdb/mdb_dump.c vendored Normal file
View File

@ -0,0 +1,317 @@
/* mdb_dump.c - memory-mapped database dump tool */
/*
* Copyright 2011-2015 Howard Chu, Symas Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <signal.h>
#include "lmdb.h"
#ifdef _WIN32
#define Z "I"
#else
#define Z "z"
#endif
#define PRINT 1
static int mode;
typedef struct flagbit {
int bit;
char *name;
} flagbit;
flagbit dbflags[] = {
{ MDB_REVERSEKEY, "reversekey" },
{ MDB_DUPSORT, "dupsort" },
{ MDB_INTEGERKEY, "integerkey" },
{ MDB_DUPFIXED, "dupfixed" },
{ MDB_INTEGERDUP, "integerdup" },
{ MDB_REVERSEDUP, "reversedup" },
{ 0, NULL }
};
static volatile sig_atomic_t gotsig;
static void dumpsig( int sig )
{
gotsig=1;
}
static const char hexc[] = "0123456789abcdef";
static void hex(unsigned char c)
{
putchar(hexc[c >> 4]);
putchar(hexc[c & 0xf]);
}
static void text(MDB_val *v)
{
unsigned char *c, *end;
putchar(' ');
c = v->mv_data;
end = c + v->mv_size;
while (c < end) {
if (isprint(*c)) {
putchar(*c);
} else {
putchar('\\');
hex(*c);
}
c++;
}
putchar('\n');
}
static void byte(MDB_val *v)
{
unsigned char *c, *end;
putchar(' ');
c = v->mv_data;
end = c + v->mv_size;
while (c < end) {
hex(*c++);
}
putchar('\n');
}
/* Dump in BDB-compatible format */
static int dumpit(MDB_txn *txn, MDB_dbi dbi, char *name)
{
MDB_cursor *mc;
MDB_stat ms;
MDB_val key, data;
MDB_envinfo info;
unsigned int flags;
int rc, i;
rc = mdb_dbi_flags(txn, dbi, &flags);
if (rc) return rc;
rc = mdb_stat(txn, dbi, &ms);
if (rc) return rc;
rc = mdb_env_info(mdb_txn_env(txn), &info);
if (rc) return rc;
printf("VERSION=3\n");
printf("format=%s\n", mode & PRINT ? "print" : "bytevalue");
if (name)
printf("database=%s\n", name);
printf("type=btree\n");
printf("mapsize=%" Z "u\n", info.me_mapsize);
if (info.me_mapaddr)
printf("mapaddr=%p\n", info.me_mapaddr);
printf("maxreaders=%u\n", info.me_maxreaders);
if (flags & MDB_DUPSORT)
printf("duplicates=1\n");
for (i=0; dbflags[i].bit; i++)
if (flags & dbflags[i].bit)
printf("%s=1\n", dbflags[i].name);
printf("db_pagesize=%d\n", ms.ms_psize);
printf("HEADER=END\n");
rc = mdb_cursor_open(txn, dbi, &mc);
if (rc) return rc;
while ((rc = mdb_cursor_get(mc, &key, &data, MDB_NEXT) == MDB_SUCCESS)) {
if (gotsig) {
rc = EINTR;
break;
}
if (mode & PRINT) {
text(&key);
text(&data);
} else {
byte(&key);
byte(&data);
}
}
printf("DATA=END\n");
if (rc == MDB_NOTFOUND)
rc = MDB_SUCCESS;
return rc;
}
static void usage(char *prog)
{
fprintf(stderr, "usage: %s [-V] [-f output] [-l] [-n] [-p] [-a|-s subdb] dbpath\n", prog);
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[])
{
int i, rc;
MDB_env *env;
MDB_txn *txn;
MDB_dbi dbi;
char *prog = argv[0];
char *envname;
char *subname = NULL;
int alldbs = 0, envflags = 0, list = 0;
if (argc < 2) {
usage(prog);
}
/* -a: dump main DB and all subDBs
* -s: dump only the named subDB
* -n: use NOSUBDIR flag on env_open
* -p: use printable characters
* -f: write to file instead of stdout
* -V: print version and exit
* (default) dump only the main DB
*/
while ((i = getopt(argc, argv, "af:lnps:V")) != EOF) {
switch(i) {
case 'V':
printf("%s\n", MDB_VERSION_STRING);
exit(0);
break;
case 'l':
list = 1;
/*FALLTHROUGH*/;
case 'a':
if (subname)
usage(prog);
alldbs++;
break;
case 'f':
if (freopen(optarg, "w", stdout) == NULL) {
fprintf(stderr, "%s: %s: reopen: %s\n",
prog, optarg, strerror(errno));
exit(EXIT_FAILURE);
}
break;
case 'n':
envflags |= MDB_NOSUBDIR;
break;
case 'p':
mode |= PRINT;
break;
case 's':
if (alldbs)
usage(prog);
subname = optarg;
break;
default:
usage(prog);
}
}
if (optind != argc - 1)
usage(prog);
#ifdef SIGPIPE
signal(SIGPIPE, dumpsig);
#endif
#ifdef SIGHUP
signal(SIGHUP, dumpsig);
#endif
signal(SIGINT, dumpsig);
signal(SIGTERM, dumpsig);
envname = argv[optind];
rc = mdb_env_create(&env);
if (rc) {
fprintf(stderr, "mdb_env_create failed, error %d %s\n", rc, mdb_strerror(rc));
return EXIT_FAILURE;
}
if (alldbs || subname) {
mdb_env_set_maxdbs(env, 2);
}
rc = mdb_env_open(env, envname, envflags | MDB_RDONLY, 0664);
if (rc) {
fprintf(stderr, "mdb_env_open failed, error %d %s\n", rc, mdb_strerror(rc));
goto env_close;
}
rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
if (rc) {
fprintf(stderr, "mdb_txn_begin failed, error %d %s\n", rc, mdb_strerror(rc));
goto env_close;
}
rc = mdb_open(txn, subname, 0, &dbi);
if (rc) {
fprintf(stderr, "mdb_open failed, error %d %s\n", rc, mdb_strerror(rc));
goto txn_abort;
}
if (alldbs) {
MDB_cursor *cursor;
MDB_val key;
int count = 0;
rc = mdb_cursor_open(txn, dbi, &cursor);
if (rc) {
fprintf(stderr, "mdb_cursor_open failed, error %d %s\n", rc, mdb_strerror(rc));
goto txn_abort;
}
while ((rc = mdb_cursor_get(cursor, &key, NULL, MDB_NEXT_NODUP)) == 0) {
char *str;
MDB_dbi db2;
if (memchr(key.mv_data, '\0', key.mv_size))
continue;
count++;
str = malloc(key.mv_size+1);
memcpy(str, key.mv_data, key.mv_size);
str[key.mv_size] = '\0';
rc = mdb_open(txn, str, 0, &db2);
if (rc == MDB_SUCCESS) {
if (list) {
printf("%s\n", str);
list++;
} else {
rc = dumpit(txn, db2, str);
if (rc)
break;
}
mdb_close(env, db2);
}
free(str);
if (rc) continue;
}
mdb_cursor_close(cursor);
if (!count) {
fprintf(stderr, "%s: %s does not contain multiple databases\n", prog, envname);
rc = MDB_NOTFOUND;
} else if (rc == MDB_NOTFOUND) {
rc = MDB_SUCCESS;
}
} else {
rc = dumpit(txn, dbi, subname);
}
if (rc && rc != MDB_NOTFOUND)
fprintf(stderr, "%s: %s: %s\n", prog, envname, mdb_strerror(rc));
mdb_close(env, dbi);
txn_abort:
mdb_txn_abort(txn);
env_close:
mdb_env_close(env);
return rc ? EXIT_FAILURE : EXIT_SUCCESS;
}

77
deps/liblmdb/mdb_load.1 vendored Normal file
View File

@ -0,0 +1,77 @@
.TH MDB_LOAD 1 "2014/06/20" "LMDB 0.9.14"
.\" Copyright 2014-2015 Howard Chu, Symas Corp. All Rights Reserved.
.\" Copying restrictions apply. See COPYRIGHT/LICENSE.
.SH NAME
mdb_load \- LMDB environment import tool
.SH SYNOPSIS
.B mdb_load
[\c
.BR \-V ]
[\c
.BI \-f \ file\fR]
[\c
.BR \-n ]
[\c
.BI \-s \ subdb\fR]
[\c
.BR \-N ]
[\c
.BR \-T ]
.BR \ envpath
.SH DESCRIPTION
The
.B mdb_load
utility reads from the standard input and loads it into the
LMDB environment
.BR envpath .
The input to
.B mdb_load
must be in the output format specified by the
.BR mdb_dump (1)
utility or as specified by the
.B -T
option below.
.SH OPTIONS
.TP
.BR \-V
Write the library version number to the standard output, and exit.
.TP
.BR \-f \ file
Read from the specified file instead of from the standard input.
.TP
.BR \-n
Load an LMDB database which does not use subdirectories.
.TP
.BR \-s \ subdb
Load a specific subdatabase. If no database is specified, data is loaded into the main database.
.TP
.BR \-N
Don't overwrite existing records when loading into an already existing database; just skip them.
.TP
.BR \-T
Load data from simple text files. The input must be paired lines of text, where the first
line of the pair is the key item, and the second line of the pair is its corresponding
data item.
A simple escape mechanism, where newline and backslash (\\) characters are special, is
applied to the text input. Newline characters are interpreted as record separators.
Backslash characters in the text will be interpreted in one of two ways: If the backslash
character precedes another backslash character, the pair will be interpreted as a literal
backslash. If the backslash character precedes any other character, the two characters
following the backslash will be interpreted as a hexadecimal specification of a single
character; for example, \\0a is a newline character in the ASCII character set.
For this reason, any backslash or newline characters that naturally occur in the text
input must be escaped to avoid misinterpretation by
.BR mdb_load .
.SH DIAGNOSTICS
Exit status is zero if no errors occur.
Errors result in a non-zero exit status and
a diagnostic message being written to standard error.
.SH "SEE ALSO"
.BR mdb_dump (1)
.SH AUTHOR
Howard Chu of Symas Corporation <http://www.symas.com>

456
deps/liblmdb/mdb_load.c vendored Normal file
View File

@ -0,0 +1,456 @@
/* mdb_load.c - memory-mapped database load tool */
/*
* Copyright 2011-2015 Howard Chu, Symas Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include "lmdb.h"
#define PRINT 1
#define NOHDR 2
static int mode;
static char *subname = NULL;
static size_t lineno;
static int version;
static int flags;
static char *prog;
static int Eof;
static MDB_envinfo info;
static MDB_val kbuf, dbuf;
#ifdef _WIN32
#define Z "I"
#else
#define Z "z"
#endif
#define STRLENOF(s) (sizeof(s)-1)
typedef struct flagbit {
int bit;
char *name;
int len;
} flagbit;
#define S(s) s, STRLENOF(s)
flagbit dbflags[] = {
{ MDB_REVERSEKEY, S("reversekey") },
{ MDB_DUPSORT, S("dupsort") },
{ MDB_INTEGERKEY, S("integerkey") },
{ MDB_DUPFIXED, S("dupfixed") },
{ MDB_INTEGERDUP, S("integerdup") },
{ MDB_REVERSEDUP, S("reversedup") },
{ 0, NULL, 0 }
};
static void readhdr(void)
{
char *ptr;
while (fgets(dbuf.mv_data, dbuf.mv_size, stdin) != NULL) {
lineno++;
if (!strncmp(dbuf.mv_data, "VERSION=", STRLENOF("VERSION="))) {
version=atoi((char *)dbuf.mv_data+STRLENOF("VERSION="));
if (version > 3) {
fprintf(stderr, "%s: line %" Z "d: unsupported VERSION %d\n",
prog, lineno, version);
exit(EXIT_FAILURE);
}
} else if (!strncmp(dbuf.mv_data, "HEADER=END", STRLENOF("HEADER=END"))) {
break;
} else if (!strncmp(dbuf.mv_data, "format=", STRLENOF("format="))) {
if (!strncmp((char *)dbuf.mv_data+STRLENOF("FORMAT="), "print", STRLENOF("print")))
mode |= PRINT;
else if (strncmp((char *)dbuf.mv_data+STRLENOF("FORMAT="), "bytevalue", STRLENOF("bytevalue"))) {
fprintf(stderr, "%s: line %" Z "d: unsupported FORMAT %s\n",
prog, lineno, (char *)dbuf.mv_data+STRLENOF("FORMAT="));
exit(EXIT_FAILURE);
}
} else if (!strncmp(dbuf.mv_data, "database=", STRLENOF("database="))) {
ptr = memchr(dbuf.mv_data, '\n', dbuf.mv_size);
if (ptr) *ptr = '\0';
if (subname) free(subname);
subname = strdup((char *)dbuf.mv_data+STRLENOF("database="));
} else if (!strncmp(dbuf.mv_data, "type=", STRLENOF("type="))) {
if (strncmp((char *)dbuf.mv_data+STRLENOF("type="), "btree", STRLENOF("btree"))) {
fprintf(stderr, "%s: line %" Z "d: unsupported type %s\n",
prog, lineno, (char *)dbuf.mv_data+STRLENOF("type="));
exit(EXIT_FAILURE);
}
} else if (!strncmp(dbuf.mv_data, "mapaddr=", STRLENOF("mapaddr="))) {
int i;
ptr = memchr(dbuf.mv_data, '\n', dbuf.mv_size);
if (ptr) *ptr = '\0';
i = sscanf((char *)dbuf.mv_data+STRLENOF("mapaddr="), "%p", &info.me_mapaddr);
if (i != 1) {
fprintf(stderr, "%s: line %" Z "d: invalid mapaddr %s\n",
prog, lineno, (char *)dbuf.mv_data+STRLENOF("mapaddr="));
exit(EXIT_FAILURE);
}
} else if (!strncmp(dbuf.mv_data, "mapsize=", STRLENOF("mapsize="))) {
int i;
ptr = memchr(dbuf.mv_data, '\n', dbuf.mv_size);
if (ptr) *ptr = '\0';
i = sscanf((char *)dbuf.mv_data+STRLENOF("mapsize="), "%" Z "u", &info.me_mapsize);
if (i != 1) {
fprintf(stderr, "%s: line %" Z "d: invalid mapsize %s\n",
prog, lineno, (char *)dbuf.mv_data+STRLENOF("mapsize="));
exit(EXIT_FAILURE);
}
} else if (!strncmp(dbuf.mv_data, "maxreaders=", STRLENOF("maxreaders="))) {
int i;
ptr = memchr(dbuf.mv_data, '\n', dbuf.mv_size);
if (ptr) *ptr = '\0';
i = sscanf((char *)dbuf.mv_data+STRLENOF("maxreaders="), "%u", &info.me_maxreaders);
if (i != 1) {
fprintf(stderr, "%s: line %" Z "d: invalid maxreaders %s\n",
prog, lineno, (char *)dbuf.mv_data+STRLENOF("maxreaders="));
exit(EXIT_FAILURE);
}
} else {
int i;
for (i=0; dbflags[i].bit; i++) {
if (!strncmp(dbuf.mv_data, dbflags[i].name, dbflags[i].len) &&
((char *)dbuf.mv_data)[dbflags[i].len] == '=') {
flags |= dbflags[i].bit;
break;
}
}
if (!dbflags[i].bit) {
ptr = memchr(dbuf.mv_data, '=', dbuf.mv_size);
if (!ptr) {
fprintf(stderr, "%s: line %" Z "d: unexpected format\n",
prog, lineno);
exit(EXIT_FAILURE);
} else {
*ptr = '\0';
fprintf(stderr, "%s: line %" Z "d: unrecognized keyword ignored: %s\n",
prog, lineno, (char *)dbuf.mv_data);
}
}
}
}
}
static void badend(void)
{
fprintf(stderr, "%s: line %" Z "d: unexpected end of input\n",
prog, lineno);
}
static int unhex(unsigned char *c2)
{
int x, c;
x = *c2++ & 0x4f;
if (x & 0x40)
x -= 55;
c = x << 4;
x = *c2 & 0x4f;
if (x & 0x40)
x -= 55;
c |= x;
return c;
}
static int readline(MDB_val *out, MDB_val *buf)
{
unsigned char *c1, *c2, *end;
size_t len, l2;
int c;
if (!(mode & NOHDR)) {
c = fgetc(stdin);
if (c == EOF) {
Eof = 1;
return EOF;
}
if (c != ' ') {
lineno++;
if (fgets(buf->mv_data, buf->mv_size, stdin) == NULL) {
badend:
Eof = 1;
badend();
return EOF;
}
if (c == 'D' && !strncmp(buf->mv_data, "ATA=END", STRLENOF("ATA=END")))
return EOF;
goto badend;
}
}
if (fgets(buf->mv_data, buf->mv_size, stdin) == NULL) {
Eof = 1;
return EOF;
}
lineno++;
c1 = buf->mv_data;
len = strlen((char *)c1);
l2 = len;
/* Is buffer too short? */
while (c1[len-1] != '\n') {
buf->mv_data = realloc(buf->mv_data, buf->mv_size*2);
if (!buf->mv_data) {
Eof = 1;
fprintf(stderr, "%s: line %" Z "d: out of memory, line too long\n",
prog, lineno);
return EOF;
}
c1 = buf->mv_data;
c1 += l2;
if (fgets((char *)c1, buf->mv_size+1, stdin) == NULL) {
Eof = 1;
badend();
return EOF;
}
buf->mv_size *= 2;
len = strlen((char *)c1);
l2 += len;
}
c1 = c2 = buf->mv_data;
len = l2;
c1[--len] = '\0';
end = c1 + len;
if (mode & PRINT) {
while (c2 < end) {
if (*c2 == '\\') {
if (c2[1] == '\\') {
c1++; c2 += 2;
} else {
if (c2+3 > end || !isxdigit(c2[1]) || !isxdigit(c2[2])) {
Eof = 1;
badend();
return EOF;
}
*c1++ = unhex(++c2);
c2 += 2;
}
} else {
c1++; c2++;
}
}
} else {
/* odd length not allowed */
if (len & 1) {
Eof = 1;
badend();
return EOF;
}
while (c2 < end) {
if (!isxdigit(*c2) || !isxdigit(c2[1])) {
Eof = 1;
badend();
return EOF;
}
*c1++ = unhex(c2);
c2 += 2;
}
}
c2 = out->mv_data = buf->mv_data;
out->mv_size = c1 - c2;
return 0;
}
static void usage(void)
{
fprintf(stderr, "usage: %s [-V] [-f input] [-n] [-s name] [-N] [-T] dbpath\n", prog);
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[])
{
int i, rc;
MDB_env *env;
MDB_txn *txn;
MDB_cursor *mc;
MDB_dbi dbi;
char *envname;
int envflags = 0, putflags = 0;
int dohdr = 0;
prog = argv[0];
if (argc < 2) {
usage();
}
/* -f: load file instead of stdin
* -n: use NOSUBDIR flag on env_open
* -s: load into named subDB
* -N: use NOOVERWRITE on puts
* -T: read plaintext
* -V: print version and exit
*/
while ((i = getopt(argc, argv, "f:ns:NTV")) != EOF) {
switch(i) {
case 'V':
printf("%s\n", MDB_VERSION_STRING);
exit(0);
break;
case 'f':
if (freopen(optarg, "r", stdin) == NULL) {
fprintf(stderr, "%s: %s: reopen: %s\n",
prog, optarg, strerror(errno));
exit(EXIT_FAILURE);
}
break;
case 'n':
envflags |= MDB_NOSUBDIR;
break;
case 's':
subname = strdup(optarg);
break;
case 'N':
putflags = MDB_NOOVERWRITE|MDB_NODUPDATA;
break;
case 'T':
mode |= NOHDR | PRINT;
break;
default:
usage();
}
}
if (optind != argc - 1)
usage();
dbuf.mv_size = 4096;
dbuf.mv_data = malloc(dbuf.mv_size);
if (!(mode & NOHDR))
readhdr();
envname = argv[optind];
rc = mdb_env_create(&env);
if (rc) {
fprintf(stderr, "mdb_env_create failed, error %d %s\n", rc, mdb_strerror(rc));
return EXIT_FAILURE;
}
mdb_env_set_maxdbs(env, 2);
if (info.me_maxreaders)
mdb_env_set_maxreaders(env, info.me_maxreaders);
if (info.me_mapsize)
mdb_env_set_mapsize(env, info.me_mapsize);
if (info.me_mapaddr)
envflags |= MDB_FIXEDMAP;
rc = mdb_env_open(env, envname, envflags, 0664);
if (rc) {
fprintf(stderr, "mdb_env_open failed, error %d %s\n", rc, mdb_strerror(rc));
goto env_close;
}
kbuf.mv_size = mdb_env_get_maxkeysize(env) * 2 + 2;
kbuf.mv_data = malloc(kbuf.mv_size);
while(!Eof) {
MDB_val key, data;
int batch = 0;
flags = 0;
if (!dohdr) {
dohdr = 1;
} else if (!(mode & NOHDR))
readhdr();
rc = mdb_txn_begin(env, NULL, 0, &txn);
if (rc) {
fprintf(stderr, "mdb_txn_begin failed, error %d %s\n", rc, mdb_strerror(rc));
goto env_close;
}
rc = mdb_open(txn, subname, flags|MDB_CREATE, &dbi);
if (rc) {
fprintf(stderr, "mdb_open failed, error %d %s\n", rc, mdb_strerror(rc));
goto txn_abort;
}
rc = mdb_cursor_open(txn, dbi, &mc);
if (rc) {
fprintf(stderr, "mdb_cursor_open failed, error %d %s\n", rc, mdb_strerror(rc));
goto txn_abort;
}
while(1) {
rc = readline(&key, &kbuf);
if (rc) /* rc == EOF */
break;
rc = readline(&data, &dbuf);
if (rc) {
fprintf(stderr, "%s: line %" Z "d: failed to read key value\n", prog, lineno);
goto txn_abort;
}
rc = mdb_cursor_put(mc, &key, &data, putflags);
if (rc == MDB_KEYEXIST && putflags)
continue;
if (rc) {
fprintf(stderr, "mdb_cursor_put failed, error %d %s\n", rc, mdb_strerror(rc));
goto txn_abort;
}
batch++;
if (batch == 100) {
rc = mdb_txn_commit(txn);
if (rc) {
fprintf(stderr, "%s: line %" Z "d: txn_commit: %s\n",
prog, lineno, mdb_strerror(rc));
goto env_close;
}
rc = mdb_txn_begin(env, NULL, 0, &txn);
if (rc) {
fprintf(stderr, "mdb_txn_begin failed, error %d %s\n", rc, mdb_strerror(rc));
goto env_close;
}
rc = mdb_cursor_open(txn, dbi, &mc);
if (rc) {
fprintf(stderr, "mdb_cursor_open failed, error %d %s\n", rc, mdb_strerror(rc));
goto txn_abort;
}
batch = 0;
}
}
rc = mdb_txn_commit(txn);
txn = NULL;
if (rc) {
fprintf(stderr, "%s: line %" Z "d: txn_commit: %s\n",
prog, lineno, mdb_strerror(rc));
goto env_close;
}
mdb_dbi_close(env, dbi);
}
txn_abort:
mdb_txn_abort(txn);
env_close:
mdb_env_close(env);
return rc ? EXIT_FAILURE : EXIT_SUCCESS;
}

64
deps/liblmdb/mdb_stat.1 vendored Normal file
View File

@ -0,0 +1,64 @@
.TH MDB_STAT 1 "2014/06/20" "LMDB 0.9.14"
.\" Copyright 2012-2015 Howard Chu, Symas Corp. All Rights Reserved.
.\" Copying restrictions apply. See COPYRIGHT/LICENSE.
.SH NAME
mdb_stat \- LMDB environment status tool
.SH SYNOPSIS
.B mdb_stat
[\c
.BR \-V ]
[\c
.BR \-e ]
[\c
.BR \-f [ f [ f ]]]
[\c
.BR \-n ]
[\c
.BR \-r [ r ]]
[\c
.BR \-a \ |
.BI \-s \ subdb\fR]
.BR \ envpath
.SH DESCRIPTION
The
.B mdb_stat
utility displays the status of an LMDB environment.
.SH OPTIONS
.TP
.BR \-V
Write the library version number to the standard output, and exit.
.TP
.BR \-e
Display information about the database environment.
.TP
.BR \-f
Display information about the environment freelist.
If \fB\-ff\fP is given, summarize each freelist entry.
If \fB\-fff\fP is given, display the full list of page IDs in the freelist.
.TP
.BR \-n
Display the status of an LMDB database which does not use subdirectories.
.TP
.BR \-r
Display information about the environment reader table.
Shows the process ID, thread ID, and transaction ID for each active
reader slot. The process ID and transaction ID are in decimal, the
thread ID is in hexadecimal. The transaction ID is displayed as "-"
if the reader does not currently have a read transaction open.
If \fB\-rr\fP is given, check for stale entries in the reader
table and clear them. The reader table will be printed again
after the check is performed.
.TP
.BR \-a
Display the status of all of the subdatabases in the environment.
.TP
.BR \-s \ subdb
Display the status of a specific subdatabase.
.SH DIAGNOSTICS
Exit status is zero if no errors occur.
Errors result in a non-zero exit status and
a diagnostic message being written to standard error.
.SH "SEE ALSO"
.BR mdb_copy (1)
.SH AUTHOR
Howard Chu of Symas Corporation <http://www.symas.com>

263
deps/liblmdb/mdb_stat.c vendored Normal file
View File

@ -0,0 +1,263 @@
/* mdb_stat.c - memory-mapped database status tool */
/*
* Copyright 2011-2015 Howard Chu, Symas Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "lmdb.h"
#ifdef _WIN32
#define Z "I"
#else
#define Z "z"
#endif
static void prstat(MDB_stat *ms)
{
#if 0
printf(" Page size: %u\n", ms->ms_psize);
#endif
printf(" Tree depth: %u\n", ms->ms_depth);
printf(" Branch pages: %"Z"u\n", ms->ms_branch_pages);
printf(" Leaf pages: %"Z"u\n", ms->ms_leaf_pages);
printf(" Overflow pages: %"Z"u\n", ms->ms_overflow_pages);
printf(" Entries: %"Z"u\n", ms->ms_entries);
}
static void usage(char *prog)
{
fprintf(stderr, "usage: %s [-V] [-n] [-e] [-r[r]] [-f[f[f]]] [-a|-s subdb] dbpath\n", prog);
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[])
{
int i, rc;
MDB_env *env;
MDB_txn *txn;
MDB_dbi dbi;
MDB_stat mst;
MDB_envinfo mei;
char *prog = argv[0];
char *envname;
char *subname = NULL;
int alldbs = 0, envinfo = 0, envflags = 0, freinfo = 0, rdrinfo = 0;
if (argc < 2) {
usage(prog);
}
/* -a: print stat of main DB and all subDBs
* -s: print stat of only the named subDB
* -e: print env info
* -f: print freelist info
* -r: print reader info
* -n: use NOSUBDIR flag on env_open
* -V: print version and exit
* (default) print stat of only the main DB
*/
while ((i = getopt(argc, argv, "Vaefnrs:")) != EOF) {
switch(i) {
case 'V':
printf("%s\n", MDB_VERSION_STRING);
exit(0);
break;
case 'a':
if (subname)
usage(prog);
alldbs++;
break;
case 'e':
envinfo++;
break;
case 'f':
freinfo++;
break;
case 'n':
envflags |= MDB_NOSUBDIR;
break;
case 'r':
rdrinfo++;
break;
case 's':
if (alldbs)
usage(prog);
subname = optarg;
break;
default:
usage(prog);
}
}
if (optind != argc - 1)
usage(prog);
envname = argv[optind];
rc = mdb_env_create(&env);
if (rc) {
fprintf(stderr, "mdb_env_create failed, error %d %s\n", rc, mdb_strerror(rc));
return EXIT_FAILURE;
}
if (alldbs || subname) {
mdb_env_set_maxdbs(env, 4);
}
rc = mdb_env_open(env, envname, envflags | MDB_RDONLY, 0664);
if (rc) {
fprintf(stderr, "mdb_env_open failed, error %d %s\n", rc, mdb_strerror(rc));
goto env_close;
}
if (envinfo) {
(void)mdb_env_stat(env, &mst);
(void)mdb_env_info(env, &mei);
printf("Environment Info\n");
printf(" Map address: %p\n", mei.me_mapaddr);
printf(" Map size: %"Z"u\n", mei.me_mapsize);
printf(" Page size: %u\n", mst.ms_psize);
printf(" Max pages: %"Z"u\n", mei.me_mapsize / mst.ms_psize);
printf(" Number of pages used: %"Z"u\n", mei.me_last_pgno+1);
printf(" Last transaction ID: %"Z"u\n", mei.me_last_txnid);
printf(" Max readers: %u\n", mei.me_maxreaders);
printf(" Number of readers used: %u\n", mei.me_numreaders);
}
if (rdrinfo) {
printf("Reader Table Status\n");
rc = mdb_reader_list(env, (MDB_msg_func *)fputs, stdout);
if (rdrinfo > 1) {
int dead;
mdb_reader_check(env, &dead);
printf(" %d stale readers cleared.\n", dead);
rc = mdb_reader_list(env, (MDB_msg_func *)fputs, stdout);
}
if (!(subname || alldbs || freinfo))
goto env_close;
}
rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
if (rc) {
fprintf(stderr, "mdb_txn_begin failed, error %d %s\n", rc, mdb_strerror(rc));
goto env_close;
}
if (freinfo) {
MDB_cursor *cursor;
MDB_val key, data;
size_t pages = 0, *iptr;
printf("Freelist Status\n");
dbi = 0;
rc = mdb_cursor_open(txn, dbi, &cursor);
if (rc) {
fprintf(stderr, "mdb_cursor_open failed, error %d %s\n", rc, mdb_strerror(rc));
goto txn_abort;
}
rc = mdb_stat(txn, dbi, &mst);
if (rc) {
fprintf(stderr, "mdb_stat failed, error %d %s\n", rc, mdb_strerror(rc));
goto txn_abort;
}
prstat(&mst);
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
iptr = data.mv_data;
pages += *iptr;
if (freinfo > 1) {
char *bad = "";
size_t pg, prev;
ssize_t i, j, span = 0;
j = *iptr++;
for (i = j, prev = 1; --i >= 0; ) {
pg = iptr[i];
if (pg <= prev)
bad = " [bad sequence]";
prev = pg;
pg += span;
for (; i >= span && iptr[i-span] == pg; span++, pg++) ;
}
printf(" Transaction %"Z"u, %"Z"d pages, maxspan %"Z"d%s\n",
*(size_t *)key.mv_data, j, span, bad);
if (freinfo > 2) {
for (--j; j >= 0; ) {
pg = iptr[j];
for (span=1; --j >= 0 && iptr[j] == pg+span; span++) ;
printf(span>1 ? " %9"Z"u[%"Z"d]\n" : " %9"Z"u\n",
pg, span);
}
}
}
}
mdb_cursor_close(cursor);
printf(" Free pages: %"Z"u\n", pages);
}
rc = mdb_open(txn, subname, 0, &dbi);
if (rc) {
fprintf(stderr, "mdb_open failed, error %d %s\n", rc, mdb_strerror(rc));
goto txn_abort;
}
rc = mdb_stat(txn, dbi, &mst);
if (rc) {
fprintf(stderr, "mdb_stat failed, error %d %s\n", rc, mdb_strerror(rc));
goto txn_abort;
}
printf("Status of %s\n", subname ? subname : "Main DB");
prstat(&mst);
if (alldbs) {
MDB_cursor *cursor;
MDB_val key;
rc = mdb_cursor_open(txn, dbi, &cursor);
if (rc) {
fprintf(stderr, "mdb_cursor_open failed, error %d %s\n", rc, mdb_strerror(rc));
goto txn_abort;
}
while ((rc = mdb_cursor_get(cursor, &key, NULL, MDB_NEXT_NODUP)) == 0) {
char *str;
MDB_dbi db2;
if (memchr(key.mv_data, '\0', key.mv_size))
continue;
str = malloc(key.mv_size+1);
memcpy(str, key.mv_data, key.mv_size);
str[key.mv_size] = '\0';
rc = mdb_open(txn, str, 0, &db2);
if (rc == MDB_SUCCESS)
printf("Status of %s\n", str);
free(str);
if (rc) continue;
rc = mdb_stat(txn, db2, &mst);
if (rc) {
fprintf(stderr, "mdb_stat failed, error %d %s\n", rc, mdb_strerror(rc));
goto txn_abort;
}
prstat(&mst);
mdb_close(env, db2);
}
mdb_cursor_close(cursor);
}
if (rc == MDB_NOTFOUND)
rc = MDB_SUCCESS;
mdb_close(env, dbi);
txn_abort:
mdb_txn_abort(txn);
env_close:
mdb_env_close(env);
return rc ? EXIT_FAILURE : EXIT_SUCCESS;
}

358
deps/liblmdb/midl.c vendored Normal file
View File

@ -0,0 +1,358 @@
/** @file midl.c
* @brief ldap bdb back-end ID List functions */
/* $OpenLDAP$ */
/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
*
* Copyright 2000-2015 The OpenLDAP Foundation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
#include <limits.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include "midl.h"
/** @defgroup internal LMDB Internals
* @{
*/
/** @defgroup idls ID List Management
* @{
*/
#define CMP(x,y) ( (x) < (y) ? -1 : (x) > (y) )
unsigned mdb_midl_search( MDB_IDL ids, MDB_ID id )
{
/*
* binary search of id in ids
* if found, returns position of id
* if not found, returns first position greater than id
*/
unsigned base = 0;
unsigned cursor = 1;
int val = 0;
unsigned n = ids[0];
while( 0 < n ) {
unsigned pivot = n >> 1;
cursor = base + pivot + 1;
val = CMP( ids[cursor], id );
if( val < 0 ) {
n = pivot;
} else if ( val > 0 ) {
base = cursor;
n -= pivot + 1;
} else {
return cursor;
}
}
if( val > 0 ) {
++cursor;
}
return cursor;
}
#if 0 /* superseded by append/sort */
int mdb_midl_insert( MDB_IDL ids, MDB_ID id )
{
unsigned x, i;
x = mdb_midl_search( ids, id );
assert( x > 0 );
if( x < 1 ) {
/* internal error */
return -2;
}
if ( x <= ids[0] && ids[x] == id ) {
/* duplicate */
assert(0);
return -1;
}
if ( ++ids[0] >= MDB_IDL_DB_MAX ) {
/* no room */
--ids[0];
return -2;
} else {
/* insert id */
for (i=ids[0]; i>x; i--)
ids[i] = ids[i-1];
ids[x] = id;
}
return 0;
}
#endif
MDB_IDL mdb_midl_alloc(int num)
{
MDB_IDL ids = malloc((num+2) * sizeof(MDB_ID));
if (ids) {
*ids++ = num;
*ids = 0;
}
return ids;
}
void mdb_midl_free(MDB_IDL ids)
{
if (ids)
free(ids-1);
}
void mdb_midl_shrink( MDB_IDL *idp )
{
MDB_IDL ids = *idp;
if (*(--ids) > MDB_IDL_UM_MAX &&
(ids = realloc(ids, (MDB_IDL_UM_MAX+1) * sizeof(MDB_ID))))
{
*ids++ = MDB_IDL_UM_MAX;
*idp = ids;
}
}
static int mdb_midl_grow( MDB_IDL *idp, int num )
{
MDB_IDL idn = *idp-1;
/* grow it */
idn = realloc(idn, (*idn + num + 2) * sizeof(MDB_ID));
if (!idn)
return ENOMEM;
*idn++ += num;
*idp = idn;
return 0;
}
int mdb_midl_need( MDB_IDL *idp, unsigned num )
{
MDB_IDL ids = *idp;
num += ids[0];
if (num > ids[-1]) {
num = (num + num/4 + (256 + 2)) & -256;
if (!(ids = realloc(ids-1, num * sizeof(MDB_ID))))
return ENOMEM;
*ids++ = num - 2;
*idp = ids;
}
return 0;
}
int mdb_midl_append( MDB_IDL *idp, MDB_ID id )
{
MDB_IDL ids = *idp;
/* Too big? */
if (ids[0] >= ids[-1]) {
if (mdb_midl_grow(idp, MDB_IDL_UM_MAX))
return ENOMEM;
ids = *idp;
}
ids[0]++;
ids[ids[0]] = id;
return 0;
}
int mdb_midl_append_list( MDB_IDL *idp, MDB_IDL app )
{
MDB_IDL ids = *idp;
/* Too big? */
if (ids[0] + app[0] >= ids[-1]) {
if (mdb_midl_grow(idp, app[0]))
return ENOMEM;
ids = *idp;
}
memcpy(&ids[ids[0]+1], &app[1], app[0] * sizeof(MDB_ID));
ids[0] += app[0];
return 0;
}
int mdb_midl_append_range( MDB_IDL *idp, MDB_ID id, unsigned n )
{
MDB_ID *ids = *idp, len = ids[0];
/* Too big? */
if (len + n > ids[-1]) {
if (mdb_midl_grow(idp, n | MDB_IDL_UM_MAX))
return ENOMEM;
ids = *idp;
}
ids[0] = len + n;
ids += len;
while (n)
ids[n--] = id++;
return 0;
}
void mdb_midl_xmerge( MDB_IDL idl, MDB_IDL merge )
{
MDB_ID old_id, merge_id, i = merge[0], j = idl[0], k = i+j, total = k;
idl[0] = (MDB_ID)-1; /* delimiter for idl scan below */
old_id = idl[j];
while (i) {
merge_id = merge[i--];
for (; old_id < merge_id; old_id = idl[--j])
idl[k--] = old_id;
idl[k--] = merge_id;
}
idl[0] = total;
}
/* Quicksort + Insertion sort for small arrays */
#define SMALL 8
#define MIDL_SWAP(a,b) { itmp=(a); (a)=(b); (b)=itmp; }
void
mdb_midl_sort( MDB_IDL ids )
{
/* Max possible depth of int-indexed tree * 2 items/level */
int istack[sizeof(int)*CHAR_BIT * 2];
int i,j,k,l,ir,jstack;
MDB_ID a, itmp;
ir = (int)ids[0];
l = 1;
jstack = 0;
for(;;) {
if (ir - l < SMALL) { /* Insertion sort */
for (j=l+1;j<=ir;j++) {
a = ids[j];
for (i=j-1;i>=1;i--) {
if (ids[i] >= a) break;
ids[i+1] = ids[i];
}
ids[i+1] = a;
}
if (jstack == 0) break;
ir = istack[jstack--];
l = istack[jstack--];
} else {
k = (l + ir) >> 1; /* Choose median of left, center, right */
MIDL_SWAP(ids[k], ids[l+1]);
if (ids[l] < ids[ir]) {
MIDL_SWAP(ids[l], ids[ir]);
}
if (ids[l+1] < ids[ir]) {
MIDL_SWAP(ids[l+1], ids[ir]);
}
if (ids[l] < ids[l+1]) {
MIDL_SWAP(ids[l], ids[l+1]);
}
i = l+1;
j = ir;
a = ids[l+1];
for(;;) {
do i++; while(ids[i] > a);
do j--; while(ids[j] < a);
if (j < i) break;
MIDL_SWAP(ids[i],ids[j]);
}
ids[l+1] = ids[j];
ids[j] = a;
jstack += 2;
if (ir-i+1 >= j-l) {
istack[jstack] = ir;
istack[jstack-1] = i;
ir = j-1;
} else {
istack[jstack] = j-1;
istack[jstack-1] = l;
l = i;
}
}
}
}
unsigned mdb_mid2l_search( MDB_ID2L ids, MDB_ID id )
{
/*
* binary search of id in ids
* if found, returns position of id
* if not found, returns first position greater than id
*/
unsigned base = 0;
unsigned cursor = 1;
int val = 0;
unsigned n = (unsigned)ids[0].mid;
while( 0 < n ) {
unsigned pivot = n >> 1;
cursor = base + pivot + 1;
val = CMP( id, ids[cursor].mid );
if( val < 0 ) {
n = pivot;
} else if ( val > 0 ) {
base = cursor;
n -= pivot + 1;
} else {
return cursor;
}
}
if( val > 0 ) {
++cursor;
}
return cursor;
}
int mdb_mid2l_insert( MDB_ID2L ids, MDB_ID2 *id )
{
unsigned x, i;
x = mdb_mid2l_search( ids, id->mid );
if( x < 1 ) {
/* internal error */
return -2;
}
if ( x <= ids[0].mid && ids[x].mid == id->mid ) {
/* duplicate */
return -1;
}
if ( ids[0].mid >= MDB_IDL_UM_MAX ) {
/* too big */
return -2;
} else {
/* insert id */
ids[0].mid++;
for (i=(unsigned)ids[0].mid; i>x; i--)
ids[i] = ids[i-1];
ids[x] = *id;
}
return 0;
}
int mdb_mid2l_append( MDB_ID2L ids, MDB_ID2 *id )
{
/* Too big? */
if (ids[0].mid >= MDB_IDL_UM_MAX) {
return -2;
}
ids[0].mid++;
ids[ids[0].mid] = *id;
return 0;
}
/** @} */
/** @} */

185
deps/liblmdb/midl.h vendored Normal file
View File

@ -0,0 +1,185 @@
/** @file midl.h
* @brief LMDB ID List header file.
*
* This file was originally part of back-bdb but has been
* modified for use in libmdb. Most of the macros defined
* in this file are unused, just left over from the original.
*
* This file is only used internally in libmdb and its definitions
* are not exposed publicly.
*/
/* $OpenLDAP$ */
/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
*
* Copyright 2000-2015 The OpenLDAP Foundation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
#ifndef _MDB_MIDL_H_
#define _MDB_MIDL_H_
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @defgroup internal LMDB Internals
* @{
*/
/** @defgroup idls ID List Management
* @{
*/
/** A generic unsigned ID number. These were entryIDs in back-bdb.
* Preferably it should have the same size as a pointer.
*/
typedef size_t MDB_ID;
/** An IDL is an ID List, a sorted array of IDs. The first
* element of the array is a counter for how many actual
* IDs are in the list. In the original back-bdb code, IDLs are
* sorted in ascending order. For libmdb IDLs are sorted in
* descending order.
*/
typedef MDB_ID *MDB_IDL;
/* IDL sizes - likely should be even bigger
* limiting factors: sizeof(ID), thread stack size
*/
#define MDB_IDL_LOGN 16 /* DB_SIZE is 2^16, UM_SIZE is 2^17 */
#define MDB_IDL_DB_SIZE (1<<MDB_IDL_LOGN)
#define MDB_IDL_UM_SIZE (1<<(MDB_IDL_LOGN+1))
#define MDB_IDL_DB_MAX (MDB_IDL_DB_SIZE-1)
#define MDB_IDL_UM_MAX (MDB_IDL_UM_SIZE-1)
#define MDB_IDL_SIZEOF(ids) (((ids)[0]+1) * sizeof(MDB_ID))
#define MDB_IDL_IS_ZERO(ids) ( (ids)[0] == 0 )
#define MDB_IDL_CPY( dst, src ) (memcpy( dst, src, MDB_IDL_SIZEOF( src ) ))
#define MDB_IDL_FIRST( ids ) ( (ids)[1] )
#define MDB_IDL_LAST( ids ) ( (ids)[(ids)[0]] )
/** Current max length of an #mdb_midl_alloc()ed IDL */
#define MDB_IDL_ALLOCLEN( ids ) ( (ids)[-1] )
/** Append ID to IDL. The IDL must be big enough. */
#define mdb_midl_xappend(idl, id) do { \
MDB_ID *xidl = (idl), xlen = ++(xidl[0]); \
xidl[xlen] = (id); \
} while (0)
/** Search for an ID in an IDL.
* @param[in] ids The IDL to search.
* @param[in] id The ID to search for.
* @return The index of the first ID greater than or equal to \b id.
*/
unsigned mdb_midl_search( MDB_IDL ids, MDB_ID id );
/** Allocate an IDL.
* Allocates memory for an IDL of the given size.
* @return IDL on success, NULL on failure.
*/
MDB_IDL mdb_midl_alloc(int num);
/** Free an IDL.
* @param[in] ids The IDL to free.
*/
void mdb_midl_free(MDB_IDL ids);
/** Shrink an IDL.
* Return the IDL to the default size if it has grown larger.
* @param[in,out] idp Address of the IDL to shrink.
*/
void mdb_midl_shrink(MDB_IDL *idp);
/** Make room for num additional elements in an IDL.
* @param[in,out] idp Address of the IDL.
* @param[in] num Number of elements to make room for.
* @return 0 on success, ENOMEM on failure.
*/
int mdb_midl_need(MDB_IDL *idp, unsigned num);
/** Append an ID onto an IDL.
* @param[in,out] idp Address of the IDL to append to.
* @param[in] id The ID to append.
* @return 0 on success, ENOMEM if the IDL is too large.
*/
int mdb_midl_append( MDB_IDL *idp, MDB_ID id );
/** Append an IDL onto an IDL.
* @param[in,out] idp Address of the IDL to append to.
* @param[in] app The IDL to append.
* @return 0 on success, ENOMEM if the IDL is too large.
*/
int mdb_midl_append_list( MDB_IDL *idp, MDB_IDL app );
/** Append an ID range onto an IDL.
* @param[in,out] idp Address of the IDL to append to.
* @param[in] id The lowest ID to append.
* @param[in] n Number of IDs to append.
* @return 0 on success, ENOMEM if the IDL is too large.
*/
int mdb_midl_append_range( MDB_IDL *idp, MDB_ID id, unsigned n );
/** Merge an IDL onto an IDL. The destination IDL must be big enough.
* @param[in] idl The IDL to merge into.
* @param[in] merge The IDL to merge.
*/
void mdb_midl_xmerge( MDB_IDL idl, MDB_IDL merge );
/** Sort an IDL.
* @param[in,out] ids The IDL to sort.
*/
void mdb_midl_sort( MDB_IDL ids );
/** An ID2 is an ID/pointer pair.
*/
typedef struct MDB_ID2 {
MDB_ID mid; /**< The ID */
void *mptr; /**< The pointer */
} MDB_ID2;
/** An ID2L is an ID2 List, a sorted array of ID2s.
* The first element's \b mid member is a count of how many actual
* elements are in the array. The \b mptr member of the first element is unused.
* The array is sorted in ascending order by \b mid.
*/
typedef MDB_ID2 *MDB_ID2L;
/** Search for an ID in an ID2L.
* @param[in] ids The ID2L to search.
* @param[in] id The ID to search for.
* @return The index of the first ID2 whose \b mid member is greater than or equal to \b id.
*/
unsigned mdb_mid2l_search( MDB_ID2L ids, MDB_ID id );
/** Insert an ID2 into a ID2L.
* @param[in,out] ids The ID2L to insert into.
* @param[in] id The ID2 to insert.
* @return 0 on success, -1 if the ID was already present in the ID2L.
*/
int mdb_mid2l_insert( MDB_ID2L ids, MDB_ID2 *id );
/** Append an ID2 into a ID2L.
* @param[in,out] ids The ID2L to append into.
* @param[in] id The ID2 to append.
* @return 0 on success, -2 if the ID2L is too big.
*/
int mdb_mid2l_append( MDB_ID2L ids, MDB_ID2 *id );
/** @} */
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* _MDB_MIDL_H_ */

177
deps/liblmdb/mtest.c vendored Normal file
View File

@ -0,0 +1,177 @@
/* mtest.c - memory-mapped database tester/toy */
/*
* Copyright 2011-2015 Howard Chu, Symas Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "lmdb.h"
#define E(expr) CHECK((rc = (expr)) == MDB_SUCCESS, #expr)
#define RES(err, expr) ((rc = expr) == (err) || (CHECK(!rc, #expr), 0))
#define CHECK(test, msg) ((test) ? (void)0 : ((void)fprintf(stderr, \
"%s:%d: %s: %s\n", __FILE__, __LINE__, msg, mdb_strerror(rc)), abort()))
int main(int argc,char * argv[])
{
int i = 0, j = 0, rc;
MDB_env *env;
MDB_dbi dbi;
MDB_val key, data;
MDB_txn *txn;
MDB_stat mst;
MDB_cursor *cursor, *cur2;
MDB_cursor_op op;
int count;
int *values;
char sval[32] = "";
srand(time(NULL));
count = (rand()%384) + 64;
values = (int *)malloc(count*sizeof(int));
for(i = 0;i<count;i++) {
values[i] = rand()%1024;
}
E(mdb_env_create(&env));
E(mdb_env_set_maxreaders(env, 1));
E(mdb_env_set_mapsize(env, 10485760));
E(mdb_env_open(env, "./testdb", MDB_FIXEDMAP /*|MDB_NOSYNC*/, 0664));
E(mdb_txn_begin(env, NULL, 0, &txn));
E(mdb_dbi_open(txn, NULL, 0, &dbi));
key.mv_size = sizeof(int);
key.mv_data = sval;
printf("Adding %d values\n", count);
for (i=0;i<count;i++) {
sprintf(sval, "%03x %d foo bar", values[i], values[i]);
/* Set <data> in each iteration, since MDB_NOOVERWRITE may modify it */
data.mv_size = sizeof(sval);
data.mv_data = sval;
if (RES(MDB_KEYEXIST, mdb_put(txn, dbi, &key, &data, MDB_NOOVERWRITE))) {
j++;
data.mv_size = sizeof(sval);
data.mv_data = sval;
}
}
if (j) printf("%d duplicates skipped\n", j);
E(mdb_txn_commit(txn));
E(mdb_env_stat(env, &mst));
E(mdb_txn_begin(env, NULL, MDB_RDONLY, &txn));
E(mdb_cursor_open(txn, dbi, &cursor));
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
printf("key: %p %.*s, data: %p %.*s\n",
key.mv_data, (int) key.mv_size, (char *) key.mv_data,
data.mv_data, (int) data.mv_size, (char *) data.mv_data);
}
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
mdb_cursor_close(cursor);
mdb_txn_abort(txn);
j=0;
key.mv_data = sval;
for (i= count - 1; i > -1; i-= (rand()%5)) {
j++;
txn=NULL;
E(mdb_txn_begin(env, NULL, 0, &txn));
sprintf(sval, "%03x ", values[i]);
if (RES(MDB_NOTFOUND, mdb_del(txn, dbi, &key, NULL))) {
j--;
mdb_txn_abort(txn);
} else {
E(mdb_txn_commit(txn));
}
}
free(values);
printf("Deleted %d values\n", j);
E(mdb_env_stat(env, &mst));
E(mdb_txn_begin(env, NULL, MDB_RDONLY, &txn));
E(mdb_cursor_open(txn, dbi, &cursor));
printf("Cursor next\n");
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
printf("key: %.*s, data: %.*s\n",
(int) key.mv_size, (char *) key.mv_data,
(int) data.mv_size, (char *) data.mv_data);
}
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
printf("Cursor last\n");
E(mdb_cursor_get(cursor, &key, &data, MDB_LAST));
printf("key: %.*s, data: %.*s\n",
(int) key.mv_size, (char *) key.mv_data,
(int) data.mv_size, (char *) data.mv_data);
printf("Cursor prev\n");
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_PREV)) == 0) {
printf("key: %.*s, data: %.*s\n",
(int) key.mv_size, (char *) key.mv_data,
(int) data.mv_size, (char *) data.mv_data);
}
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
printf("Cursor last/prev\n");
E(mdb_cursor_get(cursor, &key, &data, MDB_LAST));
printf("key: %.*s, data: %.*s\n",
(int) key.mv_size, (char *) key.mv_data,
(int) data.mv_size, (char *) data.mv_data);
E(mdb_cursor_get(cursor, &key, &data, MDB_PREV));
printf("key: %.*s, data: %.*s\n",
(int) key.mv_size, (char *) key.mv_data,
(int) data.mv_size, (char *) data.mv_data);
mdb_cursor_close(cursor);
mdb_txn_abort(txn);
printf("Deleting with cursor\n");
E(mdb_txn_begin(env, NULL, 0, &txn));
E(mdb_cursor_open(txn, dbi, &cur2));
for (i=0; i<50; i++) {
if (RES(MDB_NOTFOUND, mdb_cursor_get(cur2, &key, &data, MDB_NEXT)))
break;
printf("key: %p %.*s, data: %p %.*s\n",
key.mv_data, (int) key.mv_size, (char *) key.mv_data,
data.mv_data, (int) data.mv_size, (char *) data.mv_data);
E(mdb_del(txn, dbi, &key, NULL));
}
printf("Restarting cursor in txn\n");
for (op=MDB_FIRST, i=0; i<=32; op=MDB_NEXT, i++) {
if (RES(MDB_NOTFOUND, mdb_cursor_get(cur2, &key, &data, op)))
break;
printf("key: %p %.*s, data: %p %.*s\n",
key.mv_data, (int) key.mv_size, (char *) key.mv_data,
data.mv_data, (int) data.mv_size, (char *) data.mv_data);
}
mdb_cursor_close(cur2);
E(mdb_txn_commit(txn));
printf("Restarting cursor outside txn\n");
E(mdb_txn_begin(env, NULL, 0, &txn));
E(mdb_cursor_open(txn, dbi, &cursor));
for (op=MDB_FIRST, i=0; i<=32; op=MDB_NEXT, i++) {
if (RES(MDB_NOTFOUND, mdb_cursor_get(cursor, &key, &data, op)))
break;
printf("key: %p %.*s, data: %p %.*s\n",
key.mv_data, (int) key.mv_size, (char *) key.mv_data,
data.mv_data, (int) data.mv_size, (char *) data.mv_data);
}
mdb_cursor_close(cursor);
mdb_txn_abort(txn);
mdb_dbi_close(env, dbi);
mdb_env_close(env);
return 0;
}

124
deps/liblmdb/mtest2.c vendored Normal file
View File

@ -0,0 +1,124 @@
/* mtest2.c - memory-mapped database tester/toy */
/*
* Copyright 2011-2015 Howard Chu, Symas Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
/* Just like mtest.c, but using a subDB instead of the main DB */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "lmdb.h"
#define E(expr) CHECK((rc = (expr)) == MDB_SUCCESS, #expr)
#define RES(err, expr) ((rc = expr) == (err) || (CHECK(!rc, #expr), 0))
#define CHECK(test, msg) ((test) ? (void)0 : ((void)fprintf(stderr, \
"%s:%d: %s: %s\n", __FILE__, __LINE__, msg, mdb_strerror(rc)), abort()))
int main(int argc,char * argv[])
{
int i = 0, j = 0, rc;
MDB_env *env;
MDB_dbi dbi;
MDB_val key, data;
MDB_txn *txn;
MDB_stat mst;
MDB_cursor *cursor;
int count;
int *values;
char sval[32] = "";
srand(time(NULL));
count = (rand()%384) + 64;
values = (int *)malloc(count*sizeof(int));
for(i = 0;i<count;i++) {
values[i] = rand()%1024;
}
E(mdb_env_create(&env));
E(mdb_env_set_maxreaders(env, 1));
E(mdb_env_set_mapsize(env, 10485760));
E(mdb_env_set_maxdbs(env, 4));
E(mdb_env_open(env, "./testdb", MDB_FIXEDMAP|MDB_NOSYNC, 0664));
E(mdb_txn_begin(env, NULL, 0, &txn));
E(mdb_dbi_open(txn, "id1", MDB_CREATE, &dbi));
key.mv_size = sizeof(int);
key.mv_data = sval;
printf("Adding %d values\n", count);
for (i=0;i<count;i++) {
sprintf(sval, "%03x %d foo bar", values[i], values[i]);
data.mv_size = sizeof(sval);
data.mv_data = sval;
if (RES(MDB_KEYEXIST, mdb_put(txn, dbi, &key, &data, MDB_NOOVERWRITE)))
j++;
}
if (j) printf("%d duplicates skipped\n", j);
E(mdb_txn_commit(txn));
E(mdb_env_stat(env, &mst));
E(mdb_txn_begin(env, NULL, MDB_RDONLY, &txn));
E(mdb_cursor_open(txn, dbi, &cursor));
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
printf("key: %p %.*s, data: %p %.*s\n",
key.mv_data, (int) key.mv_size, (char *) key.mv_data,
data.mv_data, (int) data.mv_size, (char *) data.mv_data);
}
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
mdb_cursor_close(cursor);
mdb_txn_abort(txn);
j=0;
key.mv_data = sval;
for (i= count - 1; i > -1; i-= (rand()%5)) {
j++;
txn=NULL;
E(mdb_txn_begin(env, NULL, 0, &txn));
sprintf(sval, "%03x ", values[i]);
if (RES(MDB_NOTFOUND, mdb_del(txn, dbi, &key, NULL))) {
j--;
mdb_txn_abort(txn);
} else {
E(mdb_txn_commit(txn));
}
}
free(values);
printf("Deleted %d values\n", j);
E(mdb_env_stat(env, &mst));
E(mdb_txn_begin(env, NULL, MDB_RDONLY, &txn));
E(mdb_cursor_open(txn, dbi, &cursor));
printf("Cursor next\n");
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
printf("key: %.*s, data: %.*s\n",
(int) key.mv_size, (char *) key.mv_data,
(int) data.mv_size, (char *) data.mv_data);
}
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
printf("Cursor prev\n");
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_PREV)) == 0) {
printf("key: %.*s, data: %.*s\n",
(int) key.mv_size, (char *) key.mv_data,
(int) data.mv_size, (char *) data.mv_data);
}
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
mdb_cursor_close(cursor);
mdb_txn_abort(txn);
mdb_dbi_close(env, dbi);
mdb_env_close(env);
return 0;
}

133
deps/liblmdb/mtest3.c vendored Normal file
View File

@ -0,0 +1,133 @@
/* mtest3.c - memory-mapped database tester/toy */
/*
* Copyright 2011-2015 Howard Chu, Symas Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
/* Tests for sorted duplicate DBs */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "lmdb.h"
#define E(expr) CHECK((rc = (expr)) == MDB_SUCCESS, #expr)
#define RES(err, expr) ((rc = expr) == (err) || (CHECK(!rc, #expr), 0))
#define CHECK(test, msg) ((test) ? (void)0 : ((void)fprintf(stderr, \
"%s:%d: %s: %s\n", __FILE__, __LINE__, msg, mdb_strerror(rc)), abort()))
int main(int argc,char * argv[])
{
int i = 0, j = 0, rc;
MDB_env *env;
MDB_dbi dbi;
MDB_val key, data;
MDB_txn *txn;
MDB_stat mst;
MDB_cursor *cursor;
int count;
int *values;
char sval[32];
char kval[sizeof(int)];
srand(time(NULL));
memset(sval, 0, sizeof(sval));
count = (rand()%384) + 64;
values = (int *)malloc(count*sizeof(int));
for(i = 0;i<count;i++) {
values[i] = rand()%1024;
}
E(mdb_env_create(&env));
E(mdb_env_set_mapsize(env, 10485760));
E(mdb_env_set_maxdbs(env, 4));
E(mdb_env_open(env, "./testdb", MDB_FIXEDMAP|MDB_NOSYNC, 0664));
E(mdb_txn_begin(env, NULL, 0, &txn));
E(mdb_dbi_open(txn, "id2", MDB_CREATE|MDB_DUPSORT, &dbi));
key.mv_size = sizeof(int);
key.mv_data = kval;
data.mv_size = sizeof(sval);
data.mv_data = sval;
printf("Adding %d values\n", count);
for (i=0;i<count;i++) {
if (!(i & 0x0f))
sprintf(kval, "%03x", values[i]);
sprintf(sval, "%03x %d foo bar", values[i], values[i]);
if (RES(MDB_KEYEXIST, mdb_put(txn, dbi, &key, &data, MDB_NODUPDATA)))
j++;
}
if (j) printf("%d duplicates skipped\n", j);
E(mdb_txn_commit(txn));
E(mdb_env_stat(env, &mst));
E(mdb_txn_begin(env, NULL, MDB_RDONLY, &txn));
E(mdb_cursor_open(txn, dbi, &cursor));
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
printf("key: %p %.*s, data: %p %.*s\n",
key.mv_data, (int) key.mv_size, (char *) key.mv_data,
data.mv_data, (int) data.mv_size, (char *) data.mv_data);
}
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
mdb_cursor_close(cursor);
mdb_txn_abort(txn);
j=0;
for (i= count - 1; i > -1; i-= (rand()%5)) {
j++;
txn=NULL;
E(mdb_txn_begin(env, NULL, 0, &txn));
sprintf(kval, "%03x", values[i & ~0x0f]);
sprintf(sval, "%03x %d foo bar", values[i], values[i]);
key.mv_size = sizeof(int);
key.mv_data = kval;
data.mv_size = sizeof(sval);
data.mv_data = sval;
if (RES(MDB_NOTFOUND, mdb_del(txn, dbi, &key, &data))) {
j--;
mdb_txn_abort(txn);
} else {
E(mdb_txn_commit(txn));
}
}
free(values);
printf("Deleted %d values\n", j);
E(mdb_env_stat(env, &mst));
E(mdb_txn_begin(env, NULL, MDB_RDONLY, &txn));
E(mdb_cursor_open(txn, dbi, &cursor));
printf("Cursor next\n");
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
printf("key: %.*s, data: %.*s\n",
(int) key.mv_size, (char *) key.mv_data,
(int) data.mv_size, (char *) data.mv_data);
}
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
printf("Cursor prev\n");
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_PREV)) == 0) {
printf("key: %.*s, data: %.*s\n",
(int) key.mv_size, (char *) key.mv_data,
(int) data.mv_size, (char *) data.mv_data);
}
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
mdb_cursor_close(cursor);
mdb_txn_abort(txn);
mdb_dbi_close(env, dbi);
mdb_env_close(env);
return 0;
}

168
deps/liblmdb/mtest4.c vendored Normal file
View File

@ -0,0 +1,168 @@
/* mtest4.c - memory-mapped database tester/toy */
/*
* Copyright 2011-2015 Howard Chu, Symas Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
/* Tests for sorted duplicate DBs with fixed-size keys */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "lmdb.h"
#define E(expr) CHECK((rc = (expr)) == MDB_SUCCESS, #expr)
#define RES(err, expr) ((rc = expr) == (err) || (CHECK(!rc, #expr), 0))
#define CHECK(test, msg) ((test) ? (void)0 : ((void)fprintf(stderr, \
"%s:%d: %s: %s\n", __FILE__, __LINE__, msg, mdb_strerror(rc)), abort()))
int main(int argc,char * argv[])
{
int i = 0, j = 0, rc;
MDB_env *env;
MDB_dbi dbi;
MDB_val key, data;
MDB_txn *txn;
MDB_stat mst;
MDB_cursor *cursor;
int count;
int *values;
char sval[8];
char kval[sizeof(int)];
memset(sval, 0, sizeof(sval));
count = 510;
values = (int *)malloc(count*sizeof(int));
for(i = 0;i<count;i++) {
values[i] = i*5;
}
E(mdb_env_create(&env));
E(mdb_env_set_mapsize(env, 10485760));
E(mdb_env_set_maxdbs(env, 4));
E(mdb_env_open(env, "./testdb", MDB_FIXEDMAP|MDB_NOSYNC, 0664));
E(mdb_txn_begin(env, NULL, 0, &txn));
E(mdb_dbi_open(txn, "id4", MDB_CREATE|MDB_DUPSORT|MDB_DUPFIXED, &dbi));
key.mv_size = sizeof(int);
key.mv_data = kval;
data.mv_size = sizeof(sval);
data.mv_data = sval;
printf("Adding %d values\n", count);
strcpy(kval, "001");
for (i=0;i<count;i++) {
sprintf(sval, "%07x", values[i]);
if (RES(MDB_KEYEXIST, mdb_put(txn, dbi, &key, &data, MDB_NODUPDATA)))
j++;
}
if (j) printf("%d duplicates skipped\n", j);
E(mdb_txn_commit(txn));
E(mdb_env_stat(env, &mst));
/* there should be one full page of dups now.
*/
E(mdb_txn_begin(env, NULL, MDB_RDONLY, &txn));
E(mdb_cursor_open(txn, dbi, &cursor));
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
printf("key: %p %.*s, data: %p %.*s\n",
key.mv_data, (int) key.mv_size, (char *) key.mv_data,
data.mv_data, (int) data.mv_size, (char *) data.mv_data);
}
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
mdb_cursor_close(cursor);
mdb_txn_abort(txn);
/* test all 3 branches of split code:
* 1: new key in lower half
* 2: new key at split point
* 3: new key in upper half
*/
key.mv_size = sizeof(int);
key.mv_data = kval;
data.mv_size = sizeof(sval);
data.mv_data = sval;
sprintf(sval, "%07x", values[3]+1);
E(mdb_txn_begin(env, NULL, 0, &txn));
(void)RES(MDB_KEYEXIST, mdb_put(txn, dbi, &key, &data, MDB_NODUPDATA));
mdb_txn_abort(txn);
sprintf(sval, "%07x", values[255]+1);
E(mdb_txn_begin(env, NULL, 0, &txn));
(void)RES(MDB_KEYEXIST, mdb_put(txn, dbi, &key, &data, MDB_NODUPDATA));
mdb_txn_abort(txn);
sprintf(sval, "%07x", values[500]+1);
E(mdb_txn_begin(env, NULL, 0, &txn));
(void)RES(MDB_KEYEXIST, mdb_put(txn, dbi, &key, &data, MDB_NODUPDATA));
E(mdb_txn_commit(txn));
/* Try MDB_NEXT_MULTIPLE */
E(mdb_txn_begin(env, NULL, 0, &txn));
E(mdb_cursor_open(txn, dbi, &cursor));
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT_MULTIPLE)) == 0) {
printf("key: %.*s, data: %.*s\n",
(int) key.mv_size, (char *) key.mv_data,
(int) data.mv_size, (char *) data.mv_data);
}
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
mdb_cursor_close(cursor);
mdb_txn_abort(txn);
j=0;
for (i= count - 1; i > -1; i-= (rand()%3)) {
j++;
txn=NULL;
E(mdb_txn_begin(env, NULL, 0, &txn));
sprintf(sval, "%07x", values[i]);
key.mv_size = sizeof(int);
key.mv_data = kval;
data.mv_size = sizeof(sval);
data.mv_data = sval;
if (RES(MDB_NOTFOUND, mdb_del(txn, dbi, &key, &data))) {
j--;
mdb_txn_abort(txn);
} else {
E(mdb_txn_commit(txn));
}
}
free(values);
printf("Deleted %d values\n", j);
E(mdb_env_stat(env, &mst));
E(mdb_txn_begin(env, NULL, MDB_RDONLY, &txn));
E(mdb_cursor_open(txn, dbi, &cursor));
printf("Cursor next\n");
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
printf("key: %.*s, data: %.*s\n",
(int) key.mv_size, (char *) key.mv_data,
(int) data.mv_size, (char *) data.mv_data);
}
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
printf("Cursor prev\n");
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_PREV)) == 0) {
printf("key: %.*s, data: %.*s\n",
(int) key.mv_size, (char *) key.mv_data,
(int) data.mv_size, (char *) data.mv_data);
}
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
mdb_cursor_close(cursor);
mdb_txn_abort(txn);
mdb_dbi_close(env, dbi);
mdb_env_close(env);
return 0;
}

135
deps/liblmdb/mtest5.c vendored Normal file
View File

@ -0,0 +1,135 @@
/* mtest5.c - memory-mapped database tester/toy */
/*
* Copyright 2011-2015 Howard Chu, Symas Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
/* Tests for sorted duplicate DBs using cursor_put */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "lmdb.h"
#define E(expr) CHECK((rc = (expr)) == MDB_SUCCESS, #expr)
#define RES(err, expr) ((rc = expr) == (err) || (CHECK(!rc, #expr), 0))
#define CHECK(test, msg) ((test) ? (void)0 : ((void)fprintf(stderr, \
"%s:%d: %s: %s\n", __FILE__, __LINE__, msg, mdb_strerror(rc)), abort()))
int main(int argc,char * argv[])
{
int i = 0, j = 0, rc;
MDB_env *env;
MDB_dbi dbi;
MDB_val key, data;
MDB_txn *txn;
MDB_stat mst;
MDB_cursor *cursor;
int count;
int *values;
char sval[32];
char kval[sizeof(int)];
srand(time(NULL));
memset(sval, 0, sizeof(sval));
count = (rand()%384) + 64;
values = (int *)malloc(count*sizeof(int));
for(i = 0;i<count;i++) {
values[i] = rand()%1024;
}
E(mdb_env_create(&env));
E(mdb_env_set_mapsize(env, 10485760));
E(mdb_env_set_maxdbs(env, 4));
E(mdb_env_open(env, "./testdb", MDB_FIXEDMAP|MDB_NOSYNC, 0664));
E(mdb_txn_begin(env, NULL, 0, &txn));
E(mdb_dbi_open(txn, "id2", MDB_CREATE|MDB_DUPSORT, &dbi));
E(mdb_cursor_open(txn, dbi, &cursor));
key.mv_size = sizeof(int);
key.mv_data = kval;
data.mv_size = sizeof(sval);
data.mv_data = sval;
printf("Adding %d values\n", count);
for (i=0;i<count;i++) {
if (!(i & 0x0f))
sprintf(kval, "%03x", values[i]);
sprintf(sval, "%03x %d foo bar", values[i], values[i]);
if (RES(MDB_KEYEXIST, mdb_cursor_put(cursor, &key, &data, MDB_NODUPDATA)))
j++;
}
if (j) printf("%d duplicates skipped\n", j);
mdb_cursor_close(cursor);
E(mdb_txn_commit(txn));
E(mdb_env_stat(env, &mst));
E(mdb_txn_begin(env, NULL, MDB_RDONLY, &txn));
E(mdb_cursor_open(txn, dbi, &cursor));
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
printf("key: %p %.*s, data: %p %.*s\n",
key.mv_data, (int) key.mv_size, (char *) key.mv_data,
data.mv_data, (int) data.mv_size, (char *) data.mv_data);
}
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
mdb_cursor_close(cursor);
mdb_txn_abort(txn);
j=0;
for (i= count - 1; i > -1; i-= (rand()%5)) {
j++;
txn=NULL;
E(mdb_txn_begin(env, NULL, 0, &txn));
sprintf(kval, "%03x", values[i & ~0x0f]);
sprintf(sval, "%03x %d foo bar", values[i], values[i]);
key.mv_size = sizeof(int);
key.mv_data = kval;
data.mv_size = sizeof(sval);
data.mv_data = sval;
if (RES(MDB_NOTFOUND, mdb_del(txn, dbi, &key, &data))) {
j--;
mdb_txn_abort(txn);
} else {
E(mdb_txn_commit(txn));
}
}
free(values);
printf("Deleted %d values\n", j);
E(mdb_env_stat(env, &mst));
E(mdb_txn_begin(env, NULL, MDB_RDONLY, &txn));
E(mdb_cursor_open(txn, dbi, &cursor));
printf("Cursor next\n");
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
printf("key: %.*s, data: %.*s\n",
(int) key.mv_size, (char *) key.mv_data,
(int) data.mv_size, (char *) data.mv_data);
}
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
printf("Cursor prev\n");
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_PREV)) == 0) {
printf("key: %.*s, data: %.*s\n",
(int) key.mv_size, (char *) key.mv_data,
(int) data.mv_size, (char *) data.mv_data);
}
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
mdb_cursor_close(cursor);
mdb_txn_abort(txn);
mdb_dbi_close(env, dbi);
mdb_env_close(env);
return 0;
}

141
deps/liblmdb/mtest6.c vendored Normal file
View File

@ -0,0 +1,141 @@
/* mtest6.c - memory-mapped database tester/toy */
/*
* Copyright 2011-2015 Howard Chu, Symas Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
/* Tests for DB splits and merges */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "lmdb.h"
#define E(expr) CHECK((rc = (expr)) == MDB_SUCCESS, #expr)
#define RES(err, expr) ((rc = expr) == (err) || (CHECK(!rc, #expr), 0))
#define CHECK(test, msg) ((test) ? (void)0 : ((void)fprintf(stderr, \
"%s:%d: %s: %s\n", __FILE__, __LINE__, msg, mdb_strerror(rc)), abort()))
char dkbuf[1024];
int main(int argc,char * argv[])
{
int i = 0, j = 0, rc;
MDB_env *env;
MDB_dbi dbi;
MDB_val key, data, sdata;
MDB_txn *txn;
MDB_stat mst;
MDB_cursor *cursor;
int count;
int *values;
long kval;
char *sval;
srand(time(NULL));
E(mdb_env_create(&env));
E(mdb_env_set_mapsize(env, 10485760));
E(mdb_env_set_maxdbs(env, 4));
E(mdb_env_open(env, "./testdb", MDB_FIXEDMAP|MDB_NOSYNC, 0664));
E(mdb_txn_begin(env, NULL, 0, &txn));
E(mdb_dbi_open(txn, "id6", MDB_CREATE|MDB_INTEGERKEY, &dbi));
E(mdb_cursor_open(txn, dbi, &cursor));
E(mdb_stat(txn, dbi, &mst));
sval = calloc(1, mst.ms_psize / 4);
key.mv_size = sizeof(long);
key.mv_data = &kval;
sdata.mv_size = mst.ms_psize / 4 - 30;
sdata.mv_data = sval;
printf("Adding 12 values, should yield 3 splits\n");
for (i=0;i<12;i++) {
kval = i*5;
sprintf(sval, "%08x", kval);
data = sdata;
(void)RES(MDB_KEYEXIST, mdb_cursor_put(cursor, &key, &data, MDB_NOOVERWRITE));
}
printf("Adding 12 more values, should yield 3 splits\n");
for (i=0;i<12;i++) {
kval = i*5+4;
sprintf(sval, "%08x", kval);
data = sdata;
(void)RES(MDB_KEYEXIST, mdb_cursor_put(cursor, &key, &data, MDB_NOOVERWRITE));
}
printf("Adding 12 more values, should yield 3 splits\n");
for (i=0;i<12;i++) {
kval = i*5+1;
sprintf(sval, "%08x", kval);
data = sdata;
(void)RES(MDB_KEYEXIST, mdb_cursor_put(cursor, &key, &data, MDB_NOOVERWRITE));
}
E(mdb_cursor_get(cursor, &key, &data, MDB_FIRST));
do {
printf("key: %p %s, data: %p %.*s\n",
key.mv_data, mdb_dkey(&key, dkbuf),
data.mv_data, (int) data.mv_size, (char *) data.mv_data);
} while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0);
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
mdb_cursor_close(cursor);
mdb_txn_commit(txn);
#if 0
j=0;
for (i= count - 1; i > -1; i-= (rand()%5)) {
j++;
txn=NULL;
E(mdb_txn_begin(env, NULL, 0, &txn));
sprintf(kval, "%03x", values[i & ~0x0f]);
sprintf(sval, "%03x %d foo bar", values[i], values[i]);
key.mv_size = sizeof(int);
key.mv_data = kval;
data.mv_size = sizeof(sval);
data.mv_data = sval;
if (RES(MDB_NOTFOUND, mdb_del(txn, dbi, &key, &data))) {
j--;
mdb_txn_abort(txn);
} else {
E(mdb_txn_commit(txn));
}
}
free(values);
printf("Deleted %d values\n", j);
E(mdb_env_stat(env, &mst));
E(mdb_txn_begin(env, NULL, MDB_RDONLY, &txn));
E(mdb_cursor_open(txn, dbi, &cursor));
printf("Cursor next\n");
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
printf("key: %.*s, data: %.*s\n",
(int) key.mv_size, (char *) key.mv_data,
(int) data.mv_size, (char *) data.mv_data);
}
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
printf("Cursor prev\n");
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_PREV)) == 0) {
printf("key: %.*s, data: %.*s\n",
(int) key.mv_size, (char *) key.mv_data,
(int) data.mv_size, (char *) data.mv_data);
}
CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
mdb_cursor_close(cursor);
mdb_txn_abort(txn);
mdb_dbi_close(env, dbi);
#endif
mdb_env_close(env);
return 0;
}

73
deps/liblmdb/sample-bdb.txt vendored Normal file
View File

@ -0,0 +1,73 @@
/* sample-bdb.txt - BerkeleyDB toy/sample
*
* Do a line-by-line comparison of this and sample-mdb.txt
*/
/*
* Copyright 2012-2015 Howard Chu, Symas Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
#include <stdio.h>
#include <string.h>
#include <db.h>
int main(int argc,char * argv[])
{
int rc;
DB_ENV *env;
DB *dbi;
DBT key, data;
DB_TXN *txn;
DBC *cursor;
char sval[32], kval[32];
/* Note: Most error checking omitted for simplicity */
#define FLAGS (DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_TXN|DB_INIT_MPOOL|DB_CREATE|DB_THREAD)
rc = db_env_create(&env, 0);
rc = env->open(env, "./testdb", FLAGS, 0664);
rc = db_create(&dbi, env, 0);
rc = env->txn_begin(env, NULL, &txn, 0);
rc = dbi->open(dbi, txn, "test.bdb", NULL, DB_BTREE, DB_CREATE, 0664);
memset(&key, 0, sizeof(DBT));
memset(&data, 0, sizeof(DBT));
key.size = sizeof(int);
key.data = sval;
data.size = sizeof(sval);
data.data = sval;
sprintf(sval, "%03x %d foo bar", 32, 3141592);
rc = dbi->put(dbi, txn, &key, &data, 0);
rc = txn->commit(txn, 0);
if (rc) {
fprintf(stderr, "txn->commit: (%d) %s\n", rc, db_strerror(rc));
goto leave;
}
rc = env->txn_begin(env, NULL, &txn, 0);
rc = dbi->cursor(dbi, txn, &cursor, 0);
key.flags = DB_DBT_USERMEM;
key.data = kval;
key.ulen = sizeof(kval);
data.flags = DB_DBT_USERMEM;
data.data = sval;
data.ulen = sizeof(sval);
while ((rc = cursor->c_get(cursor, &key, &data, DB_NEXT)) == 0) {
printf("key: %p %.*s, data: %p %.*s\n",
key.data, (int) key.size, (char *) key.data,
data.data, (int) data.size, (char *) data.data);
}
rc = cursor->c_close(cursor);
rc = txn->abort(txn);
leave:
rc = dbi->close(dbi, 0);
rc = env->close(env, 0);
return rc;
}

62
deps/liblmdb/sample-mdb.txt vendored Normal file
View File

@ -0,0 +1,62 @@
/* sample-mdb.txt - MDB toy/sample
*
* Do a line-by-line comparison of this and sample-bdb.txt
*/
/*
* Copyright 2012-2015 Howard Chu, Symas Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
#include <stdio.h>
#include "lmdb.h"
int main(int argc,char * argv[])
{
int rc;
MDB_env *env;
MDB_dbi dbi;
MDB_val key, data;
MDB_txn *txn;
MDB_cursor *cursor;
char sval[32];
/* Note: Most error checking omitted for simplicity */
rc = mdb_env_create(&env);
rc = mdb_env_open(env, "./testdb", 0, 0664);
rc = mdb_txn_begin(env, NULL, 0, &txn);
rc = mdb_dbi_open(txn, NULL, 0, &dbi);
key.mv_size = sizeof(int);
key.mv_data = sval;
data.mv_size = sizeof(sval);
data.mv_data = sval;
sprintf(sval, "%03x %d foo bar", 32, 3141592);
rc = mdb_put(txn, dbi, &key, &data, 0);
rc = mdb_txn_commit(txn);
if (rc) {
fprintf(stderr, "mdb_txn_commit: (%d) %s\n", rc, mdb_strerror(rc));
goto leave;
}
rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
rc = mdb_cursor_open(txn, dbi, &cursor);
while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
printf("key: %p %.*s, data: %p %.*s\n",
key.mv_data, (int) key.mv_size, (char *) key.mv_data,
data.mv_data, (int) data.mv_size, (char *) data.mv_data);
}
mdb_cursor_close(cursor);
mdb_txn_abort(txn);
leave:
mdb_dbi_close(env, dbi);
mdb_env_close(env);
return 0;
}

22
deps/liblmdb/tooltag vendored Normal file
View File

@ -0,0 +1,22 @@
<tagfile>
<compound kind="page">
<name>mdb_copy_1</name>
<title>mdb_copy - environment copy tool</title>
<filename>mdb_copy.1</filename>
</compound>
<compound kind="page">
<name>mdb_dump_1</name>
<title>mdb_dump - environment export tool</title>
<filename>mdb_dump.1</filename>
</compound>
<compound kind="page">
<name>mdb_load_1</name>
<title>mdb_load - environment import tool</title>
<filename>mdb_load.1</filename>
</compound>
<compound kind="page">
<name>mdb_stat_1</name>
<title>mdb_stat - environment status tool</title>
<filename>mdb_stat.1</filename>
</compound>
</tagfile>

8
deps/win32/unistd.h vendored Normal file
View File

@ -0,0 +1,8 @@
#ifndef INCLUDED_unistd
#define INCLUDED_unistd
#if defined (WIN32)
typedef int32_t ssize_t;
#endif
#endif

View File

@ -0,0 +1,57 @@
"use strict";
var kMessages = [
[
" _ _ _ ",
" / \\ | |__ ___ _ _| |_ ",
" / _ \\ | '_ \\ / _ \\| | | | __|",
" / ___ \\| |_) | (_) | |_| | |_ ",
"/_/ \\_\\_.__/ \\___/ \\__,_|\\__|",
"",
"Tilde Friends: Webapps that anyone can download, modify, run, and share.",
"",
"You are looking at a web site running on a JavaScript and C++ web server that uses Google V8 to let visitors author webapps.",
"",
["Full source is here <",
{href: "https://www.unprompted.com/projects/browser/sandboxos/trunk/"},
">, but it is probably more fun and useful to poke around the ",
{href: "/~cory/index", value: "existing webapps"},
". A ",
{href: "https://www.unprompted.com/projects/wiki/Projects/SandboxOS", value: "prebuilt Windows .zip"},
" is available as well. ",
],
"",
[
"Use the links at the top of the page to explore existing apps. When you are ready, click edit and start making your own. See the ",
{href: "/~cory/documentation", value: "documentation"},
" for more information.",
],
],
];
var gIndex = 0;
function printNextMessage() {
if (gIndex < kMessages.length) {
var block = kMessages[gIndex];
for (var i = 0; i < block.length; i++) {
terminal.print(block[i]);
}
terminal.print("");
}
if (gIndex < kMessages.length) {
gIndex++;
if (gIndex < kMessages.length) {
terminal.print("(press enter to continue, \"exit\" to exit)");
}
}
}
core.register("onInput", function(input) {
if (input == "exit") {
exit();
} else {
printNextMessage();
}
});
printNextMessage();

View File

@ -0,0 +1,137 @@
"use strict";
//! {"permissions": ["administration"]}
terminal.print("Administration");
if (core.user.credentials.permissions &&
core.user.credentials.permissions.administration) {
core.register("onInput", onInput);
terminal.print("Welcome, administrator.");
terminal.print("Usage:");
let kCommands = [
[
"set",
"List all global settings.",
],
[
["set ", {class: "cyan", value: "key value"}],
["Set global setting key to value."],
],
[
"permission list",
"List all permissions."
],
[
["permission add ", {class: "cyan", value: "user action1 action2 ..."}],
["Grant permission for ", {class: "cyan", value: "action1"}, ", ", {class: "cyan", value: "action2"}, ", ", {class: "cyan", value: "..."}, " to ", {class: "cyan", value: "user"}, "."],
],
[
["permission remove ", {class: "cyan", value: "user action1 action2 ..."}],
["Revoke permission for ", {class: "cyan", value: "action1"}, ", ", {class: "cyan", value: "action2"}, ", ", {class: "cyan", value: "..."}, " from ", {class: "cyan", value: "user"}, "."],
],
[
"statistics", "List statistics."
],
];
for (var i = 0; i < kCommands.length; i++) {
terminal.print({class: "yellow", value: kCommands[i][0]});
terminal.print({style: "display: block; margin-left: 2em", value: kCommands[i][1]});
}
} else {
terminal.print("You are not an administrator.");
}
var kSimpleSettings = [
'httpPort',
'httpsPort',
'index',
];
function printSettings(settings) {
terminal.print("Current settings:");
for (let i = 0; i < kSimpleSettings.length; i++) {
terminal.print(" ", {class: "magenta", value: kSimpleSettings[i]}, " = ", {class: "yellow", value: settings[kSimpleSettings[i]]});
}
}
function printPermissions(settings) {
terminal.print("Current permissions:");
let permissions = settings.permissions || {};
for (let entry in permissions) {
terminal.print(" ", {class: "magenta", value: entry}, ": ", {class: "yellow", value: permissions[entry].join(" ")});
}
}
function onInput(input) {
try {
let match;
if (input == "set") {
administration.getGlobalSettings().then(printSettings);
} else if (input == "statistics") {
administration.getStatistics().then(function(s) {
for (var i in s) {
terminal.print(" ".repeat(16 - s[i].toString().length), s[i].toString(), " ", i);
}
});
} else if (match = /^\s*set\s+(\w+)\s+(.*)/.exec(input)) {
var key = match[1];
var value = match[2];
administration.getGlobalSettings().then(function(settings) {
if (kSimpleSettings.indexOf(key) != -1) {
settings[key] = value;
administration.setGlobalSettings(settings).then(function() {
administration.getGlobalSettings().then(printSettings);
}).catch(function(error) {
terminal.print("Error updating settings: " + JSON.stringify(error));
});
} else {
terminal.print("Unknown setting: " + key);
}
});
} else if (match = /^\s*permission\s+(\w+)(?:\s+(.*))?/.exec(input)) {
var command = match[1];
var remaining = (match[2] || "").split(/\s+/);
if (command == "list") {
administration.getGlobalSettings().then(printPermissions);
} else if (command == "add") {
var user = remaining[0];
administration.getGlobalSettings().then(function(settings) {
settings.permissions = settings.permissions || {};
settings.permissions[user] = settings.permissions[user] || [];
for (var i = 1; i < remaining.length; i++) {
if (settings.permissions[user].indexOf(remaining[i]) == -1) {
settings.permissions[user].push(remaining[i]);
}
}
settings.permissions[user].sort();
administration.setGlobalSettings(settings).then(function() {
administration.getGlobalSettings().then(printPermissions);
}).catch(function(error) {
terminal.print("Error updating permissions: " + JSON.stringify(error));
});
});
} else if (command == "remove") {
var user = remaining[0];
administration.getGlobalSettings().then(function(settings) {
if (settings.permissions && settings.permissions[user]) {
for (var i = 1; i < remaining.length; i++) {
settings.permissions[user] = settings.permissions[user].filter(x => x != remaining[i]);
}
if (settings.permissions[user].length == 0) {
delete settings.permissions[user];
}
}
administration.setGlobalSettings(settings).then(function() {
administration.getGlobalSettings().then(printPermissions);
}).catch(function(error) {
terminal.print("Error updating permissions: " + JSON.stringify(error));
});
});
}
} else if (typeof input == "string") {
terminal.print("I didn't understand that.");
}
} catch (error) {
terminal.print("error: " + error);
}
}

315
packages/cory/bbs/bbs.js Normal file
View File

@ -0,0 +1,315 @@
"use strict";
var gOnInput = null;
var kMaxHistory = 20;
var kShowHistory = 20;
var lastTimestamp = null;
if (imports.terminal) {
core.register("onMessage", function(sender, message) {
if (message.message && message.when) {
printMessage(message, true);
}
});
core.register("onSessionBegin", function(user) {
if (user.packageName === core.user.packageName &&
user.index !== core.user.index) {
listUsers(user.name + " has joined the BBS. ");
}
});
core.register("onSessionEnd", function(user) {
if (user.packageName === core.user.packageName &&
user.index !== core.user.index) {
listUsers(user.name + " has left the BBS. ");
}
});
} else {
// Chat service process.
core.register("onMessage", function(sender, message) {
if (message.message && message.when) {
message.sender = sender;
return database.get("board").catch(function() {
return null;
}).then(function(data) {
try {
data = JSON.parse(data);
} catch(error) {
data = [];
}
data.push(message);
while (data.length > kMaxHistory) {
data.shift();
}
return saveBoard(data);
}).then(function() {
return core.broadcast(message);
});
}
});
}
function listUsers() {
return core.getUsers(core.user.packageOwner, core.user.packageName).then(function(users) {
terminal.select("users");
terminal.clear();
terminal.print("Users:");
var counts = {};
for (var i = 0; i < users.length; i++) {
counts[users[i].name] = (counts[users[i].name] || 0) + 1;
}
var names = Object.keys(counts).sort();
for (var i = 0; i < names.length; i++) {
var name = names[i];
var message = [];
if (message.length > 1) {
message.push(", ");
}
message.push({class: "orange", value: name});
if (counts[name] > 1) {
message.push({class: "base01", value: "(x" + counts[name] + ")"});
}
terminal.print(message);
}
terminal.select("terminal");
});
}
function saveBoard(data) {
return database.set("board", JSON.stringify(data)).catch(function(error) {
if (error.message.indexOf("MDB_MAP_FULL") != -1) {
data.shift();
return saveBoard(data);
} else {
throw error;
}
});
}
core.register("onInput", function(input) {
if (gOnInput && typeof input == "string") {
gOnInput(input);
}
});
function logo() {
terminal.clear();
terminal.print("");
terminal.print("");
terminal.print('Welcome to');
terminal.print(' ______ _ ____ ____ _____');
terminal.print(' / ____/___ _______ _( )_____ / __ )/ __ ) ___/');
terminal.print(' / / / __ \\/ ___/ / / /// ___/ / __ / __ \\__ \\ ');
terminal.print('/ /___/ /_/ / / / /_/ / (__ ) / /_/ / /_/ /__/ / ');
terminal.print('\\____/\\____/_/ \\__, / /____/ /_____/_____/____/ ');
terminal.print(' /____/ ');
terminal.print(' yesterday\'s technology...today!');
terminal.print("");
}
function welcome() {
logo();
chat();
}
function main() {
terminal.clear();
logo();
terminal.print("");
terminal.print("Main menu commands:");
terminal.print(" ", {command: "chat"}, " chat message board");
terminal.print(" ", {command: "guess"}, " guess the number game");
terminal.print(" ", {command: "exit"}, " back to that sweet logo");
gOnInput = function(input) {
input = input.toLowerCase();
if (input == "chat") {
chat();
} else if (input == "guess") {
guess();
} else if (input == "exit") {
terminal.print("Goodbye.");
exit(0);
} else {
terminal.print("I didn't understand that: " + input);
main();
}
};
}
function formatMessage(message) {
var result;
if (typeof message == "string") {
result = [];
var regex = /(\w+:\/*\S+?)(?=(?:[\.!?])?(?:$|\s))/gi;
var match;
var lastIndex = 0;
while ((match = regex.exec(message)) !== null) {
result.push({class: "base1", value: message.substring(lastIndex, match.index)});
result.push({href: match[0]});
lastIndex = regex.lastIndex;
}
result.push({class: "base1", value: message.substring(lastIndex)});
} else {
result = message;
}
return result;
}
function niceTime(lastTime, thisTime) {
if (!lastTime) {
return thisTime;
}
let result = [];
let lastParts = lastTime.split(" ");
let thisParts = thisTime.split(" ");
for (let i = 0; i < thisParts.length; i++) {
if (thisParts[i] !== lastParts[i]) {
result.push(thisParts[i]);
}
}
return result.join(" ");
}
function printMessage(message, notify) {
terminal.print(
{class: "base0", value: niceTime(lastTimestamp, message.when)},
" ",
{class: "base00", value: "<"},
{class: "base3", value: (message.sender ? message.sender.name : "unknown")},
{class: "base00", value: ">"},
" ",
formatMessage(message.message));
lastTimestamp = message.when;
if (notify) {
return core.getUser().then(function(user) {
if (message.message.indexOf("!") != -1) {
return terminal.notify("SOMEONE IS SHOUTING!", {body: "<" + (message.sender ? message.sender.name : "unknown") + "> " + message.message});
} else if (message.message.indexOf(user.name + ":") != -1) {
return terminal.notify("Someone is talking at you.", {body: "<" + (message.sender ? message.sender.name : "unknown") + "> " + message.message});
}
});
}
}
function chat() {
terminal.setEcho(false);
terminal.print("");
terminal.print("You are now in a chat. Anything you type will be broadcast to everyone else connected. To leave, say ", {command: "exit"}, ".");
listUsers();
database.get("board").catch(function() {
return null;
}).then(function(board) {
try {
board = JSON.parse(board);
} catch (error) {
board = [];
}
for (let i = Math.max(0, board.length - kShowHistory); i < board.length; i++) {
printMessage(board[i], false);
}
});
gOnInput = function(input) {
if (input == "exit") {
terminal.setEcho(true);
main();
} else {
core.getService("chat").then(function(chatService) {
return chatService.postMessage({when: new Date().toString(), message: input});
}).catch(function(error) {
terminal.print("ERROR: " + JSON.stringify(error));
});
}
};
}
function guess() {
terminal.clear();
var number = Math.round(Math.random() * 100);
var guesses = 0;
terminal.print("OK, I have a number in mind. What do you think it is? Use ", {command: "exit"}, " to stop.");
gOnInput = function(input) {
if (input == "exit") {
main();
} else {
var guess = parseInt(input);
guesses++;
if (input != guess.toString()) {
terminal.print("I'm not sure that's an integer. Please guess only integers.");
} else {
if (guess < number) {
terminal.print("Too low.");
} else if (guess > number) {
terminal.print("Too high.");
} else if (guess == number) {
terminal.print("Wow, you got it in " + guesses + " guesses! It was " + number + ".");
guessEnd(guesses);
}
}
}
};
}
function guessEnd(guesses) {
terminal.print("What's your name, for the high score table?");
gOnInput = function(name) {
var entry = {'guesses': guesses, 'name': name, 'when': new Date().toString()};
database.get("guessHighScores").then(function(data) {
data = JSON.parse(data);
var index = data.length;
for (var i in data) {
if (guesses < data[i].guesses) {
index = i;
break;
}
}
data.splice(index, 0, entry);
printHighScores(data);
database.set("guessHighScores", JSON.stringify(data));
gOnInput = function() {
main();
};
}).catch(function() {
var data = [entry];
printHighScores(data);
database.set("guessHighScores", JSON.stringify(data));
main();
});
};
}
function printTable(data) {
var widths = [];
for (var i in data) {
var row = data[i];
for (var c in row) {
widths[c] = Math.max(widths[c] || 0, row[c].length);
}
}
for (var i in data) {
var row = data[i];
var line = "";
for (var c in row) {
line += row[c];
line += " ".repeat(widths[c] - row[c].length + 2);
}
terminal.print(line);
}
}
function printHighScores(data) {
printTable([["Name", "Guesses", "Date"]].concat(data.map(function(entry) {
return [entry.name, entry.guesses.toString(), entry.when];
})));
}
if (imports.terminal) {
terminal.split([
{type: "horizontal", children: [
{name: "terminal", grow: 1},
{name: "users", grow: 0},
]},
]);
welcome();
}

View File

@ -0,0 +1,93 @@
"use strict";
let kDocumentation = {
"core.broadcast": ["message", "Broadcast a message to every other instance of the same app. Messages will be received through the \"onMessage\" event."],
"core.getService": ["name", "Get a reference to a long-running service process identified by name. A process will be started if it is not already running. Useful for coordinating between client processes."],
"core.getPackages": ["", "Get a list of all available applications."],
"core.getUser": ["", "Gets information about the current user."],
"core.getUsers": ["packageOwner, packageName", "Get a list of all online users, restricted to a package if specified."],
"core.register": ["eventName, handlerFunction", "Register a callback function for the given event."],
"database.get": ["key", "Retrieve the database value associated with the given key."],
"database.set": ["key, value", "Sets the database value for the given key, overwriting any existing value."],
"database.getAll": ["", "Retrieve a list of all key names."],
"database.remove": ["key", "Remove the database entry for the given key."],
"terminal.print": ["arguments...", `Print to the terminal. Multiple arguments and lists are all expanded. The following special values are supported:
{href: "http://www..."} => Create a link to the href value. Text will be the href value or 'value' if specified.
{iframe: "<html>...</html>", width: 640, height: 480} => Create an iframe with the given srcdoc.
{style: "color: #f00", value: "Hello, world!"} => Create styled text.
{command: "exit", value: "get out of here"} => Create a link that when clicked will act as if the user typed the given command.`],
"terminal.clear": ["", "Remove all terminal output."],
"terminal.readLine": ["", "Produces the next line of text from user input."],
"terminal.setEcho": ["echo", "Controls whether the terminal will automatically echo user input (default=true)."],
"terminal.setTitle": ["title", "Sets the browser window/tab title."],
"terminal.setPrompt": ["prompt", "Sets the terminal prompt (default \">\")."],
"terminal.setPassword": ["enabled", "Controls whether the terminal input box is set as a password input and obscures the entered text."],
"terminal.setHash": ["hash", "Sets the URL #hash, typically so that the user can copy / bookmark it and return to a similar state."],
"terminal.postMessageToIframe": ["name, message", "Sends the message to the iframe that was created with the given name using window.postMessage."],
"terminal.notify": ["body, {title, icon}", ["Produces an ", {href: "https://developer.mozilla.org/en-US/docs/Web/API/notification", value: "HTML5 Notification"}, ". Arguments are the same as the Notification constructor."]],
};
terminal.print("V8 Version ", version);
terminal.print("");
heading("API Documentation");
dumpDocumentation("imports", imports);
heading("Notes");
terminal.print(`All API functions are invoked asynchronously. They
immediately return a `,
{href: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise", value: "Promise"},
` object. If you want to do
something with the result, you most likely want to call them
like this:
database.get(key).then(function(value) {
doSomethingWithTheResult(value);
});`);
terminal.print("");
heading("Colors (CSS class names)");
dumpColors();
function heading(text) {
terminal.print({class: "green", value: "+" + "-".repeat(text.length + 2) + "+"});
terminal.print({class: "green", value: "| " + text + " |"});
terminal.print({class: "green", value: "+" + "-".repeat(text.length + 2) + "+"});
}
function dumpDocumentation(prefix, object, depth) {
if (typeof object == "function") {
let documentation = kDocumentation[prefix.substring("imports.".length)] || ["", ""];
terminal.print(
{class: "yellow", value: prefix.substring("imports.".length)},
"(",
{class: "base0", value: documentation[0]},
")");
terminal.print({style: "display: block; margin-left: 2em", value: documentation[1]});
terminal.print("");
} else if (object && typeof object != "string") {
for (let i in object) {
dumpDocumentation(prefix + "." + i, object[i], (depth || 0) + 1);
}
}
}
function dumpColors() {
var kColors = [
"base03",
"base02",
"base01",
"base00",
"base0",
"base1",
"base2",
"base3",
"yellow",
"red",
"magenta",
"violet",
"blue",
"cyan",
"green",
];
terminal.print({style: "background-color: #000", value: kColors.map(function(color) { return [" ", {class: color, value: color}, " "]; })});
}

View File

@ -0,0 +1,53 @@
"use strict";
core.register("onSessionBegin", index);
core.register("onSessionEnd", index);
function index() {
Promise.all([core.getPackages(), core.getUsers()]).then(function(values) {
let packages = values[0];
let users = values[1];
let usersByApp = {};
for (let i in users) {
let user = users[i];
if (!usersByApp["/~" + user.packageOwner + "/" + user.packageName]) {
usersByApp["/~" + user.packageOwner + "/" + user.packageName] = [];
}
usersByApp["/~" + user.packageOwner + "/" + user.packageName].push(user.name);
}
terminal.clear();
terminal.print("Available applications [active users]:");
packages.sort(function(x, y) {
return Math.sign(x.owner.localeCompare(y.owner)) * 10 + Math.sign(x.name.localeCompare(y.name)) * 1;
}).forEach(function(app) {
let users = usersByApp["/~" + app.owner + "/" + app.name];
let message = [];
if (users) {
message.push(" [");
let counts = {};
for (let i = 0; i < users.length; i++) {
counts[users[i]] = (counts[users[i]] || 0) + 1;
}
let names = Object.keys(counts).sort();
for (let i = 0; i < names.length; i++) {
var name = names[i];
if (message.length > 1) {
message.push(", ");
}
message.push({class: "orange", value: name});
if (counts[name] > 1) {
message.push({class: "base01", value: "(x" + counts[name] + ")"});
}
}
message.push("]");
}
terminal.print(
"* ",
{href: "/~" + app.owner + "/" + app.name},
message);
});
});
}
index();

View File

@ -0,0 +1,124 @@
"use strict";
// This script runs server-side, once for each client session.
if (imports.terminal) {
terminal.setEcho(false);
terminal.split([
{name: "graphics", basis: "520px", shrink: "0", grow: "0"},
{name: "text"},
]);
// Request a callback every time the user hits enter at the terminal prompt.
core.register("onInput", function(input) {
// Ask a persistent service session to broadcast our message. We'll also get a copy back.
return core.getService("turtle").then(function(service) {
return service.postMessage(input);
});
});
// Request a callback for every message that is broadcast.
core.register("onMessage", function(sender, message) {
if (message.history) {
for (var i = 0; i < message.history.length; i++) {
// Pass the message on to the iframe in the client.
terminal.postMessageToIframe("turtle", message.history[i]);
}
} else {
// Pass the message on to the iframe in the client.
terminal.postMessageToIframe("turtle", message);
}
});
core.register("onWindowMessage", function(data) {
terminal.print(data.message);
});
terminal.select("graphics");
terminal.print("MMO Turtle Graphics using ", {href: "http://codeheartjs.com/turtle/"}, ".");
// Add an iframe to the terminal. This is how we sandbox code running on the client.
var contents = `
<script src="http://codeheartjs.com/turtle/turtle.min.js">-*- javascript -*-</script>
<script>
setScale(2);
setWidth(3);
// Receive messages in the iframe and use them to draw.
function onMessage(event) {
var parts = event.data.split(" ");
var command = parts.shift();
if (command == "reset") {
setPosition(0, 0);
setHeading(0);
clear(WHITE);
_ch_startTimer(30);
} else if (command == "home") {
var wasDown = _turtle.penDown;
pu();
setPosition(0, 0);
setHeading(0);
if (wasDown) {
pd();
}
_ch_startTimer(30);
} else if (command == "clear") {
clear(WHITE);
_ch_startTimer(30);
} else if (["fd", "bk", "rt", "lt", "pu", "pd"].indexOf(command) != -1) {
window[command].apply(window, parts.map(parseInt));
event.source.postMessage(event.data, event.origin);
_ch_startTimer(30);
} else {
event.source.postMessage("Unrecognized command: " + command, event.origin);
}
}
// Register for messages in the iframe
window.addEventListener('message', onMessage, false);
</script>
`
terminal.print({iframe: contents, width: 640, height: 480, name: "turtle"});
terminal.select("text");
terminal.print("Supported commands: ", ["fd <distance>", "bk <distance>", "rt <angle>", "lt <angle>", "pu", "pd", "home", "reset", "clear"].join(", "));
// Get the party started by asking for the history of commands (the turtle party).
setTimeout(function() {
core.getService("turtle").then(function(service) {
return service.postMessage("sync");
});
}, 1000);
} else {
var gHistory = null;
function ensureHistoryLoaded() {
if (!gHistory) {
return database.get("history").then(function(data) {
gHistory = JSON.parse(data);
return gHistory;
}).catch(function(error) {
gHistory = [];
return gHistory;
});
} else {
return new Promise(function(resolve, reject) { resolve(gHistory); });
}
}
core.register("onMessage", function(sender, message) {
return ensureHistoryLoaded().then(function(history) {
if (message == "reset") {
history.length = 0;
database.set("history", JSON.stringify(history));
return core.broadcast(message);
} else if (message == "sync") {
sender.postMessage({history: history});
} else {
history.push(message);
database.set("history", JSON.stringify(history));
return core.broadcast(message);
}
});
});
}

View File

@ -0,0 +1,74 @@
"use strict";
//! {"permissions": ["network"]}
terminal.print("Hello, world!");
let kFrom = core.user.name + "@unprompted.com";
let kTo = "test@unprompted.com";
let kSubject = "Hello, world!";
let kBody = "This is the body of the email."
let inBuffer = "";
let sentFrom = false;
let sentTo = false;
let sentData = false;
function lineReceived(socket, line) {
terminal.print("> ", line);
let parts = line.split(" ", 1);
terminal.print(JSON.stringify(parts));
if (parts[0] == "220") {
socket.write("HELO rowlf.unprompted.com\r\n");
} else if (parts[0] == "250") {
if (!sentFrom) {
terminal.print("FROM");
socket.write("MAIL FROM: " + kFrom + "\r\n");
sentFrom = true;
} else if (!sentTo) {
terminal.print("TO");
socket.write("RCPT TO: " + kTo + "\r\n");
sentTo = true;
} else if (!sentData) {
terminal.print("DATA");
socket.write("DATA\r\n");
sentData = true;
} else {
terminal.print("QUIT");
socket.write("QUIT\r\n");
}
} else if (parts[0] == "354") {
terminal.print("MESSAGE");
socket.write("Subject: " + kSubject + "\r\n\r\n" + kBody + "\r\n.\r\n");
}
}
function dataReceived(socket, data) {
if (data === null) {
return;
}
terminal.print(data);
inBuffer += data;
let again = true;
while (again) {
again = false;
let end = inBuffer.indexOf("\n");
if (end != -1) {
again = true;
let line = inBuffer.substring(0, end);
inBuffer = inBuffer.substring(end + 1);
lineReceived(socket, line);
}
}
}
network.newConnection().then(function(socket) {
socket.read(function(data) {
try {
dataReceived(socket, data);
} catch (error) {
terminal.print("ERROR: ", error.message);
}
});
socket.connect("localhost", 25);
});

204
packages/cory/todo/todo.js Normal file
View File

@ -0,0 +1,204 @@
"use strict";
var kUnchecked = "☐";
var kChecked = "☑";
let activeList = null;
let confirmRemove;
terminal.setPrompt("Add Item>");
core.register("onInput", function(command) {
if (typeof command == "string" && command.substring(0, "action:".length) == "action:") {
command = JSON.parse(command.substring("action:".length));
if (confirmRemove && command.action != "reallyRemoveList" && command.action != "reallyRemove") {
confirmRemove = false;
}
if (command.action == "set") {
setItem(command.key, command.item, command.value).then(notifyChanged).then(redisplay);
} else if (command.action == "remove") {
confirmRemove = command;
redisplay();
} else if (command.action == "reallyRemove") {
confirmRemove = false;
removeItem(command.key, command.item).then(notifyChanged).then(redisplay);
} else if (command.action == "editList") {
activeList = command.key;
terminal.setHash(activeList);
redisplay();
} else if (command.action == "lists") {
activeList = null;
redisplay();
} else if (command.action == "removeList") {
confirmRemove = true;
redisplay();
} else if (command.action == "reallyRemoveList") {
confirmRemove = false;
activeList = null;
database.remove(command.key).then(notifyChanged).then(redisplay).catch(function(error) {
terminal.print(JSON.stringify(error));
terminal.print(command.key);
});
}
} else if (typeof command == "string") {
if (activeList) {
addItem(activeList, command).then(notifyChanged).then(redisplay);
} else {
activeList = makePrivateKey(command);
writeList(activeList, {name: command, items: []}).then(notifyChanged).then(redisplay);
}
} else if (command.hash) {
activeList = command.hash;
if (activeList.charAt(0) == "#") {
activeList = activeList.substring(1);
}
redisplay();
}
});
core.register("onMessage", function(message) {
return redisplay();
});
function notifyChanged() {
return core.broadcast({changed: true});
}
function readList(key) {
return database.get(key).catch(function(error) {
return null;
}).then(function(todo) {
try {
todo = JSON.parse(todo);
} catch (error) {
todo = {name: "TODO", items: []};
}
return todo;
});
}
function writeList(key, todo) {
return database.set(key, JSON.stringify(todo));
}
function addItem(key, name) {
return readList(key).then(function(todo) {
todo.items.push({name: name, value: false});
return writeList(key, todo);
});
}
function setItem(key, name, value) {
return readList(key).then(function(todo) {
for (var i = 0; i < todo.items.length; i++) {
if (todo.items[i].name == name) {
todo.items[i].value = value;
}
}
return writeList(key, todo);
});
}
function removeItem(key, name) {
return readList(key).then(function(todo) {
todo.items = todo.items.filter(function(item) {
return item.name != name;
});
return writeList(key, todo);
});
}
function printList(name, key, items) {
terminal.print(name,
" - ",
{command: "action:" + JSON.stringify({action: "lists"}), value: "back"},
" - ",
{command: "action:" + JSON.stringify({action: (confirmRemove === true ? "reallyRemoveList" : "removeList"), key: key}), value: (confirmRemove === true ? "confirm remove" : "remove")});
terminal.print("=".repeat(name.length));
for (var i = 0; i < items.length; i++) {
var isChecked = items[i].value;
var style = ["", "text-decoration: line-through"];
terminal.print(
{command: "action:" + JSON.stringify({action: "set", key: key, item: items[i].name, value: !isChecked}), value: isChecked ? kChecked : kUnchecked},
" ",
{style: style[isChecked ? 1 : 0], value: items[i].name},
" (",
{command: "action:" + JSON.stringify({
action: (confirmRemove && confirmRemove.item == items[i].name ? "reallyRemove" : "remove"),
key: key,
item: items[i].name}), value: (confirmRemove && confirmRemove.item == items[i].name ? "confirm remove" : "remove")},
")");
}
}
function redisplay() {
terminal.clear();
terminal.setEcho(false);
if (activeList) {
readList(activeList).then(function(data) {
printList(getName(activeList), activeList, data.items);
}).catch(function(error) {
terminal.print("error: " + error);
});
} else {
printListOfLists();
}
}
function makeId() {
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var result = "";
for (var i = 0; i < 32; i++) {
result += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
}
return result;
}
function makePublicKey(name) {
return JSON.stringify({public: true, id: makeId(), name: name});
}
function makePrivateKey(name) {
return JSON.stringify({public: false, id: makeId(), name: name, user: core.user.name});
}
function hasPermission(key) {
let result = false;
try {
let data = JSON.parse(key);
result = data.public || data.user == core.user.name;
} catch (error) {
result = true;
}
return result;
}
function getName(key) {
let name = "TODO";
try {
name = JSON.parse(key).name || name;
} catch (error) {
}
return name;
}
function getVisibleLists() {
return database.getAll().then(function(data) {
return data.filter(hasPermission);
});
}
function printListOfLists() {
terminal.print("TODO Lists:");
getVisibleLists().then(function(keys) {
for (var i = 0; i < keys.length; i++) {
let key = keys[i];
terminal.print({
command: "action:" + JSON.stringify({action: "editList", key: key}),
value: getName(key),
});
}
});
}
redisplay();

View File

@ -0,0 +1,41 @@
"use strict";
// Start at bottom left facing up.
// Height = 20. Width = 10.
// 10 between.
var letters = {
A: 'fd(20); rt(90); fd(10); rt(90); fd(10); rt(90); fd(10); pu(); bk(10); lt(90); pd(); fd(10); pu(); lt(90); fd(10); lt(90); pd();',
D: 'fd(20); rt(90); fd(10); rt(70); fd(11); rt(40); fd(11); rt(70); fd(10); pu(); bk(20); rt(90); pd();',
E: 'pu(); fd(20); rt(90); fd(10); lt(180); pd(); fd(10); lt(90); fd(10); lt(90); fd(8); pu(); rt(180); fd(8); lt(90); pd(); fd(10); lt(90); fd(10); pu(); fd(10); lt(90); pd()',
H: 'fd(20); pu(); bk(10); pd(); rt(90); fd(10); lt(90); pu(); fd(10); rt(180); pd(); fd(20); pu(); lt(90); fd(10); lt(90); pd();',
L: 'pu(); fd(20); rt(180); pd(); fd(20); lt(90); fd(10); pu(); fd(10); lt(90); pd();',
O: 'fd(20); rt(90); fd(10); rt(90); fd(20); rt(90); fd(10); pu(); bk(20); rt(90); pd();',
R: 'fd(20); rt(90); fd(10); rt(90); fd(10); rt(90); fd(10); pu(); bk(8); lt(90); pd(); fd(10); pu(); lt(90); fd(12); lt(90); pd();',
W: 'pu(); fd(20); rt(180); pd(); fd(20); lt(90); fd(5); lt(90); fd(12); rt(180); pu(); fd(12); pd(); lt(90); fd(5); lt(90); fd(20); pu(); bk(20); rt(90); fd(10); lt(90); pd();',
' ': 'pu(); rt(90); fd(20); lt(90); pd();',
};
function render(text) {
terminal.clear();
terminal.print(text, " using ", {href: "http://codeheartjs.com/turtle/"}, ".");
var contents = '<script src="http://codeheartjs.com/turtle/turtle.min.js">-*- javascript -*-</script><script>\n';
contents += 'setScale(2); setWidth(5);\n';
for (var i = 0; i < text.length; i++) {
var c = text.charAt(i).toUpperCase();
if (letters[c]) {
contents += letters[c] + '\n';
} else {
contents += letters[' '] + '\n';
}
}
contents += "ht();\n";
contents += "window.addEventListener('message', function(event) { console.debug(event.data); }, false);\n";
contents += "</script>\n";
terminal.print({iframe: contents, width: 640, height: 480});
terminal.print("Type text and the letters ", {style: "color: #ff0", value: Object.keys(letters).join("")}, " in it will be drawn.");
}
render("Hello, world!");
core.register("onInput", render);

952
packages/cory/xmpp/xmpp.js Normal file
View File

@ -0,0 +1,952 @@
"use strict";
//! {"permissions": ["network"]}
// md5.js
/*
* JavaScript MD5 1.0.1
* https://github.com/blueimp/JavaScript-MD5
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*
* Based on
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*jslint bitwise: true */
/*global unescape, define */
'use strict';
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t) {
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
}
function md5_ff(a, b, c, d, x, s, t) {
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t) {
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t) {
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t) {
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length.
*/
function binl_md5(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << (len % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var i, olda, oldb, oldc, oldd,
a = 1732584193,
b = -271733879,
c = -1732584194,
d = 271733878;
for (i = 0; i < x.length; i += 16) {
olda = a;
oldb = b;
oldc = c;
oldd = d;
a = md5_ff(a, b, c, d, x[i], 7, -680876936);
d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i], 20, -373897302);
a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
d = md5_hh(d, a, b, c, x[i], 11, -358537222);
c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i], 6, -198630844);
d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return [a, b, c, d];
}
/*
* Convert an array of little-endian words to a string
*/
function binl2rstr(input) {
var i,
output = '';
for (i = 0; i < input.length * 32; i += 8) {
output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF);
}
return output;
}
/*
* Convert a raw string to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*/
function rstr2binl(input) {
var i,
output = [];
output[(input.length >> 2) - 1] = undefined;
for (i = 0; i < output.length; i += 1) {
output[i] = 0;
}
for (i = 0; i < input.length * 8; i += 8) {
output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32);
}
return output;
}
/*
* Calculate the MD5 of a raw string
*/
function rstr_md5(s) {
return binl2rstr(binl_md5(rstr2binl(s), s.length * 8));
}
/*
* Calculate the HMAC-MD5, of a key and some data (raw strings)
*/
function rstr_hmac_md5(key, data) {
var i,
bkey = rstr2binl(key),
ipad = [],
opad = [],
hash;
ipad[15] = opad[15] = undefined;
if (bkey.length > 16) {
bkey = binl_md5(bkey, key.length * 8);
}
for (i = 0; i < 16; i += 1) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
return binl2rstr(binl_md5(opad.concat(hash), 512 + 128));
}
/*
* Convert a raw string to a hex string
*/
function rstr2hex(input) {
var hex_tab = '0123456789abcdef',
output = '',
x,
i;
for (i = 0; i < input.length; i += 1) {
x = input.charCodeAt(i);
output += hex_tab.charAt((x >>> 4) & 0x0F) +
hex_tab.charAt(x & 0x0F);
}
return output;
}
/*
* Encode a string as utf-8
*/
function str2rstr_utf8(input) {
return unescape(input);
}
/*
* Take string arguments and return either raw or hex encoded strings
*/
function raw_md5(s) {
return rstr_md5(str2rstr_utf8(s));
}
function hex_md5(s) {
return rstr2hex(raw_md5(s));
}
function raw_hmac_md5(k, d) {
return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d));
}
function hex_hmac_md5(k, d) {
return rstr2hex(raw_hmac_md5(k, d));
}
function md5(string, key, raw) {
if (!key) {
if (!raw) {
return hex_md5(string);
}
return raw_md5(string);
}
if (!raw) {
return hex_hmac_md5(key, string);
}
return raw_hmac_md5(key, string);
}
// end md5.js
// base64.js
/**
*
* Base64 encode / decode
* http://www.webtoolkit.info/
*
**/
// private property
var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var Base64 = {
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = _keyStr.indexOf(input.charAt(i++));
enc2 = _keyStr.indexOf(input.charAt(i++));
enc3 = _keyStr.indexOf(input.charAt(i++));
enc4 = _keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = 0;
var c1 = 0;
var c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
// end base64.js
function xmlEncode(text) {
return text.replace(/([\&"'<>])/g, function(x, item) {
return {'&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;', "'": '&apos;'}[item];
});
}
function xmlDecode(xml) {
return xml.replace(/(&quot;|&lt;|&gt;|&amp;|&apos;)/g, function(x, item) {
return {'&amp;': '&', '&quot;': '"', '&lt;': '<', '&gt;': '>', '&apos;': "'"}[item];
});
}
// xmpp.js
function XmlStreamParser() {
this.buffer = "";
this._parsed = [];
this.reset();
return this;
}
XmlStreamParser.kText = "text";
XmlStreamParser.kElement = "element";
XmlStreamParser.kEndElement = "endElement";
XmlStreamParser.kAttributeName = "attributeName";
XmlStreamParser.kAttributeValue = "attributeValue";
XmlStreamParser.prototype.reset = function() {
this._state = XmlStreamParser.kText;
this._attributes = {};
this._attributeName = "";
this._attributeValue = "";
this._attributeEquals = false;
this._attributeQuote = "";
this._slash = false;
this._value = "";
this._decl = false;
}
XmlStreamParser.prototype.parse = function(data) {
this._parsed = [];
for (var i = 0; i < data.length; i++) {
var c = data.charAt(i);
this.parseCharacter(c);
}
return this._parsed;
}
XmlStreamParser.prototype.flush = function() {
var node = {type: this._state};
if (this._value) {
node.value = xmlDecode(this._value);
}
if (this._attributes.length || this._state == XmlStreamParser.kElement) {
node.attributes = this._attributes;
}
if (this._state != XmlStreamParser.kText || this._value) {
this.emit(node);
}
this.reset();
}
XmlStreamParser.prototype.parseCharacter = function(c) {
switch (this._state) {
case XmlStreamParser.kText:
if (c == '<') {
this.flush();
this._state = XmlStreamParser.kElement;
} else {
this._value += c;
}
break;
case XmlStreamParser.kElement:
case XmlStreamParser.kEndElement:
switch (c) {
case '>':
this.finishElement();
break;
case '/':
if (!this._value) {
this._state = XmlStreamParser.kEndElement;
} else if (!this._slash) {
this._slash = true;
} else {
this._value += c;
}
break;
case '?':
if (!this._value) {
this._decl = true;
} else {
this._value += '?';
}
break;
case ' ':
case '\t':
case '\r':
case '\n':
this._state = XmlStreamParser.kAttributeName;
break;
default:
if (this._slash) {
this._slash = false;
this._value += '/';
}
this._value += c;
break;
}
break;
case XmlStreamParser.kAttributeName:
switch (c) {
case ' ':
case '\t':
case '\r':
case '\n':
if (this._attributeName) {
this._state = XmlStreamParser.kAttributeValue;
}
break;
case '/':
if (!this._slash) {
this._slash = true;
} else {
this._value += '/';
}
break;
case '=':
this._state = XmlStreamParser.kAttributeValue;
break;
case '>':
if (this._attributeName) {
this._attributes[this._attributeName] = null;
}
this._state = XmlStreamParser.kElement;
this.finishElement();
break;
default:
this._attributeName += c;
break;
}
break;
case XmlStreamParser.kAttributeValue:
switch (c) {
case ' ':
case '\t':
case '\r':
case '\n':
if (this._attributeValue) {
this._state = XmlStreamParser.kAttributeName;
}
break;
case '"':
case "'":
if (!this._attributeValue && !this._attributeQuote) {
this._attributeQuote = c;
} else if (this._attributeQuote == c) {
this._attributes[this._attributeName] = this._attributeValue;
this._attributeName = "";
this._attributeValue = "";
this._attributeQuote = "";
this._state = XmlStreamParser.kAttributeName;
} else {
this._attributeValue += c;
}
break;
case '>':
this.finishElement();
break;
default:
this._attributeValue += c;
break;
}
break;
}
}
XmlStreamParser.prototype.finishElement = function() {
if (this._decl) {
this.reset();
} else {
var value = this._value;
var slash = this._slash;
this.flush();
if (slash) {
this._state = XmlStreamParser.kEndElement;
this._value = value;
this.flush();
}
}
this._state = XmlStreamParser.kText;
}
XmlStreamParser.prototype.emit = function(node) {
this._parsed.push(node);
}
function XmlStanzaParser(depth) {
this._depth = depth || 0;
this._parsed = [];
this._stack = [];
this._stream = new XmlStreamParser();
return this;
}
XmlStanzaParser.prototype.reset = function() {
this._parsed = [];
this._stack = [];
this._stream.reset();
}
XmlStanzaParser.prototype.emit = function(stanza) {
this._parsed.push(stanza);
}
XmlStanzaParser.prototype.parse = function(data) {
this._parsed = [];
var nodes = this._stream.parse(data);
for (var i = 0; i < nodes.length; i++) {
this.parseNode(nodes[i]);
}
return this._parsed;
}
XmlStanzaParser.prototype.parseNode = function(node) {
switch (node.type) {
case XmlStreamParser.kElement:
this._stack.push({name: node.value, attributes: node.attributes, children: [], text: ""});
break;
case XmlStreamParser.kEndElement:
if (this._stack.length == 1 + this._depth) {
this.emit(this._stack.pop());
} else {
var last = this._stack.pop();
this._stack[this._stack.length - 1].children.push(last);
}
break;
case XmlStreamParser.kText:
if (this._stack) {
this._stack[this._stack.length - 1].text += node.value;
}
break;
}
}
// end xmpp.js
var gFocus = false;
var gUnread = 0;
function updateTitle() {
if (gUnread) {
terminal.setTitle("(" + gUnread.toString() + ") ~Friends XMPP");
} else {
terminal.setTitle("~Friends XMPP");
}
}
terminal.print("~Friends XMPP");
updateTitle();
terminal.setEcho(false);
terminal.setPrompt("Username:");
terminal.readLine().then(function(userName) {
terminal.setPassword(true);
terminal.setPrompt("Password:");
terminal.readLine().then(function(password) {
terminal.setPrompt(">");
terminal.setPassword(false);
network.newConnection().then(function(socket) {
connect(socket, userName, password);
}).catch(function(error) {
terminal.print(error);
});
});
});
function niceTime(lastTime, thisTime) {
if (!lastTime) {
return thisTime;
}
let result = [];
let lastParts = lastTime.split(" ");
let thisParts = thisTime.split(" ");
for (let i = 0; i < thisParts.length; i++) {
if (thisParts[i] !== lastParts[i]) {
result.push(thisParts[i]);
}
}
return result.join(" ");
}
function formatMessage(message) {
var result;
if (typeof message == "string") {
result = [];
var regex = /(\w+:\/*\S+?)(?=(?:[\.!?])?(?:$|\s))/gi;
var match;
var lastIndex = 0;
while ((match = regex.exec(message)) !== null) {
result.push({class: "base1", value: message.substring(lastIndex, match.index)});
result.push({href: match[0]});
lastIndex = regex.lastIndex;
}
result.push({class: "base1", value: message.substring(lastIndex)});
} else {
result = message;
}
return result;
}
var lastTimestamp = null;
function printMessage(stanza) {
var body;
var delayed = false;
var now = new Date().toString();
for (var i in stanza.children) {
if (stanza.children[i].name == "body") {
body = stanza.children[i].text;
}
if (stanza.children[i].name == "delay") {
delayed = true;
now = new Date(stanza.children[i].attributes.stamp).toString();
}
}
var from = stanza.attributes.from || "unknown";
if (from && from.indexOf('/') != -1) {
from = from.split("/")[1];
}
terminal.print(
{class: "base0", value: niceTime(lastTimestamp, now)},
" ",
{class: "base00", value: "<"},
{class: "base3", value: from},
{class: "base00", value: ">"},
" ",
formatMessage(body));
lastTimestamp = now;
}
var gRecent = [];
core.register("focus", function() {
gFocus = true;
gUnread = 0;
updateTitle();
});
core.register("blur", function() {
gFocus = false;
});
var gPingCount = 0;
function schedulePing(socket) {
setTimeout(function() {
socket.write("<iq type='get' id='ping" + (++gPingCount) + "'><ping xmlns='urn:xmpp:ping'/></iq>");
schedulePing(socket);
}, 60000);
}
terminal.split([
{type: "horizontal", children: [
{name: "terminal", grow: 1},
{name: "users", grow: 0},
]},
]);
terminal.select("terminal");
var gPresence = {};
function refreshUsers() {
terminal.select("users");
terminal.clear();
for (var i in gPresence) {
terminal.print(i);
}
terminal.select("terminal");
}
function connect(socket, userName, password) {
var kTrustedCertificate = "-----BEGIN CERTIFICATE-----\n" +
"MIICqjCCAhOgAwIBAgIJAPEhMguftPdoMA0GCSqGSIb3DQEBCwUAMG4xCzAJBgNV\n" +
"BAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEPMA0GA1UEBwwGQXVzdGluMRswGQYDVQQK\n" +
"DBJUcm91YmxlIEltcGFjdCBMTEMxITAfBgNVBAMMGGphYmJlci50cm91YmxlaW1w\n" +
"YWN0LmNvbTAeFw0xNDEyMjYwMzU5NDRaFw0yNDEyMjMwMzU5NDRaMG4xCzAJBgNV\n" +
"BAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEPMA0GA1UEBwwGQXVzdGluMRswGQYDVQQK\n" +
"DBJUcm91YmxlIEltcGFjdCBMTEMxITAfBgNVBAMMGGphYmJlci50cm91YmxlaW1w\n" +
"YWN0LmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAueniASgCpF7mQFGt\n" +
"TycOhMt9VMetFwwDkwVglvO+VKq8JWxWkJaCWm8YYacG6+zn4RlV3zVQhrAcReTU\n" +
"pPQAe+28wJdqVt/HPyfcwJtLKUEL7Nk5N8mY2s6yyBVvMn9e7Yt/fnv7pOCpcmBi\n" +
"kuLlwSGEfMnDskt8kH4coidP4w0CAwEAAaNQME4wHQYDVR0OBBYEFOztZhuuqXrN\n" +
"yUnPo/9aoNNb/o2CMB8GA1UdIwQYMBaAFOztZhuuqXrNyUnPo/9aoNNb/o2CMAwG\n" +
"A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADgYEAgK/7yoGEHeG95i6E1A8ZBkeL\n" +
"monKMys3RxnJciuFdBrUcvymsgOTrAGvatPXatNbHQ/eY8LnkKHtf0pCCs0B/xST\n" +
"DTO3KdlNCXApMUieFPjVggRzikbmbPCvtTt2BzqQKzVqubf9eM+kbsD7Pkgycm5+\n" +
"q46TZws0oz5lAvklIgo=\n" +
"-----END CERTIFICATE-----";
var resource = "tildefriend" + core.user.index;
socket.connect("jabber.troubleimpact.com", 5222).then(function() {
var parse = new XmlStanzaParser(1);
socket.write("<?xml version='1.0'?>");
socket.write("<stream:stream to='jabber.troubleimpact.com' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>");
var started = false;
var authenticated = false;
socket.onError(function(error) {
terminal.print("SOCKET ERROR");
terminal.print(JSON.stringify(error));
terminal.print(error);
terminal.print(error.message);
});
socket.read(function(data) {
try {
gRecent.push(data);
while (gRecent.length > 10) {
gRecent.shift();
}
if (data === undefined) {
terminal.print(JSON.stringify(data));
terminal.print("Disconnected.");
terminal.print("Recent data:");
for (let i = 0; i < gRecent.length; i++) {
terminal.print(JSON.stringify(gRecent[i]));
}
return;
}
parse.parse(data).forEach(function(stanza) {
if (stanza.name == "stream:features") {
if (!started) {
socket.write("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
} else if (!authenticated) {
socket.write("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='DIGEST-MD5'/>");
} else {
socket.write("<iq type='set' id='bind0'><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><resource>" + resource + "</resource></bind></iq>");
}
} else if (stanza.name == "proceed") {
if (!started) {
started = true;
socket.addTrustedCertificate(kTrustedCertificate);
socket.startTls().then(function() {
parse.reset();
socket.write("<stream:stream to='jabber.troubleimpact.com' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>");
}).catch(function(e) {
terminal.print("TLS FAILED: " + e);
});
}
} else if (stanza.name == "success") {
authenticated = true;
socket.write("<?xml version='1.0'?>");
socket.write("<stream:stream to='jabber.troubleimpact.com' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>");
parse.reset();
} else if (stanza.name == "iq") {
if (stanza.attributes.id == "bind0") {
socket.write("<iq type='set' id='session0'><session xmlns='urn:ietf:params:xml:ns:xmpp-session'/></iq>");
} else if (stanza.attributes.id == "session0") {
socket.write("<presence to='chadhappyfuntime@conference.jabber.troubleimpact.com/" + userName + "'><priority>1</priority><x xmlns='http://jabber.org/protocol/muc'/></presence>");
core.register("onInput", function(input) {
socket.write("<message type='groupchat' to='chadhappyfuntime@conference.jabber.troubleimpact.com'><body>" + xmlEncode(input) + "</body></message>");
});
schedulePing(socket);
} else if (stanza.attributes.id == "ping" + gPingCount) {
// Ping response.
} else {
terminal.print(JSON.stringify(stanza));
}
} else if (stanza.name == "message") {
printMessage(stanza);
if (!gFocus) {
++gUnread;
updateTitle();
}
} else if (stanza.name == "challenge") {
var challenge = Base64.decode(stanza.text);
var parts = challenge.split(',');
challenge = {};
for (var i = 0; i < parts.length; i++) {
var equals = parts[i].indexOf("=");
if (equals != -1) {
var key = parts[i].substring(0, equals);
var value = parts[i].substring(equals + 1);
if (value.length > 2 && value.charAt(0) == '"' && value.charAt(value.length - 1) == '"') {
value = value.substring(1, value.length - 1);
}
challenge[key] = value;
}
}
if (challenge.rspauth) {
socket.write("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>");
} else {
var realm = "jabber.troubleimpact.com";
var cnonce = Base64.encode(new Date().toString());
var x = userName + ":" + realm + ":" + password;
var y = raw_md5(x);
var a1 = y + ":" + challenge.nonce + ":" + cnonce;
var digestUri = "xmpp/" + realm;
var a2 = "AUTHENTICATE:" + digestUri;
var ha1 = md5(a1);
var ha2 = md5(a2);
var nc = "00000001";
var kd = ha1 + ":" + challenge.nonce + ":" + nc + ":" + cnonce + ":" + challenge.qop + ":" + ha2;
var response = md5(kd);
var value = Base64.encode('username="' + userName + '",realm="' + realm + '",nonce="' + challenge.nonce + '",cnonce="' + cnonce + '",nc=' + nc + ',qop=' + challenge.qop + ',digest-uri="' + digestUri + '",response=' + response + ',charset=utf-8');
socket.write("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>" + value + "</response>");
}
} else if (stanza.name == "presence") {
var name = stanza.attributes.from.split('/', 2)[1];
if (stanza.attributes.type == "unavailable") {
terminal.print(name + " has left the room.");
delete gPresence[name];
} else {
if (!gPresence[name]) {
terminal.print(name + " has joined the room.");
}
gPresence[name] = stanza;
}
refreshUsers();
} else {
terminal.print(data);
}
});
} catch (error) {
terminal.print("ERROR: " + error);
terminal.print("ERROR: " + JSON.stringify(error));
terminal.print("ERROR: " + error.message);
}
});
}).catch(function(e) {
terminal.print("connect failed: ", e);
});
}

190
src/Database.cpp Normal file
View File

@ -0,0 +1,190 @@
#include "Database.h"
#include "Task.h"
#include <assert.h>
#include <sstream>
int Database::_count = 0;
Database::Database(Task* task) {
++_count;
_task = task;
v8::Handle<v8::External> data = v8::External::New(task->getIsolate(), this);
v8::Local<v8::ObjectTemplate> databaseTemplate = v8::ObjectTemplate::New(task->getIsolate());
databaseTemplate->SetInternalFieldCount(1);
databaseTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "get"), v8::FunctionTemplate::New(task->getIsolate(), get, data));
databaseTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "set"), v8::FunctionTemplate::New(task->getIsolate(), set, data));
databaseTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "remove"), v8::FunctionTemplate::New(task->getIsolate(), remove, data));
databaseTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "getAll"), v8::FunctionTemplate::New(task->getIsolate(), getAll, data));
v8::Local<v8::Object> databaseObject = databaseTemplate->NewInstance();
databaseObject->SetInternalField(0, v8::External::New(task->getIsolate(), this));
_object = v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object> >(task->getIsolate(), databaseObject);
}
Database::~Database() {
--_count;
}
void Database::create(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope handleScope(args.GetIsolate());
if (Database* database = new Database(Task::get(args.GetIsolate()))) {
if (database->open(args.GetIsolate(), *v8::String::Utf8Value(args[0].As<v8::String>()))) {
v8::Handle<v8::Object> result = v8::Local<v8::Object>::New(args.GetIsolate(), database->_object);
args.GetReturnValue().Set(result);
}
database->release();
}
}
bool Database::checkError(const char* command, int result) {
bool isError = false;
if (result != MDB_SUCCESS) {
isError = true;
std::ostringstream buffer;
buffer << command << " failed (" << result << "): " << mdb_strerror(result);
_task->getIsolate()->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(_task->getIsolate(), buffer.str().c_str())));
}
return isError;
}
bool Database::open(v8::Isolate* isolate, const char* path) {
int result = mdb_env_create(&_environment);
if (checkError("mdb_env_create", result)) {
return false;
}
result = mdb_env_set_maxdbs(_environment, 10);
checkError("mdb_env_set_maxdbs", result);
result = mdb_env_open(_environment, path, 0, 0644);
if (!checkError("mdb_env_open", result)) {
result = mdb_txn_begin(_environment, 0, 0, &_transaction);
if (!checkError("mdb_txn_begin", result)) {
result = mdb_dbi_open(_transaction, NULL, MDB_CREATE, &_database);
if (!checkError("mdb_dbi_open", result)) {
result = mdb_txn_commit(_transaction);
checkError("mdb_txn_commit", result);
}
}
if (result != MDB_SUCCESS) {
mdb_txn_abort(_transaction);
}
}
if (result != MDB_SUCCESS) {
mdb_env_close(_environment);
}
return result == MDB_SUCCESS;
}
void Database::get(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Database* database = Database::get(args.Data())) {
int result = mdb_txn_begin(database->_environment, 0, MDB_RDONLY, &database->_transaction);
if (!database->checkError("mdb_txn_begin", result)) {
MDB_val key;
MDB_val value;
v8::String::Utf8Value keyString(args[0].As<v8::String>());
key.mv_data = *keyString;
key.mv_size = keyString.length();
if (mdb_get(database->_transaction, database->_database, &key, &value) == MDB_SUCCESS) {
args.GetReturnValue().Set(v8::String::NewFromUtf8(args.GetIsolate(), reinterpret_cast<const char*>(value.mv_data), v8::String::kNormalString, value.mv_size));
}
mdb_txn_reset(database->_transaction);
}
}
}
void Database::set(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Database* database = Database::get(args.Data())) {
int result = mdb_txn_begin(database->_environment, 0, 0, &database->_transaction);
if (!database->checkError("mdb_txn_begin", result)) {
MDB_val key;
MDB_val data;
v8::String::Utf8Value keyString(args[0].As<v8::String>());
key.mv_data = *keyString;
key.mv_size = keyString.length();
v8::String::Utf8Value valueString(args[1]->ToString(args.GetIsolate()));
data.mv_data = *valueString;
data.mv_size = valueString.length();
result = mdb_put(database->_transaction, database->_database, &key, &data, 0);
database->checkError("mdb_put", result);
mdb_txn_commit(database->_transaction);
}
}
}
void Database::remove(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Database* database = Database::get(args.Data())) {
int result = mdb_txn_begin(database->_environment, 0, 0, &database->_transaction);
if (!database->checkError("mdb_txn_begin", result)) {
MDB_val key;
v8::String::Utf8Value keyString(args[0].As<v8::String>());
key.mv_data = *keyString;
key.mv_size = keyString.length();
result = mdb_del(database->_transaction, database->_database, &key, 0);
database->checkError("mdb_del", result);
mdb_txn_commit(database->_transaction);
}
}
}
void Database::getAll(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Database* database = Database::get(args.Data())) {
int result = mdb_txn_begin(database->_environment, 0, MDB_RDONLY, &database->_transaction);
if (!database->checkError("mdb_txn_begin", result)) {
MDB_cursor* cursor;
result = mdb_cursor_open(database->_transaction, database->_database, &cursor);
if (!database->checkError("mdb_cursor_open", result)) {
int expectedCount = 0;
MDB_stat statistics;
if (mdb_stat(database->_transaction, database->_database, &statistics) == 0) {
expectedCount = statistics.ms_entries;
}
v8::Local<v8::Array> array = v8::Array::New(args.GetIsolate(), expectedCount);
MDB_val key;
int index = 0;
while ((result = mdb_cursor_get(cursor, &key, 0, MDB_NEXT)) == 0) {
array->Set(index++, v8::String::NewFromUtf8(args.GetIsolate(), reinterpret_cast<const char*>(key.mv_data), v8::String::kNormalString, key.mv_size));
}
if (result == MDB_NOTFOUND) {
args.GetReturnValue().Set(array);
} else {
database->checkError("mdb_cursor_get", result);
}
mdb_cursor_close(cursor);
}
mdb_txn_reset(database->_transaction);
}
}
}
void Database::onRelease(const v8::WeakCallbackData<v8::Object, Database>& data) {
data.GetParameter()->_object.Reset();
delete data.GetParameter();
}
void Database::ref() {
if (++_refCount == 1) {
_object.ClearWeak();
}
}
void Database::release() {
assert(_refCount >= 1);
if (--_refCount == 0) {
_object.SetWeak(this, onRelease);
}
}
Database* Database::get(v8::Handle<v8::Value> databaseObject) {
return reinterpret_cast<Database*>(v8::Handle<v8::External>::Cast(databaseObject)->Value());
}

44
src/Database.h Normal file
View File

@ -0,0 +1,44 @@
#ifndef INCLUDED_Database
#define INCLUDED_Database
#include <lmdb.h>
#include <v8.h>
class Task;
class Database {
public:
static void create(const v8::FunctionCallbackInfo<v8::Value>& args);
static int getCount() { return _count; }
private:
Database(Task* task);
~Database();
Task* _task;
int _refCount = 1;
v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object> > _object;
MDB_env* _environment;
MDB_dbi _database;
MDB_txn* _transaction;
static int _count;
static Database* get(v8::Handle<v8::Value> databaseObject);
static void onRelease(const v8::WeakCallbackData<v8::Object, Database>& data);
static void get(const v8::FunctionCallbackInfo<v8::Value>& args);
static void set(const v8::FunctionCallbackInfo<v8::Value>& args);
static void remove(const v8::FunctionCallbackInfo<v8::Value>& args);
static void getAll(const v8::FunctionCallbackInfo<v8::Value>& args);
bool open(v8::Isolate* isolate, const char* path);
bool checkError(const char* command, int result);
void ref();
void release();
};
#endif

129
src/File.cpp Normal file
View File

@ -0,0 +1,129 @@
#include "File.h"
#include "Task.h"
#include <cstring>
#include <fstream>
#include <iostream>
#include <uv.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <dirent.h>
#include <unistd.h>
#endif
void File::configure(v8::Isolate* isolate, v8::Handle<v8::ObjectTemplate> global) {
v8::Local<v8::ObjectTemplate> fileTemplate = v8::ObjectTemplate::New(isolate);
fileTemplate->Set(v8::String::NewFromUtf8(isolate, "readFile"), v8::FunctionTemplate::New(isolate, readFile));
fileTemplate->Set(v8::String::NewFromUtf8(isolate, "readDirectory"), v8::FunctionTemplate::New(isolate, readDirectory));
fileTemplate->Set(v8::String::NewFromUtf8(isolate, "makeDirectory"), v8::FunctionTemplate::New(isolate, makeDirectory));
fileTemplate->Set(v8::String::NewFromUtf8(isolate, "writeFile"), v8::FunctionTemplate::New(isolate, writeFile));
fileTemplate->Set(v8::String::NewFromUtf8(isolate, "renameFile"), v8::FunctionTemplate::New(isolate, renameFile));
fileTemplate->Set(v8::String::NewFromUtf8(isolate, "unlinkFile"), v8::FunctionTemplate::New(isolate, unlinkFile));
global->Set(v8::String::NewFromUtf8(isolate, "File"), fileTemplate);
}
void File::readFile(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope(args.GetIsolate());
v8::Handle<v8::String> fileName = args[0]->ToString();
v8::String::Utf8Value utf8FileName(fileName);
std::ifstream file(*utf8FileName, std::ios_base::in | std::ios_base::binary | std::ios_base::ate);
std::streampos fileSize = file.tellg();
if (fileSize >= 0 && fileSize < 4 * 1024 * 1024) {
file.seekg(0, std::ios_base::beg);
char* buffer = new char[fileSize];
file.read(buffer, fileSize);
std::string contents(buffer, buffer + fileSize);
args.GetReturnValue().Set(v8::String::NewFromOneByte(args.GetIsolate(), reinterpret_cast<const uint8_t*>(buffer), v8::String::kNormalString, fileSize));
delete[] buffer;
}
}
void File::writeFile(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope(args.GetIsolate());
v8::Handle<v8::String> fileName = args[0]->ToString();
v8::Handle<v8::String> contents = args[1]->ToString();
v8::String::Utf8Value utf8FileName(fileName);
std::ofstream file(*utf8FileName, std::ios_base::out | std::ios_base::binary);
if (contents->ContainsOnlyOneByte()) {
std::vector<uint8_t> bytes(contents->Length());
contents->WriteOneByte(bytes.data(), 0, bytes.size(), v8::String::NO_NULL_TERMINATION);
if (!file.write(reinterpret_cast<const char*>(bytes.data()), bytes.size())) {
args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(), -1));
}
} else {
v8::String::Utf8Value utf8Contents(contents);
if (!file.write(*utf8Contents, utf8Contents.length())) {
args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(), -1));
}
}
}
void File::renameFile(const v8::FunctionCallbackInfo<v8::Value>& args) {
Task* task = reinterpret_cast<Task*>(args.GetIsolate()->GetData(0));
v8::HandleScope scope(args.GetIsolate());
v8::String::Utf8Value oldName(args[0]->ToString());
v8::String::Utf8Value newName(args[1]->ToString());
uv_fs_t req;
int result = uv_fs_rename(task->getLoop(), &req, *oldName, *newName, 0);
args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(), result));
}
void File::unlinkFile(const v8::FunctionCallbackInfo<v8::Value>& args) {
Task* task = reinterpret_cast<Task*>(args.GetIsolate()->GetData(0));
v8::HandleScope scope(args.GetIsolate());
v8::String::Utf8Value fileName(args[0]->ToString());
uv_fs_t req;
int result = uv_fs_unlink(task->getLoop(), &req, *fileName, 0);
args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(), result));
}
void File::readDirectory(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope(args.GetIsolate());
v8::Handle<v8::String> directory = args[0]->ToString();
v8::Handle<v8::Array> array = v8::Array::New(args.GetIsolate(), 0);
#ifdef _WIN32
WIN32_FIND_DATA find;
std::string pattern = *v8::String::Utf8Value(directory);
pattern += "\\*";
HANDLE handle = FindFirstFile(pattern.c_str(), &find);
if (handle != INVALID_HANDLE_VALUE) {
int index = 0;
do {
array->Set(v8::Integer::New(args.GetIsolate(), index++), v8::String::NewFromUtf8(args.GetIsolate(), find.cFileName));
} while (FindNextFile(handle, &find) != 0);
FindClose(handle);
}
#else
if (DIR* dir = opendir(*v8::String::Utf8Value(directory))) {
int index = 0;
while (struct dirent* entry = readdir(dir)) {
array->Set(v8::Integer::New(args.GetIsolate(), index++), v8::String::NewFromUtf8(args.GetIsolate(), entry->d_name));
}
closedir(dir);
}
#endif
args.GetReturnValue().Set(array);
}
void File::makeDirectory(const v8::FunctionCallbackInfo<v8::Value>& args) {
Task* task = Task::get(args.GetIsolate());
v8::HandleScope scope(args.GetIsolate());
v8::Handle<v8::String> directory = args[0]->ToString();
uv_fs_t req;
int result = uv_fs_mkdir(task->getLoop(), &req, *v8::String::Utf8Value(directory), 0755, 0);
args.GetReturnValue().Set(result);
}

19
src/File.h Normal file
View File

@ -0,0 +1,19 @@
#ifndef INCLUDED_File
#define INCLUDED_File
#include <v8.h>
class File {
public:
static void configure(v8::Isolate* isolate, v8::Handle<v8::ObjectTemplate> global);
private:
static void readFile(const v8::FunctionCallbackInfo<v8::Value>& args);
static void writeFile(const v8::FunctionCallbackInfo<v8::Value>& args);
static void readDirectory(const v8::FunctionCallbackInfo<v8::Value>& args);
static void makeDirectory(const v8::FunctionCallbackInfo<v8::Value>& args);
static void unlinkFile(const v8::FunctionCallbackInfo<v8::Value>& args);
static void renameFile(const v8::FunctionCallbackInfo<v8::Value>& args);
};
#endif

32
src/Mutex.cpp Normal file
View File

@ -0,0 +1,32 @@
#include "Mutex.h"
#include <iostream>
#include <assert.h>
Mutex::Mutex() {
int result = uv_mutex_init(&_mutex);
if (result != 0) {
assert("Mutex lock failed.");
}
}
Mutex::~Mutex() {
uv_mutex_destroy(&_mutex);
}
void Mutex::lock() {
uv_mutex_lock(&_mutex);
}
void Mutex::unlock() {
uv_mutex_unlock(&_mutex);
}
Lock::Lock(Mutex& mutex)
: _mutex(mutex) {
_mutex.lock();
}
Lock::~Lock() {
_mutex.unlock();
}

26
src/Mutex.h Normal file
View File

@ -0,0 +1,26 @@
#ifndef INCLUDED_Mutex
#define INCLUDED_Mutex
#include <uv.h>
class Mutex {
public:
Mutex();
~Mutex();
void lock();
void unlock();
private:
uv_mutex_t _mutex;
};
class Lock {
public:
Lock(Mutex& mutex);
~Lock();
private:
Mutex& _mutex;
};
#endif

85
src/PacketStream.cpp Normal file
View File

@ -0,0 +1,85 @@
#include "PacketStream.h"
#include <cstring>
#include <iostream>
PacketStream::PacketStream()
: _onReceive(0),
_onReceiveUserData(0) {
}
PacketStream::~PacketStream() {
_onReceive = 0;
_onReceiveUserData = 0;
close();
}
void PacketStream::close() {
if (!uv_is_closing(reinterpret_cast<uv_handle_t*>(&_stream))) {
uv_close(reinterpret_cast<uv_handle_t*>(&_stream), 0);
}
}
void PacketStream::start() {
_stream.data = this;
uv_read_start(reinterpret_cast<uv_stream_t*>(&_stream), onAllocate, onRead);
}
void PacketStream::send(int packetType, char* begin, size_t length) {
size_t bufferLength = sizeof(uv_write_t) + sizeof(packetType) + sizeof(length) + length;
char* buffer = new char[bufferLength];
uv_write_t* request = reinterpret_cast<uv_write_t*>(buffer);
buffer += sizeof(uv_write_t);
memcpy(buffer, &packetType, sizeof(packetType));
memcpy(buffer + sizeof(packetType), &length, sizeof(length));
memcpy(buffer + sizeof(packetType) + sizeof(length), begin, length);
uv_buf_t writeBuffer;
writeBuffer.base = buffer;
writeBuffer.len = sizeof(packetType) + sizeof(length) + length;
uv_write(request, reinterpret_cast<uv_stream_t*>(&_stream), &writeBuffer, 1, onWrite);
}
void PacketStream::setOnReceive(OnReceive* onReceiveCallback, void* userData) {
_onReceive = onReceiveCallback;
_onReceiveUserData = userData;
}
void PacketStream::onWrite(uv_write_t* request, int status) {
delete[] reinterpret_cast<char*>(request);
}
void PacketStream::onAllocate(uv_handle_t* handle, size_t suggestedSize, uv_buf_t* buffer) {
buffer->base = new char[suggestedSize];
buffer->len = suggestedSize;
}
void PacketStream::onRead(uv_stream_t* handle, ssize_t count, const uv_buf_t* buffer) {
PacketStream* owner = reinterpret_cast<PacketStream*>(handle->data);
if (count >= 0) {
if (count > 0) {
owner->_buffer.insert(owner->_buffer.end(), buffer->base, buffer->base + count);
owner->processMessages();
}
delete[] reinterpret_cast<char*>(buffer->base);
} else {
owner->close();
}
}
void PacketStream::processMessages() {
int packetType = 0;
size_t length = 0;
while (_buffer.size() >= sizeof(packetType) + sizeof(length)) {
memcpy(&packetType, &*_buffer.begin(), sizeof(packetType));
memcpy(&length, &*_buffer.begin() + sizeof(packetType), sizeof(length));
if (_buffer.size() >= sizeof(packetType) + sizeof(length) + length) {
if (_onReceive) {
_onReceive(packetType, &*_buffer.begin() + sizeof(length) + sizeof(packetType), length, _onReceiveUserData);
}
_buffer.erase(_buffer.begin(), _buffer.begin() + sizeof(length) + sizeof(packetType) + length);
} else {
break;
}
}
}

34
src/PacketStream.h Normal file
View File

@ -0,0 +1,34 @@
#ifndef INCLUDED_PacketStream
#define INCLUDED_PacketStream
#include <uv.h>
#include <vector>
class PacketStream {
public:
PacketStream();
~PacketStream();
void start();
typedef void (OnReceive)(int packetType, const char* begin, size_t length, void* userData);
void send(int packetType, char* begin, size_t length);
void setOnReceive(OnReceive* onReceiveCallback, void* userData);
void close();
uv_pipe_t& getStream() { return _stream; }
private:
OnReceive* _onReceive;
void* _onReceiveUserData;
uv_pipe_t _stream;
std::vector<char> _buffer;
void processMessages();
static void onAllocate(uv_handle_t* handle, size_t suggestedSize, uv_buf_t* buffer);
static void onRead(uv_stream_t* handle, ssize_t count, const uv_buf_t* buffer);
static void onWrite(uv_write_t* request, int status);
};
#endif

210
src/Serialize.cpp Normal file
View File

@ -0,0 +1,210 @@
#include "Serialize.h"
#include "Task.h"
#include "TaskStub.h"
#include <cstring>
void Serialize::writeInt8(std::vector<char>& buffer, int8_t value) {
buffer.insert(buffer.end(), value);
}
void Serialize::writeInt32(std::vector<char>& buffer, int32_t value) {
const char* p = reinterpret_cast<char*>(&value);
buffer.insert(buffer.end(), p, p + sizeof(value));
}
void Serialize::writeUint32(std::vector<char>& buffer, uint32_t value) {
const char* p = reinterpret_cast<char*>(&value);
buffer.insert(buffer.end(), p, p + sizeof(value));
}
void Serialize::writeDouble(std::vector<char>& buffer, double value) {
const char* p = reinterpret_cast<char*>(&value);
buffer.insert(buffer.end(), p, p + sizeof(value));
}
int8_t Serialize::readInt8(const std::vector<char>& buffer, int& offset) {
int8_t result;
std::memcpy(&result, &*buffer.begin() + offset, sizeof(result));
offset += sizeof(result);
return result;
}
int32_t Serialize::readInt32(const std::vector<char>& buffer, int& offset) {
int32_t result;
std::memcpy(&result, &*buffer.begin() + offset, sizeof(result));
offset += sizeof(result);
return result;
}
uint32_t Serialize::readUint32(const std::vector<char>& buffer, int& offset) {
uint32_t result;
std::memcpy(&result, &*buffer.begin() + offset, sizeof(result));
offset += sizeof(result);
return result;
}
double Serialize::readDouble(const std::vector<char>& buffer, int& offset) {
double result;
std::memcpy(&result, &*buffer.begin() + offset, sizeof(result));
offset += sizeof(result);
return result;
}
bool Serialize::store(Task* task, std::vector<char>& buffer, v8::Handle<v8::Value> value) {
return storeInternal(task, buffer, value, 0);
}
bool Serialize::storeInternal(Task* task, std::vector<char>& buffer, v8::Handle<v8::Value> value, int depth) {
if (value.IsEmpty()) {
return false;
} else if (value->IsUndefined()) {
writeInt32(buffer, kUndefined);
} else if (value->IsNull()) {
writeInt32(buffer, kNull);
} else if (value->IsBoolean()) {
writeInt32(buffer, kBoolean);
writeInt8(buffer, value->IsTrue() ? 1 : 0);
} else if (value->IsInt32()) {
writeInt32(buffer, kInt32);
writeInt32(buffer, value->Int32Value());
} else if (value->IsUint32()) {
writeInt32(buffer, kUint32);
writeInt32(buffer, value->Uint32Value());
} else if (value->IsNumber()) {
writeInt32(buffer, kNumber);
writeDouble(buffer, value->NumberValue());
} else if (value->IsString()) {
writeInt32(buffer, kString);
v8::String::Utf8Value utf8(value->ToString());
writeInt32(buffer, utf8.length());
buffer.insert(buffer.end(), *utf8, *utf8 + utf8.length());
} else if (value->IsArray()) {
writeInt32(buffer, kArray);
v8::Handle<v8::Array> array = v8::Handle<v8::Array>::Cast(value);
writeInt32(buffer, array->Length());
for (size_t i = 0; i < array->Length(); ++i) {
storeInternal(task, buffer, array->Get(i), depth + 1);
}
} else if (value->IsFunction()) {
writeInt32(buffer, kFunction);
exportid_t exportId = task->exportFunction(v8::Handle<v8::Function>::Cast(value));
writeInt32(buffer, exportId);
} else if (value->IsNativeError()) {
storeInternal(task, buffer, storeMessage(task, v8::Exception::CreateMessage(value)), depth);
} else if (value->IsObject()) {
writeInt32(buffer, kObject);
v8::Handle<v8::Object> object = value->ToObject();
// XXX: For some reason IsNativeError isn't working reliably. Catch an
// object that still looks like an error object and treat it as such.
if (object->GetOwnPropertyNames()->Length() == 0
&& !object->Get(v8::String::NewFromUtf8(task->getIsolate(), "stackTrace")).IsEmpty()) {
object = v8::Handle<v8::Object>::Cast(storeMessage(task, v8::Exception::CreateMessage(value)));
}
v8::Handle<v8::Array> keys = object->GetOwnPropertyNames();
writeInt32(buffer, keys->Length());
for (size_t i = 0; i < keys->Length(); ++i) {
v8::Handle<v8::Value> key = keys->Get(i);
storeInternal(task, buffer, key, depth + 1);
storeInternal(task, buffer, object->Get(key), depth + 1);
}
} else {
writeInt32(buffer, kString);
v8::String::Utf8Value utf8(value->ToString());
writeInt32(buffer, utf8.length());
buffer.insert(buffer.end(), *utf8, *utf8 + utf8.length());
}
return true;
}
v8::Handle<v8::Value> Serialize::store(Task* task, v8::TryCatch& tryCatch) {
return storeMessage(task, tryCatch.Message());
}
v8::Handle<v8::Object> Serialize::storeMessage(Task* task, v8::Handle<v8::Message> message) {
v8::Handle<v8::Object> error = v8::Object::New(task->getIsolate());
error->Set(v8::String::NewFromUtf8(task->getIsolate(), "message"), message->Get());
error->Set(v8::String::NewFromUtf8(task->getIsolate(), "fileName"), message->GetScriptResourceName());
error->Set(v8::String::NewFromUtf8(task->getIsolate(), "lineNumber"), v8::Integer::New(task->getIsolate(), message->GetLineNumber()));
error->Set(v8::String::NewFromUtf8(task->getIsolate(), "sourceLine"), message->GetSourceLine());
if (!message->GetStackTrace().IsEmpty()) {
error->Set(v8::String::NewFromUtf8(task->getIsolate(), "stackTrace"), message->GetStackTrace()->AsArray());
}
return error;
}
v8::Handle<v8::Value> Serialize::load(Task* task, TaskStub* from, const std::vector<char>& buffer) {
int offset = 0;
return loadInternal(task, from, buffer, offset, 0);
}
v8::Handle<v8::Value> Serialize::loadInternal(Task* task, TaskStub* from, const std::vector<char>& buffer, int& offset, int depth) {
if (static_cast<size_t>(offset) >= buffer.size()) {
return v8::Undefined(task->getIsolate());
} else {
int32_t type = readInt32(buffer, offset);
v8::Handle<v8::Value> result;
switch (type) {
case kUndefined:
result = v8::Undefined(task->getIsolate());
break;
case kNull:
result = v8::Null(task->getIsolate());
break;
case kBoolean:
result = v8::Boolean::New(task->getIsolate(), readInt8(buffer, offset) != 0);
break;
case kInt32:
result = v8::Int32::New(task->getIsolate(), readInt32(buffer, offset));
break;
case kUint32:
result = v8::Uint32::New(task->getIsolate(), readUint32(buffer, offset));
break;
case kNumber:
result = v8::Number::New(task->getIsolate(), readDouble(buffer, offset));
break;
case kString:
{
int32_t length = readInt32(buffer, offset);
result = v8::String::NewFromUtf8(task->getIsolate(), &*buffer.begin() + offset, v8::String::kNormalString, length);
offset += length;
}
break;
case kArray:
{
int32_t length = readInt32(buffer, offset);
v8::Handle<v8::Array> array = v8::Array::New(task->getIsolate());
for (int i = 0; i < length; ++i) {
v8::Handle<v8::Value> value = loadInternal(task, from, buffer, offset, depth + 1);
array->Set(i, value);
}
result = array;
}
break;
case kFunction:
{
exportid_t exportId = readInt32(buffer, offset);
result = task->addImport(from->getId(), exportId);
}
break;
case kObject:
{
int32_t length = readInt32(buffer, offset);
v8::Handle<v8::Object> object = v8::Object::New(task->getIsolate());
for (int i = 0; i < length; ++i) {
v8::Handle<v8::Value> key = loadInternal(task, from, buffer, offset, depth + 1);
v8::Handle<v8::Value> value = loadInternal(task, from, buffer, offset, depth + 1);
object->Set(key, value);
}
result = object;
}
break;
}
return result;
}
}

47
src/Serialize.h Normal file
View File

@ -0,0 +1,47 @@
#ifndef INCLUDED_Serialize
#define INCLUDED_Serialize
#include <v8.h>
#include <vector>
class Task;
class TaskStub;
class Serialize {
public:
static bool store(Task* task, std::vector<char>& buffer, v8::Handle<v8::Value> value);
static v8::Handle<v8::Value> load(Task* task, TaskStub* from, const std::vector<char>& buffer);
static v8::Handle<v8::Value> store(Task* task, v8::TryCatch& tryCatch);
static v8::Handle<v8::Object> storeMessage(Task* task, v8::Handle<v8::Message> message);
private:
static bool storeInternal(Task* task, std::vector<char>& buffer, v8::Handle<v8::Value> value, int depth);
static v8::Handle<v8::Value> loadInternal(Task* task, TaskStub* from, const std::vector<char>& buffer, int& offse, int deptht);
static void writeInt8(std::vector<char>& buffer, int8_t value);
static void writeInt32(std::vector<char>& buffer, int32_t value);
static void writeUint32(std::vector<char>& buffer, uint32_t value);
static void writeDouble(std::vector<char>& buffer, double value);
static int8_t readInt8(const std::vector<char>& buffer, int& offset);
static int32_t readInt32(const std::vector<char>& buffer, int& offset);
static uint32_t readUint32(const std::vector<char>& buffer, int& offset);
static double readDouble(const std::vector<char>& buffer, int& offset);
enum Types {
kUndefined,
kNull,
kBoolean,
kInt32,
kUint32,
kNumber,
kString,
kArray,
kObject,
kFunction,
kError,
};
};
#endif

653
src/Socket.cpp Normal file
View File

@ -0,0 +1,653 @@
#include "Socket.h"
#include "Task.h"
#include "TaskTryCatch.h"
#include "Tls.h"
#include "TlsContextWrapper.h"
#include <assert.h>
#include <cstring>
#include <uv.h>
int Socket::_count = 0;
int Socket::_openCount = 0;
TlsContext* Socket::_defaultTlsContext = 0;
struct SocketResolveData {
uv_getaddrinfo_t resolver;
Socket* socket;
promiseid_t promise;
};
Socket::Socket(Task* task) {
v8::HandleScope scope(task->getIsolate());
++_count;
v8::Handle<v8::External> data = v8::External::New(task->getIsolate(), this);
v8::Local<v8::ObjectTemplate> socketTemplate = v8::ObjectTemplate::New(task->getIsolate());
socketTemplate->SetInternalFieldCount(1);
socketTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "bind"), v8::FunctionTemplate::New(task->getIsolate(), bind, data));
socketTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "connect"), v8::FunctionTemplate::New(task->getIsolate(), connect, data));
socketTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "listen"), v8::FunctionTemplate::New(task->getIsolate(), listen, data));
socketTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "accept"), v8::FunctionTemplate::New(task->getIsolate(), accept, data));
socketTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "startTls"), v8::FunctionTemplate::New(task->getIsolate(), startTls, data));
socketTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "stopTls"), v8::FunctionTemplate::New(task->getIsolate(), stopTls, data));
socketTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "shutdown"), v8::FunctionTemplate::New(task->getIsolate(), shutdown, data));
socketTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "close"), v8::FunctionTemplate::New(task->getIsolate(), close, data));
socketTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "read"), v8::FunctionTemplate::New(task->getIsolate(), read, data));
socketTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "onError"), v8::FunctionTemplate::New(task->getIsolate(), onError, data));
socketTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "write"), v8::FunctionTemplate::New(task->getIsolate(), write, data));
socketTemplate->SetAccessor(v8::String::NewFromUtf8(task->getIsolate(), "peerName"), getPeerName, 0, data);
socketTemplate->SetAccessor(v8::String::NewFromUtf8(task->getIsolate(), "peerCertificate"), getPeerCertificate, 0, data);
socketTemplate->SetAccessor(v8::String::NewFromUtf8(task->getIsolate(), "isConnected"), isConnected, 0, data);
v8::Local<v8::Object> socketObject = socketTemplate->NewInstance();
socketObject->SetInternalField(0, v8::External::New(task->getIsolate(), this));
_object = v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object> >(task->getIsolate(), socketObject);
uv_tcp_init(task->getLoop(), &_socket);
++_openCount;
_socket.data = this;
_task = task;
}
Socket::~Socket() {
if (_tls) {
delete _tls;
_tls = 0;
}
--_count;
}
void Socket::close() {
if (!uv_is_closing(reinterpret_cast<uv_handle_t*>(&_socket))) {
if (!_onRead.IsEmpty()) {
_onRead.Reset();
}
uv_close(reinterpret_cast<uv_handle_t*>(&_socket), onClose);
}
}
void Socket::reportError(const char* error) {
v8::Handle<v8::Value> exception = v8::Exception::Error(v8::String::NewFromUtf8(_task->getIsolate(), error));
if (!_onError.IsEmpty()) {
v8::Handle<v8::Function> callback = v8::Local<v8::Function>::New(_task->getIsolate(), _onError);
callback->Call(callback, 1, &exception);
} else {
_task->getIsolate()->ThrowException(exception);
}
}
void Socket::reportTlsErrors() {
char buffer[4096];
while (_tls && _tls->getError(buffer, sizeof(buffer))) {
reportError(buffer);
}
}
void Socket::startTls(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Socket* socket = Socket::get(args.Data())) {
if (!socket->_tls) {
TlsContext* context = 0;
if (args.Length() > 0 && !args[0].IsEmpty() && !args[0]->IsUndefined()) {
if (TlsContextWrapper* wrapper = TlsContextWrapper::get(args[0])) {
context = wrapper->getContext();
}
} else {
if (!_defaultTlsContext) {
_defaultTlsContext = TlsContext::create();
}
context = _defaultTlsContext;
}
if (context) {
socket->_tls = context->createSession();
}
if (socket->_tls) {
socket->_tls->setHostname(socket->_peerName.c_str());
if (socket->_direction == kAccept) {
socket->_tls->startAccept();
} else if (socket->_direction == kConnect) {
socket->_tls->startConnect();
}
socket->_startTlsPromise = socket->_task->allocatePromise();
socket->processOutgoingTls();
args.GetReturnValue().Set(socket->_task->getPromise(socket->_startTlsPromise));
} else {
args.GetIsolate()->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(args.GetIsolate(), "Failed to get TLS context")));
}
} else {
args.GetIsolate()->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(args.GetIsolate(), "startTls with TLS already started")));
}
}
}
void Socket::stopTls(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Socket* socket = Socket::get(args.Data())) {
if (socket->_tls) {
socket->processOutgoingTls();
delete socket->_tls;
socket->_tls = 0;
} else {
args.GetIsolate()->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(args.GetIsolate(), "stopTls with TLS already stopped")));
}
}
}
bool Socket::processSomeOutgoingTls(promiseid_t promise, uv_write_cb callback) {
char buffer[8192];
int result = _tls->readEncrypted(buffer, sizeof(buffer));
if (result > 0) {
char* rawBuffer = new char[sizeof(uv_write_t) + result];
uv_write_t* request = reinterpret_cast<uv_write_t*>(rawBuffer);
std::memset(request, 0, sizeof(*request));
request->data = reinterpret_cast<void*>(promise);
rawBuffer += sizeof(uv_write_t);
std::memcpy(rawBuffer, buffer, result);
uv_buf_t writeBuffer;
writeBuffer.base = rawBuffer;
writeBuffer.len = result;
int writeResult = uv_write(request, reinterpret_cast<uv_stream_t*>(&_socket), &writeBuffer, 1, callback);
if (writeResult != 0) {
std::string error = "uv_write: " + std::string(uv_strerror(writeResult));
reportError(error.c_str());
}
} else {
reportTlsErrors();
}
return result > 0;
}
void Socket::processOutgoingTls() {
while (processSomeOutgoingTls(-1, onWrite)) {}
}
void Socket::bind(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Socket* socket = Socket::get(args.Data())) {
v8::String::Utf8Value node(args[0]->ToString());
v8::String::Utf8Value port(args[1]->ToString());
SocketResolveData* data = new SocketResolveData();
std::memset(data, 0, sizeof(*data));
struct addrinfo hints;
hints.ai_family = PF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = 0;
data->resolver.data = data;
data->socket = socket;
data->promise = socket->_task->allocatePromise();
int result = uv_getaddrinfo(socket->_task->getLoop(), &data->resolver, onResolvedForBind, *node, *port, &hints);
if (result != 0) {
std::string error = "uv_getaddrinfo: " + std::string(uv_strerror(result));
socket->_task->rejectPromise(data->promise, v8::Exception::Error(v8::String::NewFromUtf8(args.GetIsolate(), error.c_str())));
delete data;
}
args.GetReturnValue().Set(socket->_task->getPromise(data->promise));
}
}
void Socket::onResolvedForBind(uv_getaddrinfo_t* resolver, int status, struct addrinfo* result) {
SocketResolveData* data = reinterpret_cast<SocketResolveData*>(resolver->data);
if (status != 0) {
std::string error = "uv_getaddrinfo: " + std::string(uv_strerror(status));
data->socket->_task->rejectPromise(data->promise, v8::Exception::Error(v8::String::NewFromUtf8(data->socket->_task->getIsolate(), error.c_str())));
} else {
int bindResult = uv_tcp_bind(&data->socket->_socket, result->ai_addr, 0);
if (bindResult != 0) {
std::string error = "uv_tcp_bind: " + std::string(uv_strerror(bindResult));
data->socket->_task->rejectPromise(data->promise, v8::Exception::Error(v8::String::NewFromUtf8(data->socket->_task->getIsolate(), error.c_str())));
} else {
data->socket->_task->resolvePromise(data->promise, v8::Undefined(data->socket->_task->getIsolate()));
}
}
delete data;
}
void Socket::connect(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Socket* socket = Socket::get(args.Data())) {
socket->_direction = kConnect;
v8::String::Utf8Value node(args[0]->ToString());
v8::String::Utf8Value port(args[1]->ToString());
socket->_peerName = *node;
promiseid_t promise = socket->_task->allocatePromise();
SocketResolveData* data = new SocketResolveData();
std::memset(data, 0, sizeof(*data));
struct addrinfo hints;
hints.ai_family = PF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = 0;
data->resolver.data = data;
data->socket = socket;
data->promise = promise;
int result = uv_getaddrinfo(socket->_task->getLoop(), &data->resolver, onResolvedForConnect, *node, *port, &hints);
if (result != 0) {
std::string error = "uv_getaddrinfo: " + std::string(uv_strerror(result));
socket->_task->rejectPromise(promise, v8::Exception::Error(v8::String::NewFromUtf8(args.GetIsolate(), error.c_str())));
delete data;
}
args.GetReturnValue().Set(socket->_task->getPromise(promise));
}
}
void Socket::onResolvedForConnect(uv_getaddrinfo_t* resolver, int status, struct addrinfo* result) {
SocketResolveData* data = reinterpret_cast<SocketResolveData*>(resolver->data);
if (status != 0) {
std::string error = "uv_getaddrinfo: " + std::string(uv_strerror(status));
data->socket->_task->rejectPromise(data->promise, v8::Exception::Error(v8::String::NewFromUtf8(data->socket->_task->getIsolate(), error.c_str())));
} else {
uv_connect_t* request = new uv_connect_t();
std::memset(request, 0, sizeof(*request));
request->data = reinterpret_cast<void*>(data->promise);
int connectResult = uv_tcp_connect(request, &data->socket->_socket, result->ai_addr, onConnect);
if (connectResult != 0) {
std::string error("uv_tcp_connect: " + std::string(uv_strerror(connectResult)));
data->socket->_task->rejectPromise(data->promise, v8::Exception::Error(v8::String::NewFromUtf8(data->socket->_task->getIsolate(), error.c_str())));
}
}
delete data;
}
void Socket::onConnect(uv_connect_t* request, int status) {
promiseid_t promise = reinterpret_cast<intptr_t>(request->data);
if (promise != -1) {
Socket* socket = reinterpret_cast<Socket*>(request->handle->data);
if (status == 0) {
socket->_connected = true;
socket->_task->resolvePromise(promise, v8::Integer::New(socket->_task->getIsolate(), status));
} else {
std::string error("uv_tcp_connect: " + std::string(uv_strerror(status)));
socket->_task->rejectPromise(promise, v8::String::NewFromUtf8(socket->_task->getIsolate(), error.c_str()));
}
}
}
void Socket::listen(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Socket* socket = Socket::get(args.Data())) {
int backlog = args[0]->ToInteger()->Value();
if (socket->_onConnect.IsEmpty()) {
v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function> > callback(args.GetIsolate(), args[1].As<v8::Function>());
socket->_onConnect = callback;
int result = uv_listen(reinterpret_cast<uv_stream_t*>(&socket->_socket), backlog, onNewConnection);
if (result != 0) {
std::string error = "uv_listen: " + std::string(uv_strerror(result));
args.GetIsolate()->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(args.GetIsolate(), error.c_str(), v8::String::kNormalString, error.size())));
}
args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(), result));
} else {
args.GetIsolate()->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(args.GetIsolate(), "listen: Already listening.")));
}
}
}
void Socket::onNewConnection(uv_stream_t* server, int status) {
if (Socket* socket = reinterpret_cast<Socket*>(server->data)) {
v8::HandleScope handleScope(socket->_task->getIsolate());
TaskTryCatch tryCatch(socket->_task);
if (!socket->_onConnect.IsEmpty()) {
v8::Handle<v8::Function> callback = v8::Local<v8::Function>::New(socket->_task->getIsolate(), socket->_onConnect);
callback->Call(callback, 0, 0);
}
}
}
void Socket::accept(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Socket* socket = Socket::get(args.Data())) {
v8::HandleScope handleScope(args.GetIsolate());
Socket* client = new Socket(socket->_task);
client->_direction = kAccept;
promiseid_t promise = socket->_task->allocatePromise();
v8::Handle<v8::Value> promiseObject = socket->_task->getPromise(promise);
v8::Handle<v8::Object> result = v8::Local<v8::Object>::New(args.GetIsolate(), client->_object);
int status = uv_accept(reinterpret_cast<uv_stream_t*>(&socket->_socket), reinterpret_cast<uv_stream_t*>(&client->_socket));
if (status == 0) {
client->_connected = true;
socket->_task->resolvePromise(promise, result);
} else {
std::string error = "uv_accept: " + std::string(uv_strerror(status));
socket->_task->rejectPromise(promise, v8::String::NewFromUtf8(args.GetIsolate(), error.c_str(), v8::String::kNormalString, error.size()));
}
args.GetReturnValue().Set(promiseObject);
client->release();
}
}
void Socket::close(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Socket* socket = Socket::get(args.Data())) {
if (socket->_closePromise == -1) {
socket->_closePromise = socket->_task->allocatePromise();
args.GetReturnValue().Set(socket->_task->getPromise(socket->_closePromise));
socket->close();
}
}
}
void Socket::shutdown(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Socket* socket = Socket::get(args.Data())) {
if (socket->_tls) {
promiseid_t promise = socket->_task->allocatePromise();
socket->processTlsShutdown(promise);
args.GetReturnValue().Set(socket->_task->getPromise(promise));
} else {
promiseid_t promise = socket->_task->allocatePromise();
socket->shutdownInternal(promise);
args.GetReturnValue().Set(socket->_task->getPromise(promise));
}
}
}
void Socket::shutdownInternal(promiseid_t promise) {
uv_shutdown_t* request = new uv_shutdown_t();
std::memset(request, 0, sizeof(*request));
request->data = reinterpret_cast<void*>(promise);
int result = uv_shutdown(request, reinterpret_cast<uv_stream_t*>(&_socket), onShutdown);
if (result != 0) {
std::string error = "uv_shutdown: " + std::string(uv_strerror(result));
_task->rejectPromise(promise, v8::Exception::Error(v8::String::NewFromUtf8(_task->getIsolate(), error.c_str())));
delete request;
}
}
void Socket::processTlsShutdown(promiseid_t promise) {
_tls->shutdown();
if (!processSomeOutgoingTls(promise, onTlsShutdown)) {
shutdownInternal(promise);
}
}
void Socket::onTlsShutdown(uv_write_t* request, int status) {
if (Socket* socket = reinterpret_cast<Socket*>(request->handle->data)) {
promiseid_t promise = reinterpret_cast<intptr_t>(request->data);
socket->processTlsShutdown(promise);
}
}
void Socket::onError(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Socket* socket = Socket::get(args.Data())) {
v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function> > callback(args.GetIsolate(), args[0].As<v8::Function>());
socket->_onError = callback;
}
}
void Socket::read(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Socket* socket = Socket::get(args.Data())) {
v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function> > callback(args.GetIsolate(), args[0].As<v8::Function>());
socket->_onRead = callback;
int result = uv_read_start(reinterpret_cast<uv_stream_t*>(&socket->_socket), allocateBuffer, onRead);
promiseid_t promise = socket->_task->allocatePromise();
if (result != 0) {
std::string error = "uv_read_start: " + std::string(uv_strerror(result));
socket->_task->rejectPromise(promise, v8::String::NewFromUtf8(socket->_task->getIsolate(), error.c_str(), v8::String::kNormalString, error.size()));
} else {
socket->_task->resolvePromise(promise, v8::Undefined(socket->_task->getIsolate()));
}
}
}
void Socket::allocateBuffer(uv_handle_t* handle, size_t suggestedSize, uv_buf_t* buf) {
*buf = uv_buf_init(new char[suggestedSize], suggestedSize);
}
void Socket::onRead(uv_stream_t* stream, ssize_t readSize, const uv_buf_t* buffer) {
if (Socket* socket = reinterpret_cast<Socket*>(stream->data)) {
v8::HandleScope handleScope(socket->_task->getIsolate());
TaskTryCatch tryCatch(socket->_task);
v8::Handle<v8::Value> data;
if (readSize <= 0) {
socket->_connected = false;
v8::Local<v8::Function> callback = v8::Local<v8::Function>::New(socket->_task->getIsolate(), socket->_onRead);
if (!callback.IsEmpty()) {
data = v8::Undefined(socket->_task->getIsolate());
callback->Call(callback, 1, &data);
}
socket->close();
} else {
if (socket->_tls) {
socket->reportTlsErrors();
socket->_tls->writeEncrypted(buffer->base, readSize);
if (socket->_startTlsPromise != -1) {
TlsSession::HandshakeResult result = socket->_tls->handshake();
if (result == TlsSession::kDone) {
promiseid_t promise = socket->_startTlsPromise;
socket->_startTlsPromise = -1;
socket->_task->resolvePromise(promise, v8::Undefined(socket->_task->getIsolate()));
} else if (result == TlsSession::kFailed) {
promiseid_t promise = socket->_startTlsPromise;
socket->_startTlsPromise = -1;
char buffer[8192];
if (socket->_tls->getError(buffer, sizeof(buffer))) {
socket->_task->rejectPromise(promise, v8::String::NewFromUtf8(socket->_task->getIsolate(), buffer));
} else {
socket->_task->rejectPromise(promise, v8::Undefined(socket->_task->getIsolate()));
}
}
}
while (true) {
char plain[8192];
int result = socket->_tls->readPlain(plain, sizeof(plain));
if (result > 0) {
v8::Local<v8::Function> callback = v8::Local<v8::Function>::New(socket->_task->getIsolate(), socket->_onRead);
if (!callback.IsEmpty()) {
data = v8::String::NewFromOneByte(socket->_task->getIsolate(), reinterpret_cast<const uint8_t*>(plain), v8::String::kNormalString, result);
callback->Call(callback, 1, &data);
}
} else if (result == TlsSession::kReadFailed) {
socket->reportTlsErrors();
socket->close();
break;
} else if (result == TlsSession::kReadZero) {
v8::Local<v8::Function> callback = v8::Local<v8::Function>::New(socket->_task->getIsolate(), socket->_onRead);
if (!callback.IsEmpty()) {
data = v8::Undefined(socket->_task->getIsolate());
callback->Call(callback, 1, &data);
}
break;
} else {
break;
}
}
if (socket->_tls) {
socket->processOutgoingTls();
}
} else {
v8::Local<v8::Function> callback = v8::Local<v8::Function>::New(socket->_task->getIsolate(), socket->_onRead);
if (!callback.IsEmpty()) {
data = v8::String::NewFromOneByte(socket->_task->getIsolate(), reinterpret_cast<const uint8_t*>(buffer->base), v8::String::kNormalString, readSize);
callback->Call(callback, 1, &data);
}
}
}
}
delete[] buffer->base;
}
void Socket::write(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Socket* socket = Socket::get(args.Data())) {
promiseid_t promise = socket->_task->allocatePromise();
args.GetReturnValue().Set(socket->_task->getPromise(promise));
v8::Handle<v8::String> value = args[0].As<v8::String>();
if (!value.IsEmpty() && value->IsString()) {
if (socket->_tls) {
socket->reportTlsErrors();
int result;
int length;
if (value->ContainsOnlyOneByte()) {
length = value->Length();
std::vector<uint8_t> bytes(length);
value->WriteOneByte(bytes.data(), 0, bytes.size(), v8::String::NO_NULL_TERMINATION);
result = socket->_tls->writePlain(reinterpret_cast<const char*>(bytes.data()), bytes.size());
} else {
v8::String::Utf8Value utf8(value);
length = utf8.length();
result = socket->_tls->writePlain(*utf8, utf8.length());
}
char buffer[8192];
if (result <= 0 && socket->_tls->getError(buffer, sizeof(buffer))) {
socket->_task->rejectPromise(promise, v8::String::NewFromUtf8(args.GetIsolate(), buffer));
} else if (result < length) {
socket->_task->rejectPromise(promise, v8::Integer::New(socket->_task->getIsolate(), result));
} else {
socket->_task->resolvePromise(promise, v8::Integer::New(socket->_task->getIsolate(), result));
}
socket->processOutgoingTls();
} else {
v8::String::Utf8Value utf8(value);
int length;
char* rawBuffer = 0;
if (value->ContainsOnlyOneByte()) {
length = value->Length();
rawBuffer = new char[sizeof(uv_write_t) + length];
value->WriteOneByte(reinterpret_cast<uint8_t*>(rawBuffer) + sizeof(uv_write_t), 0, length, v8::String::NO_NULL_TERMINATION);
} else {
v8::String::Utf8Value utf8(value);
length = utf8.length();
rawBuffer = new char[sizeof(uv_write_t) + length];
std::memcpy(rawBuffer + sizeof(uv_write_t), *utf8, length);
}
uv_write_t* request = reinterpret_cast<uv_write_t*>(rawBuffer);
uv_buf_t buffer;
buffer.base = rawBuffer + sizeof(uv_write_t);
buffer.len = length;
request->data = reinterpret_cast<void*>(promise);
int result = uv_write(request, reinterpret_cast<uv_stream_t*>(&socket->_socket), &buffer, 1, onWrite);
if (result != 0) {
std::string error = "uv_write: " + std::string(uv_strerror(result));
socket->_task->rejectPromise(promise, v8::String::NewFromUtf8(args.GetIsolate(), error.c_str(), v8::String::kNormalString, error.size()));
}
}
} else {
socket->_task->rejectPromise(promise, v8::Integer::New(args.GetIsolate(), -2));
}
}
}
void Socket::onWrite(uv_write_t* request, int status) {
if (Socket* socket = reinterpret_cast<Socket*>(request->handle->data)) {
v8::HandleScope handleScope(socket->_task->getIsolate());
promiseid_t promise = reinterpret_cast<intptr_t>(request->data);
if (promise != -1) {
if (status == 0) {
socket->_task->resolvePromise(promise, v8::Integer::New(socket->_task->getIsolate(), status));
} else {
std::string error = "uv_write: " + std::string(uv_strerror(status));
socket->_task->rejectPromise(promise, v8::String::NewFromUtf8(socket->_task->getIsolate(), error.c_str(), v8::String::kNormalString, error.size()));
}
}
}
delete[] reinterpret_cast<char*>(request);
}
void Socket::onClose(uv_handle_t* handle) {
--_openCount;
if (Socket* socket = reinterpret_cast<Socket*>(handle->data)) {
if (socket->_closePromise != -1) {
v8::HandleScope scope(socket->_task->getIsolate());
promiseid_t promise = socket->_closePromise;
socket->_closePromise = -1;
socket->_connected = false;
socket->_task->resolvePromise(promise, v8::Integer::New(socket->_task->getIsolate(), 0));
}
if (socket->_object.IsEmpty()) {
delete socket;
}
}
}
void Socket::onShutdown(uv_shutdown_t* request, int status) {
if (Socket* socket = reinterpret_cast<Socket*>(request->handle->data)) {
promiseid_t promise = reinterpret_cast<intptr_t>(request->data);
if (status == 0) {
socket->_task->resolvePromise(promise, v8::Undefined(socket->_task->getIsolate()));
} else {
std::string error = "uv_shutdown: " + std::string(uv_strerror(status));
socket->_task->rejectPromise(promise, v8::Exception::Error(v8::String::NewFromUtf8(socket->_task->getIsolate(), error.c_str())));
}
}
delete request;
}
void Socket::getPeerName(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& info) {
if (Socket* socket = Socket::get(info.Data())) {
struct sockaddr_in6 addr;
int nameLength = sizeof(addr);
if (uv_tcp_getpeername(&socket->_socket, reinterpret_cast<sockaddr*>(&addr), &nameLength) == 0) {
char name[1024];
if (static_cast<size_t>(nameLength) > sizeof(struct sockaddr_in)) {
if (uv_ip6_name(&addr, name, sizeof(name)) == 0) {
info.GetReturnValue().Set(v8::String::NewFromUtf8(info.GetIsolate(), name));
}
} else {
if (uv_ip4_name(reinterpret_cast<struct sockaddr_in*>(&addr), name, sizeof(name)) == 0) {
info.GetReturnValue().Set(v8::String::NewFromUtf8(info.GetIsolate(), name));
}
}
}
}
}
void Socket::getPeerCertificate(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& info) {
if (Socket* socket = Socket::get(info.Data())) {
if (socket->_tls) {
std::vector<char> buffer(128 * 1024);
int result = socket->_tls->getPeerCertificate(buffer.data(), buffer.size());
if (result > 0) {
info.GetReturnValue().Set(v8::String::NewFromUtf8(info.GetIsolate(), buffer.data(), v8::String::kNormalString, result));
}
}
}
}
void Socket::isConnected(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& info) {
if (Socket* socket = Socket::get(info.Data())) {
info.GetReturnValue().Set(v8::Boolean::New(socket->_task->getIsolate(), socket->_connected));
}
}
void Socket::create(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope handleScope(args.GetIsolate());
if (Socket* socket = new Socket(Task::get(args.GetIsolate()))) {
v8::Handle<v8::Object> result = v8::Local<v8::Object>::New(args.GetIsolate(), socket->_object);
args.GetReturnValue().Set(result);
socket->release();
}
}
Socket* Socket::get(v8::Handle<v8::Value> socketObject) {
return reinterpret_cast<Socket*>(v8::Handle<v8::External>::Cast(socketObject)->Value());
}
void Socket::ref() {
if (++_refCount == 1) {
_object.ClearWeak();
}
}
void Socket::release() {
assert(_refCount >= 1);
if (--_refCount == 0) {
_object.SetWeak(this, onRelease);
}
}
void Socket::onRelease(const v8::WeakCallbackData<v8::Object, Socket>& data) {
data.GetParameter()->_object.Reset();
data.GetParameter()->close();
}

90
src/Socket.h Normal file
View File

@ -0,0 +1,90 @@
#ifndef INCLUDED_Socket
#define INCLUDED_Socket
#include <string>
#include <uv.h>
#include <v8.h>
typedef int promiseid_t;
class Task;
class TlsContext;
class TlsSession;
class Socket {
public:
static void create(const v8::FunctionCallbackInfo<v8::Value>& args);
void close();
static int getCount() { return _count; }
static int getOpenCount() { return _openCount; }
private:
Socket(Task* task);
~Socket();
Task* _task;
uv_tcp_t _socket;
TlsSession* _tls = 0;
promiseid_t _startTlsPromise = -1;
promiseid_t _closePromise = -1;
int _refCount = 1;
bool _connected = false;
std::string _peerName;
enum Direction { kUndetermined, kAccept, kConnect };
Direction _direction = kUndetermined;
static int _count;
static int _openCount;
static TlsContext* _defaultTlsContext;
v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object> > _object;
v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function> > _onConnect;
v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function> > _onRead;
v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function> > _onError;
static void startTls(const v8::FunctionCallbackInfo<v8::Value>& args);
static void stopTls(const v8::FunctionCallbackInfo<v8::Value>& args);
static void bind(const v8::FunctionCallbackInfo<v8::Value>& args);
static void connect(const v8::FunctionCallbackInfo<v8::Value>& args);
static void listen(const v8::FunctionCallbackInfo<v8::Value>& args);
static void accept(const v8::FunctionCallbackInfo<v8::Value>& args);
static void close(const v8::FunctionCallbackInfo<v8::Value>& args);
static void shutdown(const v8::FunctionCallbackInfo<v8::Value>& args);
static void read(const v8::FunctionCallbackInfo<v8::Value>& args);
static void onError(const v8::FunctionCallbackInfo<v8::Value>& args);
static void write(const v8::FunctionCallbackInfo<v8::Value>& args);
static void getPeerName(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& info);
static void getPeerCertificate(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& info);
static void isConnected(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& info);
static Socket* get(v8::Handle<v8::Value> socketObject);
static void onClose(uv_handle_t* handle);
static void onShutdown(uv_shutdown_t* request, int status);
static void onResolvedForBind(uv_getaddrinfo_t* resolver, int status, struct addrinfo* result);
static void onResolvedForConnect(uv_getaddrinfo_t* resolver, int status, struct addrinfo* result);
static void onConnect(uv_connect_t* request, int status);
static void onNewConnection(uv_stream_t* server, int status);
static void allocateBuffer(uv_handle_t* handle, size_t suggestedSize, uv_buf_t* buffer);
static void onRead(uv_stream_t* stream, ssize_t readSize, const uv_buf_t* buffer);
static void onWrite(uv_write_t* request, int status);
static void onRelease(const v8::WeakCallbackData<v8::Object, Socket>& data);
void processTlsShutdown(promiseid_t promise);
static void onTlsShutdown(uv_write_t* request, int status);
void shutdownInternal(promiseid_t promise);
bool processSomeOutgoingTls(promiseid_t promise, uv_write_cb callback);
void processOutgoingTls();
void reportTlsErrors();
void reportError(const char* error);
void ref();
void release();
};
#endif

749
src/Task.cpp Normal file
View File

@ -0,0 +1,749 @@
#include "Task.h"
#include "Database.h"
#include "File.h"
#include "Serialize.h"
#include "Socket.h"
#include "TaskStub.h"
#include "TaskTryCatch.h"
#include "TlsContextWrapper.h"
#include <algorithm>
#include <assert.h>
#include <cstring>
#include <fstream>
#include <iostream>
#include <libplatform/libplatform.h>
#include <map>
#include <sys/types.h>
#include <uv.h>
#include <v8.h>
#include <v8-platform.h>
#ifdef _WIN32
static const int STDIN_FILENO = 0;
#else
#include <unistd.h>
#endif
extern v8::Platform* gPlatform;
int gNextTaskId = 1;
int Task::_count;
struct ExportRecord {
v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function> > _persistent;
int _useCount;
ExportRecord(v8::Isolate* isolate, v8::Handle<v8::Function> function)
: _persistent(isolate, function),
_useCount(0) {
}
void ref() {
++_useCount;
}
bool release() {
return --_useCount == 0;
}
};
struct ImportRecord {
v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function> > _persistent;
exportid_t _export;
taskid_t _task;
Task* _owner;
int _useCount;
ImportRecord(v8::Isolate* isolate, v8::Handle<v8::Function> function, exportid_t exportId, taskid_t taskId, Task* owner)
: _persistent(isolate, function),
_export(exportId),
_task(taskId),
_owner(owner),
_useCount(0) {
_persistent.SetWeak(this, ImportRecord::onRelease);
}
void ref() {
if (_useCount++ == 0) {
// Make a strong ref again until an in-flight function call is finished.
_persistent.ClearWeak();
}
}
void release() {
if (--_useCount == 0) {
// All in-flight calls are finished. Make weak.
_persistent.SetWeak(this, ImportRecord::onRelease);
}
}
static void onRelease(const v8::WeakCallbackData<v8::Function, ImportRecord >& data) {
ImportRecord* import = data.GetParameter();
import->_owner->releaseExport(import->_task, import->_export);
for (size_t i = 0; i < import->_owner->_imports.size(); ++i) {
if (import->_owner->_imports[i] == import) {
import->_owner->_imports.erase(import->_owner->_imports.begin() + i);
break;
}
}
import->_persistent.Reset();
delete import;
}
};
Task::Task() {
_loop = uv_loop_new();
++_count;
v8::Isolate::CreateParams options;
options.array_buffer_allocator = &_allocator;
_isolate = v8::Isolate::New(options);
_isolate->SetData(0, this);
_isolate->SetCaptureStackTraceForUncaughtExceptions(true, 16);
}
Task::~Task() {
{
v8::Isolate::Scope isolateScope(_isolate);
v8::HandleScope handleScope(_isolate);
_context.Reset();
}
_isolate->Dispose();
_isolate = 0;
uv_loop_delete(_loop);
--_count;
}
v8::Handle<v8::Context> Task::getContext() {
return v8::Local<v8::Context>::New(_isolate, _context);
}
void Task::run() {
{
v8::Isolate::Scope isolateScope(_isolate);
v8::HandleScope handleScope(_isolate);
v8::Context::Scope contextScope(v8::Local<v8::Context>::New(_isolate, _context));
uv_run(_loop, UV_RUN_DEFAULT);
}
_promises.clear();
_exports.clear();
_imports.clear();
}
v8::Handle<v8::String> Task::loadFile(v8::Isolate* isolate, const char* fileName) {
v8::Handle<v8::String> value;
std::ifstream file(fileName, std::ios_base::in | std::ios_base::binary | std::ios_base::ate);
std::streampos fileSize = file.tellg();
if (fileSize >= 0) {
file.seekg(0, std::ios_base::beg);
char* buffer = new char[fileSize];
file.read(buffer, fileSize);
std::string contents(buffer, buffer + fileSize);
value = v8::String::NewFromOneByte(isolate, reinterpret_cast<const uint8_t*>(buffer), v8::String::kNormalString, fileSize);
delete[] buffer;
}
return value;
}
void Task::activate() {
v8::Isolate::Scope isolateScope(_isolate);
v8::HandleScope handleScope(_isolate);
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
if (!_importObject.IsEmpty()) {
v8::Local<v8::Object> imports(_importObject.Get(_isolate));
v8::Handle<v8::Array> keys = imports->GetOwnPropertyNames();
for (size_t i = 0; i < keys->Length(); ++i) {
global->SetAccessor(keys->Get(i).As<v8::String>(), getImportProperty);
}
}
global->Set(v8::String::NewFromUtf8(_isolate, "print"), v8::FunctionTemplate::New(_isolate, print));
global->Set(v8::String::NewFromUtf8(_isolate, "setTimeout"), v8::FunctionTemplate::New(_isolate, setTimeout));
global->Set(v8::String::NewFromUtf8(_isolate, "require"), v8::FunctionTemplate::New(_isolate, require));
global->SetAccessor(v8::String::NewFromUtf8(_isolate, "parent"), parent);
global->Set(v8::String::NewFromUtf8(_isolate, "exit"), v8::FunctionTemplate::New(_isolate, exit));
global->Set(v8::String::NewFromUtf8(_isolate, "utf8Length"), v8::FunctionTemplate::New(_isolate, utf8Length));
global->SetAccessor(v8::String::NewFromUtf8(_isolate, "exports"), getExports, setExports);
global->SetAccessor(v8::String::NewFromUtf8(_isolate, "imports"), getImports);
global->SetAccessor(v8::String::NewFromUtf8(_isolate, "version"), version);
global->SetAccessor(v8::String::NewFromUtf8(_isolate, "statistics"), statistics);
if (_trusted) {
global->Set(v8::String::NewFromUtf8(_isolate, "Database"), v8::FunctionTemplate::New(_isolate, Database::create));
global->Set(v8::String::NewFromUtf8(_isolate, "Socket"), v8::FunctionTemplate::New(_isolate, Socket::create));
global->Set(v8::String::NewFromUtf8(_isolate, "Task"), v8::FunctionTemplate::New(_isolate, TaskStub::create));
global->Set(v8::String::NewFromUtf8(_isolate, "TlsContext"), v8::FunctionTemplate::New(_isolate, TlsContextWrapper::create));
File::configure(_isolate, global);
}
v8::Local<v8::Context> context = v8::Context::New(_isolate, 0, global);
_context = v8::Persistent<v8::Context, v8::CopyablePersistentTraits<v8::Context> >(_isolate, context);
}
void Task::activate(const v8::FunctionCallbackInfo<v8::Value>& args) {
Task* task = Task::get(args.GetIsolate());
task->activate();
}
void Task::print(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope(args.GetIsolate());
v8::Local<v8::Context> context = args.GetIsolate()->GetCurrentContext();
v8::Handle<v8::Object> json = context->Global()->Get(v8::String::NewFromUtf8(args.GetIsolate(), "JSON"))->ToObject();
v8::Handle<v8::Function> stringify = v8::Handle<v8::Function>::Cast(json->Get(v8::String::NewFromUtf8(args.GetIsolate(), "stringify")));
Task* task = reinterpret_cast<Task*>(args.GetIsolate()->GetData(0));
TaskTryCatch tryCatch(task);
std::cout << "Task[" << task << ':' << task->_scriptName << "]>";
for (int i = 0; i < args.Length(); i++) {
std::cout << ' ';
v8::Handle<v8::Value> arg = args[i];
if (arg->IsNativeError()) {
arg = Serialize::storeMessage(task, v8::Exception::CreateMessage(arg));
}
v8::String::Utf8Value value(stringify->Call(json, 1, &arg));
std::cout << (*value ? *value : "(null)");
}
std::cout << '\n';
}
struct TimeoutData {
Task* _task;
v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function> > _callback;
};
void Task::setTimeout(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope(args.GetIsolate());
Task* task = reinterpret_cast<Task*>(args.GetIsolate()->GetData(0));
TimeoutData* timeout = new TimeoutData();
timeout->_task = task;
v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function> > function(args.GetIsolate(), v8::Handle<v8::Function>::Cast(args[0]));
timeout->_callback = function;
uv_timer_t* timer = new uv_timer_t();
uv_timer_init(task->_loop, timer);
timer->data = timeout;
uv_timer_start(timer, timeoutCallback, static_cast<uint64_t>(args[1].As<v8::Number>()->Value()), 0);
}
void Task::timeoutCallback(uv_timer_t* handle) {
TimeoutData* timeout = reinterpret_cast<TimeoutData*>(handle->data);
TaskTryCatch tryCatch(timeout->_task);
v8::HandleScope scope(timeout->_task->_isolate);
v8::Handle<v8::Function> function = v8::Local<v8::Function>::New(timeout->_task->_isolate, timeout->_callback);
function->Call(v8::Undefined(timeout->_task->_isolate), 0, 0);
delete timeout;
}
void Task::utf8Length(const v8::FunctionCallbackInfo<v8::Value>& args) {
Task* task = reinterpret_cast<Task*>(args.GetIsolate()->GetData(0));
TaskTryCatch tryCatch(task);
v8::HandleScope scope(task->_isolate);
args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(), args[0].As<v8::String>()->Utf8Length()));
}
void Task::exit(const v8::FunctionCallbackInfo<v8::Value>& args) {
::exit(args[0]->Int32Value());
}
void Task::kill() {
if (!_killed && _isolate) {
_killed = true;
v8::V8::TerminateExecution(_isolate);
}
}
void Task::execute(const char* fileName) {
v8::Isolate::Scope isolateScope(_isolate);
v8::HandleScope handleScope(_isolate);
v8::Context::Scope contextScope(v8::Local<v8::Context>::New(_isolate, _context));
v8::Handle<v8::String> name = v8::String::NewFromUtf8(_isolate, fileName);
v8::Handle<v8::String> source = loadFile(_isolate, fileName);
std::cout << "Running script " << fileName << "\n";
if (!_scriptName.size()) {
_scriptName = fileName;
}
if (!source.IsEmpty()) {
v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
if (!script.IsEmpty()) {
script->Run();
std::cout << "Script " << fileName << " completed\n";
} else {
std::cerr << "Failed to compile: " << fileName << ".\n";
}
} else {
std::string message;
message = "Failed to load file: ";
message += fileName;
_isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(_isolate, message.c_str())));
}
}
void Task::invokeExport(const v8::FunctionCallbackInfo<v8::Value>& args) {
Task* sender = Task::get(args.GetIsolate());
TaskTryCatch tryCatch(sender);
v8::Handle<v8::Object> data = v8::Handle<v8::Object>::Cast(args.Data());
exportid_t exportId = data->Get(v8::String::NewFromUtf8(args.GetIsolate(), "export"))->Int32Value();
taskid_t recipientId = data->Get(v8::String::NewFromUtf8(args.GetIsolate(), "task"))->Int32Value();
for (size_t i = 0; i < sender->_imports.size(); ++i) {
if (sender->_imports[i]->_task == recipientId && sender->_imports[i]->_export == exportId) {
sender->_imports[i]->ref();
break;
}
}
v8::Local<v8::Array> array = v8::Array::New(args.GetIsolate(), args.Length() + 1);
array->Set(0, args.This());
for (int i = 0; i < args.Length(); ++i) {
array->Set(i + 1, args[i]);
}
if (TaskStub* recipient = sender->get(recipientId)) {
promiseid_t promise = sender->allocatePromise();
sendPromiseExportMessage(sender, recipient, kInvokeExport, promise, exportId, array);
args.GetReturnValue().Set(sender->getPromise(promise));
} else {
args.GetReturnValue().Set(args.GetIsolate()->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(args.GetIsolate(), "Invoking a function on a nonexistant task."))));
}
}
v8::Handle<v8::Value> Task::invokeExport(TaskStub* from, Task* to, exportid_t exportId, const std::vector<char>& buffer) {
v8::Handle<v8::Value> result;
if (to->_exports[exportId]) {
v8::Handle<v8::Array> arguments = v8::Handle<v8::Array>::Cast(Serialize::load(to, from, buffer));
std::vector<v8::Handle<v8::Value> > argumentArray;
for (size_t i = 1; i < arguments->Length(); ++i) {
argumentArray.push_back(arguments->Get(i));
}
v8::Handle<v8::Function> function = v8::Local<v8::Function>::New(to->_isolate, to->_exports[exportId]->_persistent);
v8::Handle<v8::Value>* argumentPointer = 0;
if (argumentArray.size()) {
argumentPointer = &*argumentArray.begin();
}
result = function->Call(v8::Handle<v8::Object>::Cast(arguments->Get(0)), argumentArray.size(), argumentPointer);
} else {
std::cout << to->_scriptName << ": That's not an export we have (exportId=" << exportId << ", exports = " << to->_exports.size() << ")\n";
}
from->getStream().send(kReleaseImport, reinterpret_cast<char*>(&exportId), sizeof(exportId));
return result;
}
void Task::sendPromiseResolve(Task* from, TaskStub* to, promiseid_t promise, v8::Handle<v8::Value> result) {
if (!result.IsEmpty() && result->IsPromise()) {
// We're not going to serialize/deserialize a promise...
v8::Handle<v8::Object> data = v8::Object::New(from->_isolate);
data->Set(v8::String::NewFromUtf8(from->_isolate, "task"), v8::Int32::New(from->_isolate, to->getId()));
data->Set(v8::String::NewFromUtf8(from->_isolate, "promise"), v8::Int32::New(from->_isolate, promise));
v8::Handle<v8::Promise> promise = v8::Handle<v8::Promise>::Cast(result);
v8::Handle<v8::Function> then = v8::Function::New(from->_isolate, invokeThen, data);
promise->Then(then);
v8::Handle<v8::Function> catchCallback = v8::Function::New(from->_isolate, invokeCatch, data);
promise->Catch(catchCallback);
from->_isolate->RunMicrotasks();
} else {
sendPromiseMessage(from, to, kResolvePromise, promise, result);
}
}
void Task::sendPromiseReject(Task* from, TaskStub* to, promiseid_t promise, v8::Handle<v8::Value> result) {
if (!result.IsEmpty() && result->IsPromise()) {
// We're not going to serialize/deserialize a promise...
v8::Handle<v8::Object> data = v8::Object::New(from->_isolate);
data->Set(v8::String::NewFromUtf8(from->_isolate, "task"), v8::Int32::New(from->_isolate, to->getId()));
data->Set(v8::String::NewFromUtf8(from->_isolate, "promise"), v8::Int32::New(from->_isolate, promise));
v8::Handle<v8::Promise> promise = v8::Handle<v8::Promise>::Cast(result);
v8::Handle<v8::Function> then = v8::Function::New(from->_isolate, invokeThen, data);
promise->Then(then);
v8::Handle<v8::Function> catchCallback = v8::Function::New(from->_isolate, invokeCatch, data);
promise->Catch(catchCallback);
from->_isolate->RunMicrotasks();
} else {
sendPromiseMessage(from, to, kRejectPromise, promise, result);
}
}
void Task::sendPromiseMessage(Task* from, TaskStub* to, MessageType messageType, promiseid_t promise, v8::Handle<v8::Value> result) {
if (to) {
std::vector<char> buffer;
buffer.insert(buffer.end(), reinterpret_cast<char*>(&promise), reinterpret_cast<char*>(&promise) + sizeof(promise));
if (!result.IsEmpty() && !result->IsUndefined() && !result->IsNull()) {
Serialize::store(from, buffer, result);
}
to->getStream().send(messageType, &*buffer.begin(), buffer.size());
} else {
std::cerr << "Sending to a NULL task.\n";
}
}
void Task::sendPromiseExportMessage(Task* from, TaskStub* to, MessageType messageType, promiseid_t promise, exportid_t exportId, v8::Handle<v8::Value> result) {
std::vector<char> buffer;
buffer.insert(buffer.end(), reinterpret_cast<char*>(&promise), reinterpret_cast<char*>(&promise) + sizeof(promise));
buffer.insert(buffer.end(), reinterpret_cast<char*>(&exportId), reinterpret_cast<char*>(&exportId) + sizeof(exportId));
if (!result.IsEmpty() && !result->IsUndefined() && !result->IsNull()) {
Serialize::store(from, buffer, result);
}
to->getStream().send(messageType, &*buffer.begin(), buffer.size());
}
TaskStub* Task::get(taskid_t taskId) {
return taskId == kParentId ? _parent : _children[taskId];
}
void Task::invokeThen(const v8::FunctionCallbackInfo<v8::Value>& args) {
Task* from = reinterpret_cast<Task*>(args.GetIsolate()->GetData(0));
v8::Handle<v8::Object> data = v8::Handle<v8::Object>::Cast(args.Data());
TaskStub* to = from->get(data->Get(v8::String::NewFromUtf8(args.GetIsolate(), "task"))->Int32Value());
promiseid_t promise = data->Get(v8::String::NewFromUtf8(args.GetIsolate(), "promise"))->Int32Value();
sendPromiseMessage(from, to, kResolvePromise, promise, args[0]);
}
void Task::invokeCatch(const v8::FunctionCallbackInfo<v8::Value>& args) {
Task* from = reinterpret_cast<Task*>(args.GetIsolate()->GetData(0));
v8::Handle<v8::Object> data = v8::Handle<v8::Object>::Cast(args.Data());
TaskStub* to = from->get(data->Get(v8::String::NewFromUtf8(args.GetIsolate(), "task"))->Int32Value());
promiseid_t promise = data->Get(v8::String::NewFromUtf8(args.GetIsolate(), "promise"))->Int32Value();
sendPromiseMessage(from, to, kRejectPromise, promise, args[0]);
}
void Task::parent(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args) {
Task* task = reinterpret_cast<Task*>(args.GetIsolate()->GetData(0));
if (task->_parent) {
args.GetReturnValue().Set(task->_parent->getTaskObject());
} else {
args.GetReturnValue().Set(v8::Undefined(task->_isolate));
}
}
void Task::version(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args) {
Task* task = reinterpret_cast<Task*>(args.GetIsolate()->GetData(0));
args.GetReturnValue().Set(v8::String::NewFromUtf8(task->_isolate, v8::V8::GetVersion()));
}
void Task::getImportProperty(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args) {
v8::Local<v8::Object> imports = Task::get(args.GetIsolate())->_importObject.Get(args.GetIsolate());
args.GetReturnValue().Set(imports->Get(property));
}
void Task::getImports(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args) {
args.GetReturnValue().Set(v8::Local<v8::Object>::New(args.GetIsolate(), Task::get(args.GetIsolate())->_importObject));
}
void Task::getExports(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args) {
args.GetReturnValue().Set(v8::Local<v8::Object>::New(args.GetIsolate(), Task::get(args.GetIsolate())->_exportObject));
}
void Task::setExports(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& args) {
Task::get(args.GetIsolate())->_exportObject = v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object> >(args.GetIsolate(), v8::Handle<v8::Object>::Cast(value));
}
Task* Task::get(v8::Isolate* isolate) {
return reinterpret_cast<Task*>(isolate->GetData(0));
}
promiseid_t Task::allocatePromise() {
promiseid_t promiseId;
do {
promiseId = _nextPromise++;
} while (_promises.find(promiseId) != _promises.end());
v8::Persistent<v8::Promise::Resolver, v8::NonCopyablePersistentTraits<v8::Promise::Resolver> > promise(_isolate, v8::Promise::Resolver::New(_isolate));
_promises[promiseId] = promise;
return promiseId;
}
v8::Handle<v8::Promise::Resolver> Task::getPromise(promiseid_t promise) {
v8::Handle<v8::Promise::Resolver> result;
if (!_promises[promise].IsEmpty()) {
result = v8::Local<v8::Promise::Resolver>::New(_isolate, _promises[promise]);
}
return result;
}
void Task::resolvePromise(promiseid_t promise, v8::Handle<v8::Value> value) {
TaskTryCatch tryCatch(this);
if (!_promises[promise].IsEmpty()) {
v8::HandleScope handleScope(_isolate);
v8::Handle<v8::Promise::Resolver> resolver = v8::Local<v8::Promise::Resolver>::New(_isolate, _promises[promise]);
resolver->Resolve(value);
_isolate->RunMicrotasks();
_promises[promise].Reset();
_promises.erase(promise);
}
}
void Task::rejectPromise(promiseid_t promise, v8::Handle<v8::Value> value) {
TaskTryCatch tryCatch(this);
if (!_promises[promise].IsEmpty()) {
v8::HandleScope handleScope(_isolate);
v8::Handle<v8::Promise::Resolver> resolver = v8::Local<v8::Promise::Resolver>::New(_isolate, _promises[promise]);
resolver->Reject(value);
_isolate->RunMicrotasks();
_promises[promise].Reset();
_promises.erase(promise);
}
}
exportid_t Task::exportFunction(v8::Handle<v8::Function> function) {
exportid_t exportId = -1;
v8::Handle<v8::String> exportName = v8::String::NewFromUtf8(_isolate, "export");
v8::Local<v8::Value> value = function->GetHiddenValue(exportName);
if (!value.IsEmpty() && value->IsNumber())
{
exportid_t foundId = value->ToInteger(_isolate)->Int32Value();
if (_exports[foundId]) {
exportId = foundId;
}
}
if (exportId == -1) {
do {
exportId = _nextExport++;
} while (_exports[_nextExport]);
ExportRecord* record = new ExportRecord(_isolate, function);
function->SetHiddenValue(exportName, v8::Integer::New(_isolate, exportId));
_exports[exportId] = record;
}
if (_exports[exportId]) {
_exports[exportId]->ref();
}
return exportId;
}
void Task::releaseExport(taskid_t taskId, exportid_t exportId) {
if (TaskStub* task = get(taskId)) {
std::vector<char> buffer;
buffer.insert(buffer.end(), reinterpret_cast<char*>(&exportId), reinterpret_cast<char*>(&exportId) + sizeof(exportId));
task->getStream().send(kReleaseExport, &*buffer.begin(), buffer.size());
}
}
v8::Handle<v8::Function> Task::addImport(taskid_t taskId, exportid_t exportId) {
v8::Local<v8::Object> data = v8::Object::New(_isolate);
data->Set(v8::String::NewFromUtf8(_isolate, "export"), v8::Int32::New(_isolate, exportId));
data->Set(v8::String::NewFromUtf8(_isolate, "task"), v8::Int32::New(_isolate, taskId));
v8::Local<v8::Function> function = v8::Function::New(_isolate, Task::invokeExport, data);
_imports.push_back(new ImportRecord(_isolate, function, exportId, taskId, this));
return function;
}
void Task::statistics(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args) {
Task* task = reinterpret_cast<Task*>(args.GetIsolate()->GetData(0));
args.GetReturnValue().Set(task->getStatistics());
}
v8::Handle<v8::Object> Task::getStatistics() {
v8::Handle<v8::Object> result = v8::Object::New(_isolate);
result->Set(v8::String::NewFromUtf8(_isolate, "sockets"), v8::Integer::New(_isolate, Socket::getCount()));
result->Set(v8::String::NewFromUtf8(_isolate, "openSockets"), v8::Integer::New(_isolate, Socket::getOpenCount()));
result->Set(v8::String::NewFromUtf8(_isolate, "promises"), v8::Integer::New(_isolate, _promises.size()));
result->Set(v8::String::NewFromUtf8(_isolate, "exports"), v8::Integer::New(_isolate, _exports.size()));
result->Set(v8::String::NewFromUtf8(_isolate, "imports"), v8::Integer::New(_isolate, _imports.size()));
result->Set(v8::String::NewFromUtf8(_isolate, "tlsContexts"), v8::Integer::New(_isolate, TlsContextWrapper::getCount()));
uv_rusage_t usage;
if (uv_getrusage(&usage) == 0) {
result->Set(v8::String::NewFromUtf8(_isolate, "utime"), v8::Number::New(_isolate, usage.ru_utime.tv_sec + usage.ru_utime.tv_usec / 1000000.0));
result->Set(v8::String::NewFromUtf8(_isolate, "stime"), v8::Number::New(_isolate, usage.ru_stime.tv_sec + usage.ru_stime.tv_usec / 1000000.0));
result->Set(v8::String::NewFromUtf8(_isolate, "maxrss"), v8::Number::New(_isolate, usage.ru_maxrss));
}
return result;
}
void Task::onReceivePacket(int packetType, const char* begin, size_t length, void* userData) {
TaskStub* stub = reinterpret_cast<TaskStub*>(userData);
TaskStub* from = stub;
Task* to = stub->getOwner();
TaskTryCatch tryCatch(to);
v8::HandleScope scope(to->_isolate);
switch (static_cast<MessageType>(packetType)) {
case kStatistics:
{
promiseid_t promise;
std::memcpy(&promise, begin, sizeof(promise));
v8::Handle<v8::Value> result = to->getStatistics();
sendPromiseResolve(to, from, promise, result);
}
break;
case kInvokeExport:
{
promiseid_t promise;
exportid_t exportId;
std::memcpy(&promise, begin, sizeof(promise));
std::memcpy(&exportId, begin + sizeof(promise), sizeof(exportId));
v8::TryCatch tryCatch;
v8::Handle<v8::Value> result = invokeExport(from, to, exportId, std::vector<char>(begin + sizeof(promiseid_t) + sizeof(exportid_t), begin + length));
if (tryCatch.HasCaught()) {
sendPromiseReject(to, from, promise, Serialize::store(to, tryCatch));
} else {
sendPromiseResolve(to, from, promise, result);
}
}
break;
case kResolvePromise:
case kRejectPromise:
{
v8::Handle<v8::Value> arg;
promiseid_t promise;
std::memcpy(&promise, begin, sizeof(promiseid_t));
if (length > sizeof(promiseid_t)) {
arg = Serialize::load(to, from, std::vector<char>(begin + sizeof(promiseid_t), begin + length));
}
else {
arg = v8::Undefined(to->_isolate);
}
if (static_cast<MessageType>(packetType) == kResolvePromise) {
to->resolvePromise(promise, arg);
}
else {
to->rejectPromise(promise, arg);
}
}
break;
case kReleaseExport:
assert(length == sizeof(exportid_t));
exportid_t exportId;
memcpy(&exportId, begin, sizeof(exportId));
if (to->_exports[exportId]) {
if (to->_exports[exportId]->release()) {
to->_exports.erase(exportId);
}
}
break;
case kReleaseImport:
{
assert(length == sizeof(exportid_t));
exportid_t exportId;
memcpy(&exportId, begin, sizeof(exportId));
for (size_t i = 0; i < to->_imports.size(); ++i) {
if (to->_imports[i]->_task == from->getId() && to->_imports[i]->_export == exportId) {
to->_imports[i]->release();
break;
}
}
}
break;
case kSetTrusted:
{
assert(length == sizeof(bool));
bool trusted = false;
memcpy(&trusted, begin, sizeof(bool));
to->_trusted = trusted;
}
break;
case kActivate:
to->activate();
break;
case kExecute:
{
assert(length >= sizeof(promiseid_t));
v8::Handle<v8::Value> arg;
promiseid_t promise;
std::memcpy(&promise, begin, sizeof(promiseid_t));
arg = Serialize::load(to, from, std::vector<char>(begin + sizeof(promiseid_t), begin + length));
v8::TryCatch tryCatch(to->_isolate);
tryCatch.SetCaptureMessage(true);
tryCatch.SetVerbose(true);
to->execute(*v8::String::Utf8Value(arg));
if (tryCatch.HasCaught()) {
sendPromiseReject(to, from, promise, Serialize::store(to, tryCatch));
}
else {
sendPromiseResolve(to, from, promise, v8::Undefined(to->_isolate));
}
}
break;
case kKill:
::exit(1);
break;
case kSetImports:
{
v8::Handle<v8::Object> result = v8::Handle<v8::Object>::Cast(Serialize::load(to, from, std::vector<char>(begin, begin + length)));
to->_importObject = v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object> >(to->_isolate, result);
}
break;
case kGetExports:
promiseid_t promise;
assert(length == sizeof(promise));
std::memcpy(&promise, begin, sizeof(promiseid_t));
v8::Handle<v8::Object> result = v8::Local<v8::Object>::New(to->_isolate, to->_exportObject);
sendPromiseResolve(to, from, promise, result);
break;
}
}
void Task::configureFromStdin() {
_parent = TaskStub::createParent(this, STDIN_FILENO);
}
std::string Task::resolveRequire(const std::string& require) {
std::string result;
std::string path = _scriptName;
size_t position = path.rfind('/');
if (position != std::string::npos) {
path.resize(position + 1);
std::cout << "Looking in " << path << " for " << require << "\n";
if (require.find("..") == std::string::npos && require.find('/') == std::string::npos) {
result = path + require;
}
if (result.size() && require.rfind(".js") != require.size() - 3) {
result += ".js";
}
}
return result;
}
void Task::require(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope(args.GetIsolate());
Task* task = Task::get(args.GetIsolate());
v8::String::Utf8Value pathValue(args[0]);
if (*pathValue) {
std::string unresolved(*pathValue, *pathValue + pathValue.length());
std::string path = task->resolveRequire(unresolved);
if (!path.size()) {
args.GetReturnValue().Set(args.GetIsolate()->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(args.GetIsolate(), ("require(): Unable to resolve module: " + unresolved).c_str()))));
} else {
ScriptExportMap::iterator it = task->_scriptExports.find(path);
if (it != task->_scriptExports.end()) {
v8::Handle<v8::Object> exports = v8::Local<v8::Object>::New(args.GetIsolate(), it->second);
args.GetReturnValue().Set(exports);
} else {
v8::Handle<v8::Object> exports = v8::Object::New(args.GetIsolate());
task->_scriptExports[path] = v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object> >(args.GetIsolate(), exports);
v8::Handle<v8::String> name = v8::String::NewFromUtf8(args.GetIsolate(), path.c_str());
v8::Handle<v8::String> source = loadFile(args.GetIsolate(), path.c_str());
std::cout << "Requiring script " << path << "\n";
if (!source.IsEmpty()) {
v8::Handle<v8::Object> global = args.GetIsolate()->GetCurrentContext()->Global();
v8::Handle<v8::Value> oldExports = global->Get(v8::String::NewFromUtf8(args.GetIsolate(), "exports"));
global->Set(v8::String::NewFromUtf8(args.GetIsolate(), "exports"), exports);
v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
if (!script.IsEmpty()) {
script->Run();
std::cout << "Script " << path << " completed\n";
} else {
std::cerr << "Failed to compile script.\n";
}
global->Set(v8::String::NewFromUtf8(args.GetIsolate(), "exports"), oldExports);
args.GetReturnValue().Set(exports);
} else {
std::cerr << "Failed to load " << path << ".\n";
}
}
}
} else {
args.GetReturnValue().Set(args.GetIsolate()->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(args.GetIsolate(), "require(): No module specified."))));
}
}

163
src/Task.h Normal file
View File

@ -0,0 +1,163 @@
#ifndef INCLUDED_Task
#define INCLUDED_Task
#include "PacketStream.h"
#include <cstring>
#include <iostream>
#include <list>
#include <map>
#include <string>
#include <v8.h>
#include <v8-platform.h>
#include <vector>
struct ExportRecord;
struct ImportRecord;
class Task;
class TaskStub;
struct uv_loop_s;
typedef struct uv_loop_s uv_loop_t;
typedef int taskid_t;
typedef int promiseid_t;
typedef int exportid_t;
enum MessageType {
kResolvePromise,
kRejectPromise,
kInvokeExport,
kReleaseExport,
kReleaseImport,
kSetTrusted,
kActivate,
kExecute,
kKill,
kStatistics,
kSetImports,
kGetExports,
};
class NewArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
public:
void* Allocate(size_t length) {
char* bytes = new char[length];
std::memset(bytes, 0, length);
return bytes;
}
void* AllocateUninitialized(size_t length) {
return new char[length];
}
void Free(void* data, size_t length) {
delete[] reinterpret_cast<char*>(data);
}
};
class Task {
public:
Task();
~Task();
const std::string& getName() const { return _scriptName; }
v8::Isolate* getIsolate() { return _isolate; }
uv_loop_t* getLoop() { return _loop; }
v8::Handle<v8::Context> getContext();
void kill();
promiseid_t allocatePromise();
v8::Handle<v8::Promise::Resolver> getPromise(promiseid_t promise);
void resolvePromise(promiseid_t promise, v8::Handle<v8::Value> value);
void rejectPromise(promiseid_t promise, v8::Handle<v8::Value> value);
void configureFromStdin();
void setTrusted(bool trusted) { _trusted = trusted; }
void execute(const char* fileName);
void activate();
void run();
static int getCount() { return _count; }
static Task* get(v8::Isolate* isolate);
TaskStub* get(taskid_t taskId);
exportid_t exportFunction(v8::Handle<v8::Function> function);
static void invokeExport(const v8::FunctionCallbackInfo<v8::Value>& args);
v8::Handle<v8::Function> addImport(taskid_t taskId, exportid_t exportId);
void releaseExport(taskid_t taskId, exportid_t exportId);
private:
static int _count;
TaskStub* _stub = 0;
TaskStub* _parent = 0;
taskid_t _nextTask = 1;
static const taskid_t kParentId = 0;
std::map<taskid_t, TaskStub*> _children;
typedef std::map<std::string, v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object> > > ScriptExportMap;
ScriptExportMap _scriptExports;
bool _trusted = false;
bool _killed = false;
std::string _scriptName;
NewArrayBufferAllocator _allocator;
v8::Isolate* _isolate = 0;
std::map<promiseid_t, v8::Persistent<v8::Promise::Resolver, v8::CopyablePersistentTraits<v8::Promise::Resolver> > > _promises;
promiseid_t _nextPromise = 0;
uv_loop_t* _loop = 0;
std::map<exportid_t, ExportRecord*> _exports;
exportid_t _nextExport = 0;
v8::Persistent<v8::Context, v8::CopyablePersistentTraits<v8::Context> > _context;
std::vector<ImportRecord*> _imports;
v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object> > _importObject;
v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object> > _exportObject;
v8::Handle<v8::Object> getStatistics();
std::string resolveRequire(const std::string& require);
static void activate(const v8::FunctionCallbackInfo<v8::Value>& args);
static void exit(const v8::FunctionCallbackInfo<v8::Value>& args);
static void print(const v8::FunctionCallbackInfo<v8::Value>& args);
static void require(const v8::FunctionCallbackInfo<v8::Value>& args);
static void setTimeout(const v8::FunctionCallbackInfo<v8::Value>& args);
static void timeoutCallback(uv_timer_t* handle);
static void invokeThen(const v8::FunctionCallbackInfo<v8::Value>& args);
static void invokeCatch(const v8::FunctionCallbackInfo<v8::Value>& args);
static void parent(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args);
static void version(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args);
static void statistics(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args);
static void utf8Length(const v8::FunctionCallbackInfo<v8::Value>& args);
static void getImportProperty(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args);
static void getImports(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args);
static void getExports(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args);
static void setExports(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& args);
static v8::Handle<v8::Value> invokeExport(TaskStub* from, Task* to, exportid_t exportId, const std::vector<char>& buffer);
static void sendPromiseResolve(Task* from, TaskStub* to, promiseid_t promise, v8::Handle<v8::Value> result);
static void sendPromiseReject(Task* from, TaskStub* to, promiseid_t promise, v8::Handle<v8::Value> result);
static void onReceivePacket(int packetType, const char* begin, size_t length, void* userData);
static void sendPromiseMessage(Task* from, TaskStub* to, MessageType messageType, promiseid_t promise, v8::Handle<v8::Value> result);
static void sendPromiseExportMessage(Task* from, TaskStub* to, MessageType messageType, promiseid_t promiseId, exportid_t exportId, v8::Handle<v8::Value> result);
static v8::Handle<v8::String> loadFile(v8::Isolate* isolate, const char* fileName);
friend struct ImportRecord;
friend class TaskStub;
};
#endif

254
src/TaskStub.cpp Normal file
View File

@ -0,0 +1,254 @@
#include "TaskStub.h"
#include "PacketStream.h"
#include "Serialize.h"
#include "Task.h"
#include "TaskTryCatch.h"
#include <cstring>
#ifdef _WIN32
#include <io.h>
#include <windows.h>
#include <ws2tcpip.h>
static const int STDIN_FILENO = 0;
static const int STDOUT_FILENO = 1;
static const int STDERR_FILENO = 2;
#else
#include <unistd.h>
#endif
bool TaskStub::_determinedExecutable = false;
char TaskStub::_executable[1024];
void TaskStub::initialize() {
if (!_determinedExecutable) {
size_t size = sizeof(_executable);
uv_exepath(_executable, &size);
_determinedExecutable = true;
}
}
TaskStub::TaskStub() {
initialize();
std::memset(&_process, 0, sizeof(_process));
}
void TaskStub::ref() {
if (++_refCount == 1) {
_taskObject.ClearWeak();
}
}
void TaskStub::release() {
if (--_refCount == 0) {
_taskObject.SetWeak(this, onRelease);
}
}
TaskStub* TaskStub::createParent(Task* task, uv_file file) {
v8::Isolate::Scope isolateScope(task->_isolate);
v8::HandleScope scope(task->_isolate);
v8::Local<v8::Context> context = v8::Context::New(task->_isolate, 0);
context->Enter();
v8::Handle<v8::ObjectTemplate> parentTemplate = v8::ObjectTemplate::New(task->_isolate);
parentTemplate->SetInternalFieldCount(1);
v8::Handle<v8::Object> parentObject = parentTemplate->NewInstance();
TaskStub* parentStub = new TaskStub();
parentStub->_taskObject.Reset(task->_isolate, v8::Local<v8::Object>::New(task->_isolate, parentObject));
parentObject->SetInternalField(0, v8::External::New(task->_isolate, parentStub));
parentStub->_owner = task;
parentStub->_id = Task::kParentId;
if (uv_pipe_init(task->_loop, &parentStub->_stream.getStream(), 1) != 0) {
std::cerr << "uv_pipe_init failed\n";
}
parentStub->_stream.setOnReceive(Task::onReceivePacket, parentStub);
if (uv_pipe_open(&parentStub->_stream.getStream(), file) != 0) {
std::cerr << "uv_pipe_open failed\n";
}
parentStub->_stream.start();
return parentStub;
}
void TaskStub::create(const v8::FunctionCallbackInfo<v8::Value>& args) {
Task* parent = Task::get(args.GetIsolate());
v8::HandleScope scope(args.GetIsolate());
TaskStub* stub = new TaskStub();
v8::Handle<v8::External> data = v8::External::New(args.GetIsolate(), stub);
v8::Handle<v8::ObjectTemplate> taskTemplate = v8::ObjectTemplate::New(args.GetIsolate());
taskTemplate->SetAccessor(v8::String::NewFromUtf8(args.GetIsolate(), "trusted"), getTrusted, setTrusted, data);
taskTemplate->Set(v8::String::NewFromUtf8(args.GetIsolate(), "setImports"), v8::FunctionTemplate::New(args.GetIsolate(), setImports, data));
taskTemplate->Set(v8::String::NewFromUtf8(args.GetIsolate(), "getExports"), v8::FunctionTemplate::New(args.GetIsolate(), getExports, data));
taskTemplate->SetAccessor(v8::String::NewFromUtf8(args.GetIsolate(), "onExit"), getOnExit, setOnExit, data);
taskTemplate->Set(v8::String::NewFromUtf8(args.GetIsolate(), "activate"), v8::FunctionTemplate::New(args.GetIsolate(), TaskStub::activate, data));
taskTemplate->Set(v8::String::NewFromUtf8(args.GetIsolate(), "execute"), v8::FunctionTemplate::New(args.GetIsolate(), TaskStub::execute, data));
taskTemplate->Set(v8::String::NewFromUtf8(args.GetIsolate(), "kill"), v8::FunctionTemplate::New(args.GetIsolate(), TaskStub::kill, data));
taskTemplate->Set(v8::String::NewFromUtf8(args.GetIsolate(), "statistics"), v8::FunctionTemplate::New(args.GetIsolate(), TaskStub::statistics, data));
taskTemplate->SetInternalFieldCount(1);
v8::Handle<v8::Object> taskObject = taskTemplate->NewInstance();
stub->_taskObject.Reset(args.GetIsolate(), taskObject);
taskObject->SetInternalField(0, v8::External::New(args.GetIsolate(), stub));
stub->_owner = parent;
taskid_t id = 0;
if (parent) {
do {
id = parent->_nextTask++;
if (parent->_nextTask == Task::kParentId) {
++parent->_nextTask;
}
} while (parent->_children.find(id) != parent->_children.end());
parent->_children[id] = stub;
}
stub->_id = id;
char arg1[] = "--child";
char* argv[] = { _executable, arg1, 0 };
uv_pipe_t* pipe = reinterpret_cast<uv_pipe_t*>(&stub->_stream.getStream());
std::memset(pipe, 0, sizeof(*pipe));
if (uv_pipe_init(parent->getLoop(), pipe, 1) != 0) {
std::cerr << "uv_pipe_init failed\n";
}
uv_stdio_container_t io[3];
io[0].flags = static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_READABLE_PIPE | UV_WRITABLE_PIPE);
io[0].data.stream = reinterpret_cast<uv_stream_t*>(pipe);
io[1].flags = UV_INHERIT_FD;
io[1].data.fd = STDOUT_FILENO;
io[2].flags = UV_INHERIT_FD;
io[2].data.fd = STDERR_FILENO;
uv_process_options_t options = {0};
options.args = argv;
options.exit_cb = onProcessExit;
options.stdio = io;
options.stdio_count = sizeof(io) / sizeof(*io);
options.file = argv[0];
stub->_process.data = stub;
int result = uv_spawn(parent->getLoop(), &stub->_process, &options);
if (result == 0) {
stub->_stream.setOnReceive(Task::onReceivePacket, stub);
stub->_stream.start();
args.GetReturnValue().Set(taskObject);
} else {
std::cerr << "uv_spawn failed: " << uv_strerror(result) << "\n";
}
}
void TaskStub::onProcessExit(uv_process_t* process, int64_t status, int terminationSignal) {
TaskStub* stub = reinterpret_cast<TaskStub*>(process->data);
if (!stub->_onExit.IsEmpty()) {
TaskTryCatch tryCatch(stub->_owner);
v8::HandleScope scope(stub->_owner->_isolate);
v8::Handle<v8::Function> callback = v8::Local<v8::Function>::New(stub->_owner->_isolate, stub->_onExit);
v8::Handle<v8::Value> args[2];
args[0] = v8::Integer::New(stub->_owner->_isolate, status);
args[1] = v8::Integer::New(stub->_owner->_isolate, terminationSignal);
callback->Call(callback, 2, &args[0]);
}
stub->_stream.close();
stub->_owner->_children.erase(stub->_id);
uv_close(reinterpret_cast<uv_handle_t*>(process), 0);
}
void TaskStub::onRelease(const v8::WeakCallbackData<v8::Object, TaskStub>& data) {
}
void TaskStub::getTrusted(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args) {
args.GetReturnValue().Set(v8::Boolean::New(args.GetIsolate(), false));
}
void TaskStub::setTrusted(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& args) {
if (TaskStub* stub = TaskStub::get(args.Data())) {
bool trusted = value->BooleanValue();
stub->_stream.send(kSetTrusted, reinterpret_cast<char*>(&trusted), sizeof(trusted));
}
}
void TaskStub::getExports(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (TaskStub* stub = TaskStub::get(args.Data())) {
TaskTryCatch tryCatch(stub->_owner);
v8::HandleScope scope(args.GetIsolate());
promiseid_t promise = stub->_owner->allocatePromise();
Task::sendPromiseMessage(stub->_owner, stub, kGetExports, promise, v8::Undefined(args.GetIsolate()));
args.GetReturnValue().Set(stub->_owner->getPromise(promise));
}
}
void TaskStub::setImports(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (TaskStub* stub = TaskStub::get(args.Data())) {
std::vector<char> buffer;
Serialize::store(Task::get(args.GetIsolate()), buffer, args[0]);
stub->_stream.send(kSetImports, &*buffer.begin(), buffer.size());
}
}
void TaskStub::getOnExit(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args) {
TaskTryCatch tryCatch(TaskStub::get(args.Data())->_owner);
v8::HandleScope scope(args.GetIsolate());
args.GetReturnValue().Set(v8::Local<v8::Function>::New(args.GetIsolate(), TaskStub::get(args.Data())->_onExit));
}
void TaskStub::setOnExit(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& args) {
TaskTryCatch tryCatch(TaskStub::get(args.Data())->_owner);
v8::HandleScope scope(args.GetIsolate());
v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function> > function(args.GetIsolate(), v8::Handle<v8::Function>::Cast(value));
TaskStub::get(args.Data())->_onExit = function;
}
TaskStub* TaskStub::get(v8::Handle<v8::Value> object) {
return reinterpret_cast<TaskStub*>(v8::Handle<v8::External>::Cast(object)->Value());
}
v8::Handle<v8::Object> TaskStub::getTaskObject() {
return v8::Local<v8::Object>::New(_owner->getIsolate(), _taskObject);
}
void TaskStub::activate(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (TaskStub* stub = TaskStub::get(args.Data())) {
TaskTryCatch tryCatch(stub->_owner);
v8::HandleScope scope(args.GetIsolate());
v8::String::Utf8Value fileName(args[0]->ToString(args.GetIsolate()));
stub->_stream.send(kActivate, 0, 0);
}
}
void TaskStub::execute(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (TaskStub* stub = TaskStub::get(args.Data())) {
TaskTryCatch tryCatch(stub->_owner);
v8::HandleScope scope(args.GetIsolate());
promiseid_t promise = stub->_owner->allocatePromise();
Task::sendPromiseMessage(stub->_owner, stub, kExecute, promise, args[0]);
args.GetReturnValue().Set(stub->_owner->getPromise(promise));
}
}
void TaskStub::kill(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (TaskStub* stub = TaskStub::get(args.Data())) {
uv_process_kill(&stub->_process, SIGTERM);
}
}
void TaskStub::statistics(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (TaskStub* stub = TaskStub::get(args.Data())) {
TaskTryCatch tryCatch(stub->_owner);
v8::HandleScope scope(args.GetIsolate());
promiseid_t promise = stub->_owner->allocatePromise();
Task::sendPromiseMessage(stub->_owner, stub, kStatistics, promise, v8::Undefined(args.GetIsolate()));
args.GetReturnValue().Set(stub->_owner->getPromise(promise));
}
}

63
src/TaskStub.h Normal file
View File

@ -0,0 +1,63 @@
#ifndef INCLUDED_TaskStub
#define INCLUDED_TaskStub
#include "PacketStream.h"
#include <v8.h>
class Task;
typedef int taskid_t;
class TaskStub {
public:
void ref();
void release();
static void create(const v8::FunctionCallbackInfo<v8::Value>& args);
static TaskStub* createParent(Task* task, uv_file file);
static void initialize();
taskid_t getId() { return _id; }
Task* getOwner() { return _owner; }
v8::Handle<v8::Object> getTaskObject();
PacketStream& getStream() { return _stream; }
private:
v8::Persistent<v8::Object> _taskObject;
int _refCount = 1;
Task* _owner = 0;
PacketStream _stream;
taskid_t _id = -1;
uv_process_t _process;
v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function> > _onExit;
static bool _determinedExecutable;
static char _executable[1024];
TaskStub();
static TaskStub* get(v8::Handle<v8::Value> object);
static void getTrusted(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args);
static void setTrusted(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& args);
static void getExports(const v8::FunctionCallbackInfo<v8::Value>& args);
static void setImports(const v8::FunctionCallbackInfo<v8::Value>& args);
static void getOnExit(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args);
static void setOnExit(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& args);
static void activate(const v8::FunctionCallbackInfo<v8::Value>& args);
static void execute(const v8::FunctionCallbackInfo<v8::Value>& args);
static void kill(const v8::FunctionCallbackInfo<v8::Value>& args);
static void statistics(const v8::FunctionCallbackInfo<v8::Value>& args);
static void onRelease(const v8::WeakCallbackData<v8::Object, TaskStub>& data);
static void onProcessExit(uv_process_t* process, int64_t status, int terminationSignal);
};
#endif

57
src/TaskTryCatch.cpp Normal file
View File

@ -0,0 +1,57 @@
#include "TaskTryCatch.h"
#include "Task.h"
#include <iostream>
const char* TaskTryCatch::toString(const v8::String::Utf8Value& value) {
return *value ? *value : "(null)";
}
TaskTryCatch::TaskTryCatch(Task* task) {
_tryCatch.SetCaptureMessage(true);
_tryCatch.SetVerbose(true);
}
TaskTryCatch::~TaskTryCatch() {
if (_tryCatch.HasCaught()) {
if (v8::Isolate* isolate = v8::Isolate::GetCurrent()) {
if (Task* task = reinterpret_cast<Task*>(isolate->GetData(0))) {
std::cerr << "Task[" << task << ':' << task->getName() << "] ";
}
}
std::cerr << "Exception:\n";
v8::Handle<v8::Message> message(_tryCatch.Message());
if (!message.IsEmpty()) {
std::cerr
<< toString(v8::String::Utf8Value(message->GetScriptResourceName()))
<< ':'
<< message->GetLineNumber()
<< ": "
<< toString(v8::String::Utf8Value(_tryCatch.Exception()))
<< '\n';
std::cerr << toString(v8::String::Utf8Value(message->GetSourceLine())) << '\n';
for (int i = 0; i < message->GetStartColumn(); ++i) {
std::cerr << ' ';
}
for (int i = message->GetStartColumn(); i < message->GetEndColumn(); ++i) {
std::cerr << '^';
}
if (!message->GetStackTrace().IsEmpty()) {
for (int i = 0; i < message->GetStackTrace()->GetFrameCount(); ++i) {
std::cerr << "oops " << i << "\n";
}
}
std::cerr << '\n';
} else {
std::cerr << toString(v8::String::Utf8Value(_tryCatch.Exception())) << '\n';
}
v8::String::Utf8Value stackTrace(_tryCatch.StackTrace());
if (stackTrace.length() > 0) {
std::cerr << *stackTrace << '\n';
}
}
}

18
src/TaskTryCatch.h Normal file
View File

@ -0,0 +1,18 @@
#ifndef INCLUDED_TaskTryCatch
#define INCLUDED_TaskTryCatch
#include <v8.h>
class Task;
class TaskTryCatch {
public:
TaskTryCatch(Task* task);
~TaskTryCatch();
private:
v8::TryCatch _tryCatch;
static const char* toString(const v8::String::Utf8Value& value);
};
#endif

1126
src/Tls.cpp Normal file

File diff suppressed because it is too large Load Diff

50
src/Tls.h Normal file
View File

@ -0,0 +1,50 @@
#ifndef INCLUDED_Tls
#define INCLUDED_Tls
#include <cstddef>
class TlsSession;
class TlsContext {
public:
static TlsContext* create();
virtual ~TlsContext() {}
virtual TlsSession* createSession() { return 0; }
virtual bool setCertificate(const char* certificate) { return false; }
virtual bool setPrivateKey(const char* privateKey) { return false; }
virtual bool addTrustedCertificate(const char* certificate) { return false; }
};
class TlsSession {
public:
virtual ~TlsSession() {}
virtual void setHostname(const char* hostname) {}
virtual void startAccept() = 0;
virtual void startConnect() = 0;
virtual void shutdown() = 0;
virtual int getPeerCertificate(char* buffer, size_t bytes) { return -1; }
enum HandshakeResult {
kDone,
kMore,
kFailed,
};
virtual HandshakeResult handshake() = 0;
enum ReadResult {
kReadZero = -1,
kReadFailed = -2,
};
virtual int readPlain(char* buffer, size_t bytes) = 0;
virtual int writePlain(const char* buffer, size_t bytes) = 0;
virtual int readEncrypted(char* buffer, size_t bytes) = 0;
virtual int writeEncrypted(const char* buffer, size_t bytes) = 0;
virtual bool getError(char* buffer, size_t bytes) { return false; }
};
#endif

115
src/TlsContextWrapper.cpp Normal file
View File

@ -0,0 +1,115 @@
#include "TlsContextWrapper.h"
#include "Task.h"
#include "Tls.h"
#include <assert.h>
int TlsContextWrapper::_count = 0;
void TlsContextWrapper::create(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope handleScope(args.GetIsolate());
if (TlsContextWrapper* wrapper = new TlsContextWrapper(Task::get(args.GetIsolate()))) {
v8::Handle<v8::Object> result = v8::Local<v8::Object>::New(args.GetIsolate(), wrapper->_object);
args.GetReturnValue().Set(result);
wrapper->release();
}
}
TlsContextWrapper::TlsContextWrapper(Task* task) {
++_count;
v8::HandleScope scope(task->getIsolate());
v8::Handle<v8::External> identifier = v8::External::New(task->getIsolate(), reinterpret_cast<void*>(&TlsContextWrapper::create));
v8::Handle<v8::External> data = v8::External::New(task->getIsolate(), this);
v8::Local<v8::ObjectTemplate> wrapperTemplate = v8::ObjectTemplate::New(task->getIsolate());
wrapperTemplate->SetInternalFieldCount(2);
wrapperTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "setCertificate"), v8::FunctionTemplate::New(task->getIsolate(), setCertificate, data));
wrapperTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "setPrivateKey"), v8::FunctionTemplate::New(task->getIsolate(), setPrivateKey, data));
wrapperTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "addTrustedCertificate"), v8::FunctionTemplate::New(task->getIsolate(), addTrustedCertificate, data));
v8::Local<v8::Object> wrapperObject = wrapperTemplate->NewInstance();
wrapperObject->SetInternalField(0, identifier);
wrapperObject->SetInternalField(1, data);
_object.Reset(task->getIsolate(), wrapperObject);
_context = TlsContext::create();
_task = task;
}
TlsContextWrapper::~TlsContextWrapper() {
close();
--_count;
}
void TlsContextWrapper::close() {
if (_context) {
delete _context;
_context = 0;
}
}
void TlsContextWrapper::onRelease(const v8::WeakCallbackData<v8::Object, TlsContextWrapper>& data) {
data.GetParameter()->_object.Reset();
delete data.GetParameter();
}
TlsContextWrapper* TlsContextWrapper::get(v8::Handle<v8::Value> value) {
TlsContextWrapper* result = 0;
if (!value.IsEmpty()
&& value->IsObject())
{
v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
if (object->InternalFieldCount() == 2
&& v8::Handle<v8::External>::Cast(object->GetInternalField(0))->Value() == &TlsContextWrapper::create)
{
result = reinterpret_cast<TlsContextWrapper*>(v8::Handle<v8::External>::Cast(object->GetInternalField(1))->Value());
}
}
return result;
}
TlsContextWrapper* TlsContextWrapper::get(const v8::FunctionCallbackInfo<v8::Value>& args) {
return reinterpret_cast<TlsContextWrapper*>(v8::Handle<v8::External>::Cast(args.Data())->Value());
}
void TlsContextWrapper::ref() {
if (++_refCount == 1) {
_object.ClearWeak();
}
}
void TlsContextWrapper::release() {
assert(_refCount >= 1);
if (--_refCount == 0) {
_object.SetWeak(this, onRelease);
}
}
void TlsContextWrapper::setCertificate(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (TlsContextWrapper* wrapper = TlsContextWrapper::get(args)) {
v8::String::Utf8Value value(args[0]->ToString(args.GetIsolate()));
wrapper->_context->setCertificate(*value);
}
}
void TlsContextWrapper::setPrivateKey(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (TlsContextWrapper* wrapper = TlsContextWrapper::get(args)) {
v8::String::Utf8Value value(args[0]->ToString(args.GetIsolate()));
wrapper->_context->setPrivateKey(*value);
}
}
void TlsContextWrapper::addTrustedCertificate(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (TlsContextWrapper* wrapper = TlsContextWrapper::get(args)) {
v8::String::Utf8Value value(args[0]->ToString(args.GetIsolate()));
wrapper->_context->addTrustedCertificate(*value);
}
}
int TlsContextWrapper::getCount()
{
return _count;
}

42
src/TlsContextWrapper.h Normal file
View File

@ -0,0 +1,42 @@
#ifndef INCLUDED_TlsContextWrapper
#define INCLUDED_TlsContextWrapper
#include <v8.h>
class Task;
class TlsContext;
class TlsContextWrapper {
public:
static void create(const v8::FunctionCallbackInfo<v8::Value>& args);
void close();
static TlsContextWrapper* get(v8::Handle<v8::Value> value);
static void setCertificate(const v8::FunctionCallbackInfo<v8::Value>& args);
static void setPrivateKey(const v8::FunctionCallbackInfo<v8::Value>& args);
static void addTrustedCertificate(const v8::FunctionCallbackInfo<v8::Value>& args);
static void onRelease(const v8::WeakCallbackData<v8::Object, TlsContextWrapper>& data);
TlsContext* getContext() { return _context; }
static int getCount();
private:
TlsContextWrapper(Task* task);
~TlsContextWrapper();
static TlsContextWrapper* get(const v8::FunctionCallbackInfo<v8::Value>& args);
TlsContext* _context = 0;
Task* _task = 0;
v8::Persistent<v8::Object> _object;
int _refCount = 1;
static int _count;
void ref();
void release();
};
#endif

75
src/main.cpp Normal file
View File

@ -0,0 +1,75 @@
#include "Task.h"
#include "TaskStub.h"
#include "TaskTryCatch.h"
#include <cstring>
#include <libplatform/libplatform.h>
#include <uv.h>
#include <v8.h>
#include <v8-platform.h>
#if !defined (_WIN32) && !defined (__MACH__)
#include <signal.h>
#include <sys/prctl.h>
#include <unistd.h>
#endif
v8::Platform* gPlatform = 0;
int main(int argc, char* argv[]) {
uv_setup_args(argc, argv);
TaskStub::initialize();
v8::V8::InitializeICU();
gPlatform = v8::platform::CreateDefaultPlatform();
v8::V8::InitializePlatform(gPlatform);
v8::V8::Initialize();
v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
bool isChild = false;
const char* coreTask = "core/core.js";
for (int i = 1; i < argc; ++i) {
if (!std::strcmp(argv[i], "--child")) {
isChild = true;
} else {
coreTask = argv[i];
}
}
#if !defined (_WIN32)
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
perror("signal");
}
#endif
if (isChild) {
#if !defined (_WIN32) && !defined (__MACH__)
prctl(PR_SET_PDEATHSIG, SIGHUP);
#endif
Task task;
task.configureFromStdin();
task.activate();
task.run();
} else {
#if !defined (_WIN32) && !defined (__MACH__)
setpgid(0, 0);
#endif
Task task;
task.setTrusted(true);
task.activate();
{
v8::Isolate::Scope isolateScope(task.getIsolate());
v8::HandleScope handleScope(task.getIsolate());
v8::Context::Scope contextScope(task.getContext());
TaskTryCatch tryCatch(&task);
task.execute(coreTask);
}
task.run();
}
v8::V8::Dispose();
return 0;
}

7
tests/01-nop Executable file
View File

@ -0,0 +1,7 @@
#!/bin/bash
cat > test.js << EOF
print("hi");
EOF
$SANDBOXOS test.js

7
tests/02-valgrind Executable file
View File

@ -0,0 +1,7 @@
#!/bin/bash
cat > test.js << EOF
print("hi");
EOF
valgrind --log-file=$LOGDIR/valgrind.log $SANDBOXOS test.js

19
tests/03-child Executable file
View File

@ -0,0 +1,19 @@
#!/bin/bash
cat > test.js << EOF
var task = new Task();
task.onExit = function() {
print("child exited");
};
task.activate();
task.execute("child.js").then(function() {
print("child started");
});
EOF
cat > child.js << EOF
print("I am the child process.");
exit(0);
EOF
$SANDBOXOS test.js

27
tests/04-promise Executable file
View File

@ -0,0 +1,27 @@
#!/bin/bash
cat > test.js << EOF
var task = new Task();
task.activate();
task.execute("child.js").then(function() {
task.getExports().then(function(exports) {
return exports.add(1, 1);
}).then(function(sum) {
if (sum == 2) {
exit(0);
} else {
exit(1);
}
});
});
EOF
cat > child.js << EOF
exports = {
add: function(left, right) {
return left + right;
}
}
EOF
$SANDBOXOS test.js

26
tests/05-promise-remote-throw Executable file
View File

@ -0,0 +1,26 @@
#!/bin/bash
cat > test.js << EOF
var task = new Task();
task.activate();
task.execute("child.js").then(function() {
task.getExports().then(function(exports) {
return exports.add(1, 1);
}).then(function(sum) {
exit(1);
}).catch(function(error) {
print("Caught: " + error.message);
exit(0);
});
});
EOF
cat > child.js << EOF
exports = {
add: function(left, right) {
throw new Error("fail");
}
}
EOF
$SANDBOXOS test.js

80
tests/06-restartTask Executable file
View File

@ -0,0 +1,80 @@
#!/bin/bash
mkdir -p packages
for i in filesystem packager; do
ln -s $ROOT/packages/$i packages/$i
done
cp -R $ROOT/packages/system packages/system
mkdir -p packages/test
cat > packages/test/test.js << EOF
print("Hello!");
File.writeFile("packages/hello/hello.js", "this will fail to run!$^!U#%^#$%#%");
var p = imports.system.restartTask("hello");
print("here is our promise: " + p.toString());
print(p);
p.then(function(r) {
print("restart succeeded when it should not have: " + r);
imports.system.finishTest(1);
}).catch(function(e) {
print("restart failed: " + e);
print(e.toString());
for (var i in e) {
print(i);
print(e[i]);
}
imports.system.finishTest(0);
});
EOF
cat > packages/test/package.json << EOF
{
"name": "test",
"start": "test.js",
"trusted": true,
"imports": ["packager", "system"]
}
EOF
cat >> packages/system/system.js << EOF
exports.finishTest = function(result) {
exit(result);
}
EOF
mkdir -p packages/hello
cat > packages/hello/hello.js << EOF
print("Hi.");
EOF
cat > packages/hello/package.json << EOF
{
"name": "hello",
"start": "hello.js"
}
EOF
mkdir -p packages/auth
cat > packages/auth/auth.js << EOF
exports = {
query: function() { return null; },
getCredentials: function() { return {user: 'test', token: 'token'}; },
verifyCredentials: function() { return {permissions: []}; },
};
EOF
cat > packages/auth/package.json << EOF
{
"name": "auth",
"start": "auth.js"
}
EOF
$SANDBOXOS packages/system/system.js

29
tests/07-promise-remote-reject Executable file
View File

@ -0,0 +1,29 @@
#!/bin/bash
cat > test.js << EOF
var task = new Task();
task.activate();
task.execute("child.js").then(function() {
task.getExports().then(function(exports) {
return exports.add(1, 1);
}).then(function(sum) {
exit(1);
}).catch(function(error) {
print(error);
print("Caught: " + error.message);
exit(0);
});
});
EOF
cat > child.js << EOF
exports = {
add: function(left, right) {
return new Promise(function(resolve, reject) {
reject(new Error("oops"));
});
}
}
EOF
$SANDBOXOS test.js

34
tests/08-database Executable file
View File

@ -0,0 +1,34 @@
#!/bin/bash
mkdir testdb
cat > test.js << EOF
var db = new Database("testdb");
if (db.get("a")) {
exit(1);
}
db.set("a", 1);
if (db.get("a") != 1) {
exit(1);
}
db.set("b", 2);
db.set("c", 3);
var expected = ['a', 'b', 'c'];
var have = db.getAll();
for (var i = 0; i < have.length; i++) {
var item = have[i];
if (expected.indexOf(item) == -1) {
print("Did not find " + item + " in db.");
exit(2);
} else {
expected.splice(expected.indexOf(item), 1);
}
}
if (expected.length) {
print("Expected but did not find: " + JSON.stringify(expected));
exit(3);
}
EOF
$SANDBOXOS test.js

9
tests/09-this Executable file
View File

@ -0,0 +1,9 @@
#!/bin/bash
cat > test.js << EOF
var task = new Task();
task.activate.bind(null).apply();
exit(0);
EOF
$SANDBOXOS test.js

36
tools/run-tests Executable file
View File

@ -0,0 +1,36 @@
#!/bin/bash
export ROOT=$(cd $(dirname ${BASH_SOURCE[0]})/..; pwd)
TMP=$ROOT/tmp
LOGS=$ROOT/logs
TESTS=$ROOT/tests
export SANDBOXOS=$ROOT/sandboxos
mkdir $TMP 2> /dev/null
mkdir $LOGS 2> /dev/null
REQUESTED_TESTS=$*
if [[ -z $REQUESTED_TESTS ]]; then
REQUESTED_TESTS=$(ls $TESTS/* | xargs basename -a)
fi
for NAME in $REQUESTED_TESTS; do
TEST=$TESTS/$NAME
echo -n "$(basename $TEST) "
rm -rf $TMP/*
pushd $TMP > /dev/null
export LOGDIR=$LOGS/$NAME
mkdir $LOGDIR 2> /dev/null
unbuffer $TEST > $LOGDIR/stdout.log 2> $LOGDIR/stderr.log
RESULT=$?
popd > /dev/null
if [[ $RESULT != 0 ]]; then
echo "FAILED (with exit code $RESULT)"
exit $RESULT
else
echo "SUCCESS"
fi
done
echo
echo "All tests completed successfully."

118
tools/update-deps Executable file
View File

@ -0,0 +1,118 @@
#!/usr/bin/python -u
import os
import shutil
import subprocess
import sys
if len(sys.argv) == 1:
kWork = os.path.join('deps', sys.platform)
elif len(sys.argv) == 2:
kWork = sys.argv[1]
if not os.path.isdir(kWork):
os.makedirs(kWork)
os.chdir(kWork)
kUvRepository = 'https://github.com/libuv/libuv.git'
kUvBranch = 'v1.0.0'
kUvWork = 'uv'
kV8Repository = 'https://github.com/v8/v8.git'
kV8Branch = 'branch-heads/4.9'
kV8Work = 'v8'
def updateUv():
print 'libuv'
print
clean = False
if os.path.exists(os.path.join(kUvWork, '.update-deps-branch')):
haveBranch = open(os.path.join(kUvWork, '.update-deps-branch'), 'r').read().strip()
if kUvBranch != haveBranch:
print haveBranch, '=>', kUvBranch
clean = True
else:
clean = True
if clean:
if os.path.isdir(os.path.join(kUvWork)):
print 'Cleaning', kUvWork
shutil.rmtree(os.path.join(kUvWork))
if not os.path.isdir(kUvWork):
subprocess.check_call(['git', 'clone', '--branch', kUvBranch, kUvRepository, kUvWork])
open(os.path.join(kUvWork, '.update-deps-branch'), 'w').write(kUvBranch)
if sys.platform in ('darwin', 'win32'):
if not os.path.isdir(os.path.join(kUvWork, 'build', 'gyp')):
subprocess.check_call(['git', 'clone', 'https://chromium.googlesource.com/external/gyp.git', 'build/gyp'], cwd=kUvWork)
if sys.platform == 'linux2':
subprocess.check_call(['./gyp_uv.py', '-f', 'make'], cwd=kUvWork)
subprocess.check_call(['make', '-j8', '-C', 'out'], cwd=kUvWork)
elif sys.platform == 'darwin':
subprocess.check_call(['./gyp_uv.py', '-f', 'xcode'], cwd=kUvWork)
subprocess.check_call(['xcodebuild', '-ARCHS="x86_64"', '-project', 'uv.xcodeproj', '-configuration', 'Release', '-target', 'All'], cwd=kUvWork)
elif sys.platform == 'win32':
env = os.environ.copy()
env['VCINSTALLDIR'] = ''
env['WINDOWSSDKDIR'] = ''
subprocess.check_call(['cmd', '/C', 'call', 'vcbuild.bat', 'release', 'x64'], cwd=kUvWork, env=env)
def updateV8():
print 'v8'
print
clean = False
if False:
if os.path.exists(os.path.join(kV8Work, '.update-deps-branch')):
haveBranch = open(os.path.join(kV8Work, '.update-deps-branch'), 'r').read().strip()
if kV8Branch != haveBranch:
print haveBranch, '=>', kV8Branch
clean = True
else:
clean = True
if clean:
if os.path.isdir(kV8Work):
shutil.rmtree(kV8Work)
# XXX We modify one .py file which assumes invalid things.
if os.path.isfile(os.path.join(kV8Work, 'tools/swarming_client/third_party/requests/packages/urllib3/contrib/pyopenssl.py')):
print 'resetting tools/swarming_client'
subprocess.check_call(['git', 'reset', '--hard'], cwd=os.path.join(kV8Work, 'tools', 'swarming_client'))
extension = ''
if sys.platform == 'win32':
extension = '.bat'
if not os.path.isdir(kV8Work):
subprocess.check_call(['fetch' + extension, 'v8'])
win32Env = os.environ.copy()
win32Env['GYP_MSVS_VERSION'] = '2013'
win32Env['DEPOT_TOOLS_WIN_TOOLCHAIN'] = '0'
open(os.path.join(kV8Work, '.update-deps-branch'), 'w').write(kV8Branch)
subprocess.check_call(['git', 'fetch'], cwd=kV8Work)
subprocess.check_call(['git', 'checkout', kV8Branch], cwd=kV8Work)
if sys.platform == 'win32':
subprocess.check_call(['gclient' + extension, 'sync'], cwd=kV8Work, env=win32Env)
else:
subprocess.check_call(['gclient' + extension, 'sync'], cwd=kV8Work)
contents = open(os.path.join(kV8Work, 'tools/swarming_client/third_party/requests/packages/urllib3/contrib/pyopenssl.py'), 'r').readlines()
contents = [line for line in contents if not 'SSLv3' in line]
open(os.path.join(kV8Work, 'tools/swarming_client/third_party/requests/packages/urllib3/contrib/pyopenssl.py'), 'w').write(''.join(contents))
if sys.platform == 'linux2':
subprocess.check_call(['make', '-j4', 'native'], cwd=kV8Work)
elif sys.platform == 'darwin':
subprocess.check_call(['build/gyp_v8', '-Dtarget_arch=x64'], cwd=kV8Work)
subprocess.check_call(['xcodebuild', '-project', 'build/all.xcodeproj', '-configuration', 'Release'], cwd=kV8Work)
elif sys.platform == 'win32':
subprocess.check_call(['python', 'build\\gyp_v8', '-Dtarget_arch=x64'], cwd=kV8Work, env=win32Env)
subprocess.check_call(['devenv.com', '/Build', 'Release', 'build\\All.sln'], cwd=kV8Work)
if __name__ == '__main__':
updateUv()
updateV8()