Initial commit
674
LICENSE
Normal file
@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
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 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
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 GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
108
README.md
Normal file
@ -0,0 +1,108 @@
|
||||
# hnakra
|
||||
|
||||
The successor to HLHV. More stable and capable than ever!
|
||||
|
||||
Hnakra is similar to an HTTP reverse proxy, but it uses a custom protocol to
|
||||
allow services to connect to the router instead of the other way around. This
|
||||
approach provides a greater level of security and ease of setup, and allows
|
||||
services to do cool things like hide behind a firewall on a completely different
|
||||
network.
|
||||
|
||||
Hnakra is also designed to be multi-protocol, so services can make their content
|
||||
and functionality available over HTTP, HTTPS, gemini, etc. In theory, any
|
||||
request/response based protocol that uses URLs could be integrated into Hnakra.
|
||||
Currently, only HTTPS is supported, but other protocols are coming soon.
|
||||
|
||||
## Security features
|
||||
|
||||
Hnakra has a highly configurable user/permission system for dictating what
|
||||
services are allowed to do what. Services authenticate the identity of the
|
||||
router using its TLS certificate, and the router authenticates the identity of
|
||||
connecting services using a supplied username/key combination. This is so each
|
||||
service can be given limited access to a particular portion of the site.
|
||||
|
||||
## Router server
|
||||
|
||||
This module comes with a basic router implementation, located at `cmd/router`.
|
||||
It can be configured using `/etc/hnakra/hnakra.conf`. Each line in the
|
||||
configuration file can be blank, a command, or a comment. A list of available
|
||||
commands:
|
||||
|
||||
### `alias <alias> -> <target>`
|
||||
When a request comes in with a host matching `alias`, it is replaced with
|
||||
`target` before being routed to the appropriate service. If `(fallback)` is
|
||||
specified as `alias`, any host that doesn't match a pre-existing alias will be
|
||||
rewritten as `target`. By default, hosts equivalent to `localhost` are aliased
|
||||
to the target `@`. It is reccomended to alias your domain name to `@` as well so
|
||||
you don't need to hard-code it into your services.
|
||||
|
||||
### `unalias <alias>`
|
||||
`unalias` undoes an alias that was created previously.
|
||||
|
||||
### `keyPath <path>`
|
||||
`keyPath` specifies the location of the TLS key to load.
|
||||
|
||||
### `certPath <path>`
|
||||
`certPath` specifies the location of the TLS certificate to load.
|
||||
|
||||
### `rcon`
|
||||
This command enables the remote console, which lets you monitor the state of the
|
||||
router from a webpage. It is available at `https://@/debug/rcon`. Before
|
||||
accessing it, you must set up at least one user with rcon access.
|
||||
|
||||
### `router <port>`
|
||||
This command specifies the port that services will connect to. If not specified,
|
||||
the value of `$HNAKRA_ROUTER_PORT` will be used. If that is also blank, it will
|
||||
default to a value of `2048`.
|
||||
|
||||
### `https [port]`
|
||||
This command enables the HTTPS protocol. If the port is left blank, the value of
|
||||
`$HNAKRA_HTTPS_PORT` will be used. If that is also blank, it will default to a
|
||||
value of `443`.
|
||||
|
||||
### `http [port]`
|
||||
This command enables the insecure HTTP protocol. If the port is left blank, the
|
||||
value of `$HNAKRA_HTTP_PORT` will be used. If that is also blank, it will
|
||||
default to a value of `80`.
|
||||
|
||||
### `gemini [port]`
|
||||
This command enables the gemini protocol. If the port is left blank, the value
|
||||
of `$HNAKRA_GEMINI_PORT` will be used. If that is also blank, it will defaul to
|
||||
a value of `1965`.
|
||||
|
||||
### `noSecurity I AM NOT USING THIS IN PRODUCTION.`
|
||||
This command disables username/key authentication entirely and lets any service
|
||||
mount anywhere. For this to work, it must be typed exactly as shown above.
|
||||
|
||||
### `user <name>:<key hash> -> <capability>, ...`
|
||||
The `user` command creates a new user under the specified name, with the
|
||||
specified bcrypt key hash. Following the user is a `->` symbol, then a
|
||||
comma-separated list of capabilities that user has. A capability can be a mount
|
||||
point pattern, or the value `(rcon)`. Mount point patterns are interpreted as
|
||||
follows:
|
||||
|
||||
- A singular glob, `*`, allows the user to mount services on any host or path.
|
||||
- A URL pattern without any globs or trailing slashes (such as `https://@/path`)
|
||||
allows the user to mount services on that exact path only.
|
||||
- If the host component of the pattern is prefixed with a `.`, it will match
|
||||
subdomains of that host as well as the host itself.
|
||||
- If the host component of the pattern is prefixed with a `*`, it will match any
|
||||
host ending in the host component (not including the glob).
|
||||
- If the path component of the pattern is affixed with a `/`, it will match any
|
||||
paths under it, as well as the path itself.
|
||||
- If the path component of the pattern is affixed with a `*`, it will match any
|
||||
path that starts with the path component (not including the glob).
|
||||
|
||||
For example, the pattern `https://.@/static/` allows a user to mount services on
|
||||
`@` (or any subdomain of `@`) at `/static` (or anything underneath `/static`) on
|
||||
the HTTPS protocol.
|
||||
|
||||
Specifiying a value as `(rcon)` as opposed to a mount point pattern will allow
|
||||
access to the rcon panel (if it is enabled) by logging in with this user's
|
||||
credentials.
|
||||
|
||||
## Service package
|
||||
|
||||
This module also comes with a package that allows you to easily create a service
|
||||
in just a few lines of code. Some examples can be found in the `examples`
|
||||
directory.
|
79
cmd/router/main.go
Normal file
@ -0,0 +1,79 @@
|
||||
package main
|
||||
|
||||
import "io"
|
||||
import "os"
|
||||
import "log"
|
||||
import "hnakra/rcon"
|
||||
import "hnakra/rotate"
|
||||
import "hnakra/config"
|
||||
import "hnakra/router"
|
||||
import "hnakra/srvhttps"
|
||||
import "hnakra/srvhnakra"
|
||||
|
||||
const banner = "\n" +
|
||||
" -=\\\n" +
|
||||
"__. __|.\\___\n" +
|
||||
" - ``.__.-` ```'-. | | |\\ | |\\ | / |''| |\\\n" +
|
||||
" `-, u `. |--| | \\| |-\\ |< |-< |-\\\n" +
|
||||
" ,-' ,```` VVv | | | | | \\ | \\ | \\ | \\\n" +
|
||||
"/___-' ````--//----'''``\n" +
|
||||
" |/ DISTRIBUTED HOLANET SERVER ROUTER\n" +
|
||||
" '/"
|
||||
|
||||
func main () {
|
||||
// setup logging
|
||||
logDir := os.Getenv("HNAKRA_LOG_DIR")
|
||||
if logDir != "" {
|
||||
logger, err := rotate.New(logDir)
|
||||
if err != nil { log.Fatal("cannot access log dir:", err) }
|
||||
log.SetOutput(logger)
|
||||
}
|
||||
rcon := rcon.New("/debug/rcon")
|
||||
originalWriter := log.Writer()
|
||||
log.SetOutput(io.MultiWriter(originalWriter, rcon))
|
||||
|
||||
log.Println(banner)
|
||||
|
||||
// load config
|
||||
log.Println("... loading config")
|
||||
conf, err := config.File("/etc/hnakra/hnakra.conf")
|
||||
if err != nil { log.Fatal(err) }
|
||||
log.Println("(i) users:")
|
||||
conf.OverUsers(func (name string, user config.User) bool {
|
||||
log.Println(" -", name)
|
||||
return true
|
||||
})
|
||||
log.Println("(i) aliases:")
|
||||
if conf.AliasFallback() != "" {
|
||||
log.Println(" - (fallback) ->", conf.AliasFallback())
|
||||
}
|
||||
conf.OverAliases(func (alias, target string) bool{
|
||||
log.Println(" -", alias, "->", target)
|
||||
return true
|
||||
})
|
||||
rcon.SetConfig(conf)
|
||||
|
||||
// start servers
|
||||
log.Println("... starting up")
|
||||
rout := router.New(conf)
|
||||
srvhnakra := &srvhnakra.Server { Config: conf, Router: rout }
|
||||
rcon.SetRouter(rout)
|
||||
if conf.RconEnable() {
|
||||
err = rout.HTTPMux().Handle("@/debug/rcon/", rcon)
|
||||
if err != nil { log.Fatalln("XXX", err) }
|
||||
} else {
|
||||
log.SetOutput(originalWriter)
|
||||
}
|
||||
if conf.HTTPSEnable() {
|
||||
srvhttps := &srvhttps.Server { Config: conf, Handler: rout }
|
||||
go httpsRoutine(srvhttps)
|
||||
}
|
||||
|
||||
err = srvhnakra.ListenAndServe()
|
||||
if err != nil { log.Println("XXX", err) }
|
||||
}
|
||||
|
||||
func httpsRoutine (server *srvhttps.Server) {
|
||||
err := server.ListenAndServe()
|
||||
if err != nil { log.Println("XXX", err) }
|
||||
}
|
31
config/config.go
Normal file
@ -0,0 +1,31 @@
|
||||
package config
|
||||
|
||||
import "crypto/tls"
|
||||
|
||||
type Config interface {
|
||||
User (name string) User
|
||||
OverUsers (func (name string, user User) bool)
|
||||
|
||||
RconEnable () bool
|
||||
|
||||
RouterPort () int
|
||||
HTTPSPort () int
|
||||
HTTPSEnable () bool
|
||||
HTTPPort () int
|
||||
HTTPEnable () bool
|
||||
GeminiPort () int
|
||||
GeminiEnable () bool
|
||||
Certificate () tls.Certificate
|
||||
|
||||
ResolveAlias (alias string) string
|
||||
AliasFallback () string
|
||||
OverAliases (func (alias, target string) bool)
|
||||
}
|
||||
|
||||
type User interface {
|
||||
Validate (key []byte) bool
|
||||
RconAllow () bool
|
||||
|
||||
OverPatterns (func (pattern string) bool)
|
||||
CanMountOn (scheme, host, path string) bool
|
||||
}
|
491
config/file.go
Normal file
@ -0,0 +1,491 @@
|
||||
package config
|
||||
|
||||
import "os"
|
||||
import "io"
|
||||
import "bufio"
|
||||
import "errors"
|
||||
import "unicode"
|
||||
import "strconv"
|
||||
import "strings"
|
||||
import "crypto/tls"
|
||||
import "golang.org/x/crypto/bcrypt"
|
||||
|
||||
type matchMode int; const (
|
||||
// exactly match
|
||||
matchModeExact matchMode = iota
|
||||
|
||||
// match all starting with/ending with (depending on context)
|
||||
matchModeGlob
|
||||
|
||||
// match exactly, as well as anything underneath (hierarchically)
|
||||
matchModeExtend
|
||||
)
|
||||
|
||||
type pattern struct {
|
||||
matchAll bool
|
||||
|
||||
scheme string
|
||||
host string
|
||||
path string
|
||||
hostMode matchMode
|
||||
pathMode matchMode
|
||||
}
|
||||
|
||||
func (pattern pattern) String () (output string) {
|
||||
if pattern.matchAll {
|
||||
return "*"
|
||||
}
|
||||
output += pattern.scheme + "://"
|
||||
|
||||
switch pattern.hostMode {
|
||||
case matchModeExtend: output += "."
|
||||
case matchModeGlob: output += "*"
|
||||
}
|
||||
output += pattern.host
|
||||
|
||||
output += pattern.path
|
||||
switch pattern.pathMode {
|
||||
case matchModeExtend: output += "/"
|
||||
case matchModeGlob: output += "*"
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (pattern pattern) Match (scheme, host, path string) bool {
|
||||
if pattern.matchAll { return true }
|
||||
if scheme != pattern.scheme && pattern.scheme != "*" { return false }
|
||||
|
||||
switch pattern.hostMode {
|
||||
case matchModeExact:
|
||||
if host != pattern.host { return false }
|
||||
case matchModeGlob:
|
||||
if !strings.HasSuffix(host, pattern.host) { return false }
|
||||
case matchModeExtend:
|
||||
match :=
|
||||
host == pattern.host ||
|
||||
strings.HasSuffix(host, "." + pattern.host)
|
||||
if !match { return false }
|
||||
default: return false
|
||||
}
|
||||
|
||||
switch pattern.pathMode {
|
||||
case matchModeExact:
|
||||
if path != pattern.path { return false }
|
||||
case matchModeGlob:
|
||||
if !strings.HasPrefix(path, pattern.path) { return false }
|
||||
case matchModeExtend:
|
||||
match :=
|
||||
path == pattern.path ||
|
||||
strings.HasSuffix(path, "." + pattern.path)
|
||||
if !match { return false }
|
||||
default: return false
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// user is a real user parsed from a configuration file.
|
||||
type user struct {
|
||||
name string
|
||||
rconAllow bool
|
||||
noSecurity bool
|
||||
hash []byte
|
||||
patterns []pattern
|
||||
}
|
||||
|
||||
func (user user) String () (output string) {
|
||||
output += user.name + " ->"
|
||||
first := true
|
||||
if user.rconAllow {
|
||||
output += " (rcon)"
|
||||
first = false
|
||||
}
|
||||
for _, pattern := range user.patterns {
|
||||
if !first {
|
||||
output += ","
|
||||
}
|
||||
first = false
|
||||
output += " "
|
||||
output += pattern.String()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (user user) RconAllow () bool {
|
||||
return user.rconAllow
|
||||
}
|
||||
|
||||
func (user user) OverPatterns (callback func (pattern string) bool) {
|
||||
for _, pattern := range user.patterns {
|
||||
if !callback(pattern.String()) { break }
|
||||
}
|
||||
}
|
||||
|
||||
func (user user) Validate (key []byte) bool {
|
||||
if user.noSecurity == true { return true }
|
||||
return bcrypt.CompareHashAndPassword(user.hash, key) == nil
|
||||
}
|
||||
|
||||
func (user user) CanMountOn (scheme, host, path string) bool {
|
||||
if user.noSecurity == true { return true }
|
||||
for _, pattern := range user.patterns {
|
||||
if pattern.Match(scheme, host, path) { return true }
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// dummy is a dummy user that validates everything to true.
|
||||
type dummy struct { }
|
||||
|
||||
func (dummy) Validate ([]byte) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (dummy) CanMountOn (string, string, string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// config is a config read from a file
|
||||
type config struct {
|
||||
noSecurity bool
|
||||
users map[string] user
|
||||
|
||||
rconEnable bool
|
||||
routerPort int
|
||||
httpsEnable bool
|
||||
httpsPort int
|
||||
httpEnable bool
|
||||
httpPort int
|
||||
geminiEnable bool
|
||||
geminiPort int
|
||||
|
||||
fallback string
|
||||
aliases map[string]string
|
||||
|
||||
keyPath string
|
||||
certPath string
|
||||
cert tls.Certificate
|
||||
}
|
||||
|
||||
// File reads configuration values in order of precedence from:
|
||||
// - The file specified by path
|
||||
// - Environment variables
|
||||
// - Default values
|
||||
// If the given file is inaccessible, this function will not return an error.
|
||||
// However, if the file is accessible but it could not be parsed, it will return
|
||||
// an error.
|
||||
func File (path string) (Config, error) {
|
||||
conf := new(config)
|
||||
conf.populateDefault()
|
||||
file, err := os.Open(path)
|
||||
if err == nil {
|
||||
err = conf.readFrom(file)
|
||||
if err != nil { return nil, err }
|
||||
}
|
||||
return conf, nil
|
||||
}
|
||||
|
||||
// Default returns configuration values from environment variables. Unset values
|
||||
// are populated with default values.
|
||||
func Default () Config {
|
||||
conf := new(config)
|
||||
conf.populateDefault()
|
||||
return conf
|
||||
}
|
||||
|
||||
// ReadFrom reads a config file from a reader. It always closes the reader when
|
||||
// it is done.
|
||||
func ReadFrom (reader io.ReadCloser) (Config, error) {
|
||||
config := new(config)
|
||||
err := config.readFrom(reader)
|
||||
if err != nil { return nil, err }
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func (config *config) readFrom (reader io.ReadCloser) error {
|
||||
buferred := bufio.NewReader(reader)
|
||||
defer reader.Close()
|
||||
|
||||
config.aliases = map[string]string {
|
||||
"localhost": "@",
|
||||
"127.0.0.1": "@",
|
||||
"::ffff:127.0.0.1": "@",
|
||||
"::1": "@",
|
||||
}
|
||||
config.users = make(map[string] user)
|
||||
|
||||
var key string
|
||||
var val string
|
||||
var state int
|
||||
for {
|
||||
ch, _, err := buferred.ReadRune()
|
||||
if err != nil {
|
||||
if err == io.EOF { break }
|
||||
return err
|
||||
}
|
||||
|
||||
switch state {
|
||||
case 0:
|
||||
// wait for key or comment
|
||||
if ch == '#' {
|
||||
state = 3
|
||||
} else if !unicode.IsSpace(ch) {
|
||||
state = 1
|
||||
buferred.UnreadRune()
|
||||
}
|
||||
break
|
||||
|
||||
case 1:
|
||||
// ignore whitespace until value (or EOL)
|
||||
if ch == '\n' {
|
||||
err = config.handleKeyVal(key, "")
|
||||
if err != nil { return err }
|
||||
key = ""
|
||||
val = ""
|
||||
state = 0
|
||||
} else if unicode.IsSpace(ch) {
|
||||
state = 2
|
||||
} else {
|
||||
key += string(ch)
|
||||
}
|
||||
break
|
||||
|
||||
case 2:
|
||||
// get key until EOL
|
||||
if ch == '\n' {
|
||||
err = config.handleKeyVal(key, strings.TrimSpace(val))
|
||||
if err != nil { return err }
|
||||
key = ""
|
||||
val = ""
|
||||
state = 0
|
||||
} else {
|
||||
val += string(ch)
|
||||
}
|
||||
break
|
||||
|
||||
case 3:
|
||||
// ignore comment until EOL
|
||||
if ch == '\n' {
|
||||
state = 0
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
cert, err := tls.LoadX509KeyPair(config.certPath, config.keyPath)
|
||||
if err != nil { return err }
|
||||
config.cert = cert
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (config *config) populateDefault () {
|
||||
defaultRouterPortStr := os.Getenv("HNAKRA_ROUTER_PORT")
|
||||
defaultHTTPSPortStr := os.Getenv("HNAKRA_HTTPS_PORT")
|
||||
defaultHTTPPortStr := os.Getenv("HNAKRA_HTTP_PORT")
|
||||
defaultGeminiPortStr := os.Getenv("HNAKRA_GEMINI_PORT")
|
||||
defaultRouterPort, _ := strconv.Atoi(defaultRouterPortStr)
|
||||
defaultHTTPSPort, _ := strconv.Atoi(defaultHTTPSPortStr)
|
||||
defaultHTTPPort, _ := strconv.Atoi(defaultHTTPPortStr)
|
||||
defaultGeminiPort, _ := strconv.Atoi(defaultGeminiPortStr)
|
||||
if defaultRouterPort == 0 { defaultRouterPort = 2048 }
|
||||
if defaultHTTPSPort == 0 { defaultHTTPSPort = 443 }
|
||||
if defaultHTTPPort == 0 { defaultHTTPPort = 80 }
|
||||
if defaultGeminiPort == 0 { defaultGeminiPort = 1965 }
|
||||
|
||||
config.routerPort = defaultRouterPort
|
||||
config.httpsPort = defaultHTTPSPort
|
||||
config.httpPort = defaultHTTPPort
|
||||
config.geminiPort = defaultGeminiPort
|
||||
}
|
||||
|
||||
func (config *config) handleKeyVal (key, val string) error {
|
||||
valn, _ := strconv.Atoi(val)
|
||||
|
||||
switch key {
|
||||
case "alias":
|
||||
return config.parseAlias(key, val)
|
||||
case "unalias":
|
||||
delete(config.aliases, val)
|
||||
case "keyPath":
|
||||
config.keyPath = val
|
||||
case "certPath":
|
||||
config.certPath = val
|
||||
case "rcon":
|
||||
config.rconEnable = val == "true"
|
||||
case "router":
|
||||
config.routerPort = valn
|
||||
case "https":
|
||||
config.httpsEnable = true
|
||||
if valn > 0 { config.httpsPort = valn }
|
||||
case "http":
|
||||
config.httpEnable = true
|
||||
if valn > 0 { config.httpPort = valn }
|
||||
case "gemini":
|
||||
config.geminiEnable = true
|
||||
if valn > 0 { config.geminiPort = valn }
|
||||
case "noSecurity":
|
||||
config.noSecurity = val == "I AM NOT USING THIS IN PRODUCTION."
|
||||
case "user":
|
||||
return config.parseUser(key, val)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (config *config) parseAlias (key, val string) error {
|
||||
alias, target, found := strings.Cut(val, "->")
|
||||
alias = strings.TrimSpace(alias)
|
||||
target = strings.TrimSpace(target)
|
||||
if !found {
|
||||
return errors.New("syntax: alias must be of the form: alias <alias> -> <target>")
|
||||
}
|
||||
|
||||
if len(alias) < 1 || len(target) < 1 {
|
||||
return errors.New("syntax: alias must be of the form: alias <alias> -> <target>")
|
||||
}
|
||||
|
||||
if alias == "(fallback)" {
|
||||
config.fallback = target
|
||||
} else {
|
||||
config.aliases[alias] = target
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (config *config) parseUser (key, val string) error {
|
||||
user := user { }
|
||||
|
||||
name, keyAndPatterns, _ := strings.Cut(val, ":")
|
||||
name = strings.TrimSpace(name)
|
||||
user.name = name
|
||||
key, patternsStr, _ := strings.Cut(keyAndPatterns, "->")
|
||||
key = strings.TrimSpace(key)
|
||||
user.hash = []byte(key)
|
||||
patternStrs := strings.Split(patternsStr, ",")
|
||||
|
||||
for _, patternStr := range patternStrs {
|
||||
patternStr = strings.TrimSpace(patternStr)
|
||||
if patternStr == "(rcon)" {
|
||||
user.rconAllow = true
|
||||
} else if patternStr != "" {
|
||||
pattern, err := parsePattern(patternStr)
|
||||
if err != nil { return err }
|
||||
user.patterns = append(user.patterns, pattern)
|
||||
}
|
||||
}
|
||||
|
||||
config.users[name] = user
|
||||
return nil
|
||||
}
|
||||
|
||||
func parsePattern (val string) (pattern, error) {
|
||||
pattern := pattern { }
|
||||
if val == "*" {
|
||||
pattern.matchAll = true
|
||||
return pattern, nil
|
||||
}
|
||||
|
||||
scheme, hostAndPath, found := strings.Cut(val, "://")
|
||||
if !found { return pattern, errors.New("pattern must include scheme") }
|
||||
pattern.scheme = scheme
|
||||
|
||||
host, path, found := strings.Cut(hostAndPath, "/")
|
||||
if !found { return pattern, errors.New("pattern must include path") }
|
||||
path = "/" + path
|
||||
|
||||
if strings.HasPrefix(host, "*") {
|
||||
pattern.hostMode = matchModeGlob
|
||||
host = strings.TrimPrefix(host, "*")
|
||||
} else if strings.HasPrefix(host, ".") {
|
||||
pattern.hostMode = matchModeExtend
|
||||
host = strings.TrimPrefix(host, ".")
|
||||
}
|
||||
|
||||
if strings.HasSuffix(path, "*") {
|
||||
pattern.pathMode = matchModeGlob
|
||||
path = strings.TrimSuffix(path, "*")
|
||||
} else if strings.HasSuffix(path, "/") {
|
||||
pattern.pathMode = matchModeExtend
|
||||
path = strings.TrimSuffix(path, "/")
|
||||
}
|
||||
|
||||
pattern.host = host
|
||||
pattern.path = path
|
||||
return pattern, nil
|
||||
}
|
||||
|
||||
func (config *config) OverUsers (callback func (name string, user User) bool) {
|
||||
for name, user := range config.users {
|
||||
if !callback(name, user) { break }
|
||||
}
|
||||
}
|
||||
|
||||
func (config *config) User (name string) User {
|
||||
user := config.users[name]
|
||||
user.noSecurity = config.noSecurity
|
||||
return user
|
||||
}
|
||||
|
||||
func (config *config) RconEnable () bool {
|
||||
return config.rconEnable
|
||||
}
|
||||
|
||||
func (config *config) RouterPort () int {
|
||||
return config.routerPort
|
||||
}
|
||||
|
||||
func (config *config) HTTPSEnable () bool {
|
||||
return config.httpsEnable
|
||||
}
|
||||
|
||||
func (config *config) HTTPSPort () int {
|
||||
return config.httpsPort
|
||||
}
|
||||
|
||||
func (config *config) HTTPEnable () bool {
|
||||
return config.httpEnable
|
||||
}
|
||||
|
||||
func (config *config) HTTPPort () int {
|
||||
return config.httpPort
|
||||
}
|
||||
|
||||
func (config *config) GeminiEnable () bool {
|
||||
return config.geminiEnable
|
||||
}
|
||||
|
||||
func (config *config) GeminiPort () int {
|
||||
return config.geminiPort
|
||||
}
|
||||
|
||||
func (config *config) ResolveAlias (alias string) string {
|
||||
// try to match an alias
|
||||
for key, value := range config.aliases {
|
||||
if alias == key {
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
// if a fallback is set, and no aliases were found, use fallback
|
||||
if config.fallback != "" {
|
||||
return config.fallback
|
||||
}
|
||||
|
||||
// if we don't have anything to resolve, return input as is
|
||||
return alias
|
||||
}
|
||||
|
||||
func (config *config) AliasFallback () string {
|
||||
return config.fallback
|
||||
}
|
||||
|
||||
func (config *config) OverAliases (callback func (alias, target string) bool) {
|
||||
for alias, target := range config.aliases {
|
||||
if !callback(alias, target) { break }
|
||||
}
|
||||
}
|
||||
|
||||
func (config *config) Certificate () tls.Certificate {
|
||||
return config.cert
|
||||
}
|
27
config/tls.go
Normal file
@ -0,0 +1,27 @@
|
||||
package config
|
||||
|
||||
import "crypto/tls"
|
||||
|
||||
// TLSConfigFor returns a robus TLS config from a given Config object.
|
||||
func TLSConfigFor (conf Config) *tls.Config {
|
||||
// following:
|
||||
// https://blog.cloudflare.com/exposing-go-on-the-internet/
|
||||
return &tls.Config {
|
||||
PreferServerCipherSuites: true,
|
||||
CurvePreferences: []tls.CurveID {
|
||||
// https://safecurves.cr.yp.to/
|
||||
tls.X25519,
|
||||
tls.CurveP521,
|
||||
},
|
||||
MinVersion: tls.VersionTLS13,
|
||||
CipherSuites: []uint16 {
|
||||
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
|
||||
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
|
||||
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
|
||||
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
|
||||
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
|
||||
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
|
||||
},
|
||||
Certificates: []tls.Certificate { conf.Certificate() },
|
||||
}
|
||||
}
|
95
examples/board/main.go
Normal file
@ -0,0 +1,95 @@
|
||||
package main
|
||||
|
||||
import "log"
|
||||
import "sync"
|
||||
import "path"
|
||||
import "net/http"
|
||||
import "crypto/tls"
|
||||
import "html/template"
|
||||
import "hnakra/service"
|
||||
|
||||
type Post struct {
|
||||
Author, Content string
|
||||
Next *Post
|
||||
}
|
||||
|
||||
type Board struct {
|
||||
root string
|
||||
mount *service.HTTP
|
||||
mux *http.ServeMux
|
||||
template *template.Template
|
||||
|
||||
postsMutex sync.RWMutex
|
||||
posts *Post
|
||||
}
|
||||
|
||||
func main () {
|
||||
board := Board { root: "/board/" }
|
||||
board.mux = http.NewServeMux()
|
||||
board.mount = &service.HTTP {
|
||||
Mount: service.Mount {
|
||||
Path: board.root,
|
||||
Name: "Board",
|
||||
Description: "A board where you can post things.",
|
||||
TLSConfig: &tls.Config { InsecureSkipVerify: true },
|
||||
},
|
||||
Handler: board.mux,
|
||||
}
|
||||
handle := func (pattern string, handler func (http.ResponseWriter, *http.Request)) {
|
||||
board.mux.HandleFunc(pattern, handler)
|
||||
}
|
||||
handle(board.root, board.serveHome)
|
||||
handle(path.Join(board.root, "actionPost"), board.serveActionPost)
|
||||
board.template = template.Must(template.New("board").Parse(tem))
|
||||
|
||||
err := board.mount.Run()
|
||||
if err != nil {
|
||||
log.Println("XXX", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (board *Board) getPosts (max int) []*Post {
|
||||
board.postsMutex.RLock()
|
||||
defer board.postsMutex.RUnlock()
|
||||
|
||||
posts := make([]*Post, max)
|
||||
count := 0
|
||||
current := board.posts
|
||||
for current != nil && count < max {
|
||||
posts[count] = current
|
||||
count ++
|
||||
current = current.Next
|
||||
}
|
||||
return posts[:count]
|
||||
}
|
||||
|
||||
func (board *Board) serveHome (res http.ResponseWriter, req *http.Request) {
|
||||
if req.URL.Path != board.root {
|
||||
http.NotFoundHandler().ServeHTTP(res, req)
|
||||
return
|
||||
}
|
||||
res.Header().Add("content-type", "text/html")
|
||||
res.WriteHeader(http.StatusOK)
|
||||
board.template.ExecuteTemplate(res, "pageHome", board.getPosts(16))
|
||||
}
|
||||
|
||||
func (board *Board) serveActionPost (res http.ResponseWriter, req *http.Request) {
|
||||
if req.Method != "POST" {
|
||||
res.Header().Add("content-type", "text/plain")
|
||||
res.WriteHeader(http.StatusMethodNotAllowed)
|
||||
res.Write([]byte("Method not allowed"))
|
||||
return
|
||||
}
|
||||
|
||||
defer http.Redirect(res, req, board.root, http.StatusSeeOther)
|
||||
|
||||
req.ParseForm()
|
||||
author := req.PostFormValue("author")
|
||||
content := req.PostFormValue("content")
|
||||
|
||||
board.posts = &Post {
|
||||
Author: author,
|
||||
Content: content,
|
||||
Next: board.posts,
|
||||
}
|
||||
}
|
150
examples/board/template.go
Normal file
@ -0,0 +1,150 @@
|
||||
package main
|
||||
|
||||
const tem = `
|
||||
{{define "top"}}
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>{{.}}</title>
|
||||
<style>
|
||||
* {
|
||||
appearance: none;
|
||||
--webkit-appearance: none;
|
||||
font-family: monospace;
|
||||
box-sizing: border-box;
|
||||
color: inherit;
|
||||
font-size: 12pt;
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: #b3b5b1;
|
||||
color: #272825;
|
||||
margin: 1em;
|
||||
}
|
||||
|
||||
body > * {
|
||||
margin: auto;
|
||||
max-width: 40em;
|
||||
padding: 1em;
|
||||
}
|
||||
|
||||
header {
|
||||
background-color: #a2a89d;
|
||||
border: 1px solid #8f938c;
|
||||
border-bottom-color: #7f847b;
|
||||
border-radius: 4px 4px 0 0;
|
||||
text-shadow: 1px 1px 1px #b8bfb0;
|
||||
color: #4c4f49;
|
||||
}
|
||||
|
||||
main {
|
||||
background-color: #abaea8;
|
||||
border: 1px solid #959b91;
|
||||
border-top-color: #a1a59e;
|
||||
border-radius: 0 0 4px 4px;
|
||||
}
|
||||
|
||||
h1 { font-size: 1.5em }
|
||||
|
||||
hr {
|
||||
margin: 1em 0;
|
||||
border: none;
|
||||
border-top: 1px solid #7f847b9e;
|
||||
border-bottom: 1px solid #56604f1c;
|
||||
}
|
||||
|
||||
.formRow {
|
||||
margin: 1em 0;
|
||||
}
|
||||
|
||||
button, input, textarea {
|
||||
margin: 0;
|
||||
border: 1px solid #7f847b;
|
||||
background-color: #b3b5b1;
|
||||
padding: 0.25em 0.5em;
|
||||
box-shadow: 1px 1px 0 inset #56604f38;
|
||||
border-radius: 2px;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
textarea {
|
||||
height: 4em;
|
||||
}
|
||||
|
||||
button:not(:active), input[type=submit]:not(:active) {
|
||||
box-shadow: -1px -1px 0 inset #56604f38;
|
||||
}
|
||||
|
||||
button:active, input[type=submit]:active {
|
||||
border-color: #757a71;
|
||||
padding-top: calc(0.25em + 1px);
|
||||
padding-right: calc(0.5em - 1px);
|
||||
padding-bottom: calc(0.25em - 1px);
|
||||
padding-left: calc(0.5em + 1px);
|
||||
}
|
||||
|
||||
.post {
|
||||
padding: 0.4em 0.5em;
|
||||
background-color: #a2a69f;
|
||||
border-radius: 2px;
|
||||
border: 1px solid #8f938c;
|
||||
margin: 1em 0;
|
||||
}
|
||||
|
||||
.post .author {
|
||||
font-size: 0.7em;
|
||||
color: #5e625a;
|
||||
text-shadow: 1px 1px 0 #b3b5b1;
|
||||
margin-bottom: 0.3em;
|
||||
}
|
||||
|
||||
*:last-child { margin-bottom: 0 }
|
||||
*:first-child { margin-top: 0 }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>{{.}}</h1>
|
||||
</header>
|
||||
<main>
|
||||
{{end}}
|
||||
|
||||
{{define "bottom"}}</main></body></html>{{end}}
|
||||
|
||||
{{define "post"}}
|
||||
<div class=post>
|
||||
<div class=author>{{.Author}}</div>
|
||||
<div class=content>{{.Content}}</div>
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
{{define "postForm"}}
|
||||
<form method=POST action=actionPost>
|
||||
<div class=formRow>
|
||||
<input type=text name=author id=author placeholder="Name" required>
|
||||
</div>
|
||||
<div class=formRow>
|
||||
<textarea name=content id=content placeholder="Post content" required></textarea>
|
||||
</div>
|
||||
<div class=formRow>
|
||||
<input type=submit value="Post">
|
||||
</div>
|
||||
</form>
|
||||
{{end}}
|
||||
|
||||
{{define "pageGeneric"}}
|
||||
{{template "top" .Title}}
|
||||
<p>{{.Content}}</p>
|
||||
{{template "bottom"}}
|
||||
{{end}}
|
||||
|
||||
{{define "pageHome"}}
|
||||
{{template "top" "Home"}}
|
||||
{{template "postForm"}}
|
||||
<hr>
|
||||
{{range .}}
|
||||
{{template "post" .}}
|
||||
{{end}}
|
||||
{{template "bottom"}}
|
||||
{{end}}
|
||||
`
|
45
examples/gifs/main.go
Normal file
@ -0,0 +1,45 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
import "log"
|
||||
import "net/http"
|
||||
import "crypto/tls"
|
||||
import "hnakra/service"
|
||||
|
||||
func main () {
|
||||
static := http.FileServer(http.Dir("./static"))
|
||||
|
||||
http.HandleFunc("/gifs/", gifs)
|
||||
http.Handle("/gifs/static/", http.StripPrefix("/gifs/static", static))
|
||||
|
||||
err := (&service.HTTP { Mount: service.Mount {
|
||||
Path: "/gifs/",
|
||||
Name: "Gifs",
|
||||
Description: "Serves a lot of big gifs on one page.",
|
||||
TLSConfig: &tls.Config { InsecureSkipVerify: true },
|
||||
}}).Run()
|
||||
|
||||
if err != nil {
|
||||
log.Println("XXX", err)
|
||||
}
|
||||
}
|
||||
|
||||
func gifs (res http.ResponseWriter, req *http.Request) {
|
||||
res.Header().Add("content-type", "text/html")
|
||||
res.WriteHeader(http.StatusOK)
|
||||
|
||||
img := func (number int) {
|
||||
fmt.Fprintf(res, "<img src='static/%d.gif'>", number)
|
||||
}
|
||||
|
||||
fmt.Fprintln(res, "<!DOCTYPE html><html><head><title>Gifs</title></head><body>")
|
||||
img(0)
|
||||
img(1)
|
||||
img(2)
|
||||
img(3)
|
||||
img(4)
|
||||
img(5)
|
||||
img(6)
|
||||
img(7)
|
||||
fmt.Fprintln(res, "</body></html>")
|
||||
}
|
BIN
examples/gifs/static/0.gif
Normal file
After Width: | Height: | Size: 1.4 MiB |
BIN
examples/gifs/static/1.gif
Normal file
After Width: | Height: | Size: 2.0 MiB |
BIN
examples/gifs/static/2.gif
Normal file
After Width: | Height: | Size: 288 KiB |
BIN
examples/gifs/static/3.gif
Normal file
After Width: | Height: | Size: 2.5 MiB |
BIN
examples/gifs/static/4.gif
Normal file
After Width: | Height: | Size: 608 KiB |
BIN
examples/gifs/static/5.gif
Normal file
After Width: | Height: | Size: 3.2 MiB |
BIN
examples/gifs/static/6.gif
Normal file
After Width: | Height: | Size: 6.3 MiB |
BIN
examples/gifs/static/7.gif
Normal file
After Width: | Height: | Size: 955 KiB |
26
examples/hellorld/main.go
Normal file
@ -0,0 +1,26 @@
|
||||
package main
|
||||
|
||||
import "log"
|
||||
import "net/http"
|
||||
import "crypto/tls"
|
||||
import "hnakra/service"
|
||||
|
||||
func main () {
|
||||
http.HandleFunc("/hello/", hellorld)
|
||||
err := (&service.HTTP { Mount: service.Mount {
|
||||
Path: "/hello/",
|
||||
Name: "Hellorld",
|
||||
Description: "A test service.",
|
||||
TLSConfig: &tls.Config { InsecureSkipVerify: true },
|
||||
}}).Run()
|
||||
|
||||
if err != nil {
|
||||
log.Println("XXX", err)
|
||||
}
|
||||
}
|
||||
|
||||
func hellorld (res http.ResponseWriter, req *http.Request) {
|
||||
res.Header().Add("content-type", "text/plain")
|
||||
res.WriteHeader(200)
|
||||
res.Write([]byte("Hellorld!\n"))
|
||||
}
|
BIN
examples/image/fractal.png
Normal file
After Width: | Height: | Size: 1.6 MiB |
26
examples/image/main.go
Normal file
@ -0,0 +1,26 @@
|
||||
package main
|
||||
|
||||
import "log"
|
||||
import "net/http"
|
||||
import "crypto/tls"
|
||||
import "hnakra/service"
|
||||
|
||||
func main () {
|
||||
http.HandleFunc("/fractal.png", func (res http.ResponseWriter, req *http.Request) {
|
||||
// An interesting quirk relating to http.ServeFile: there needs
|
||||
// to be a one-to-one correspondance between pattern path and
|
||||
// file. This means you can't serve an image on a rooted
|
||||
// subtree. Otherwise it will randomly fail. I think this has to
|
||||
// do with how *something* is caching the file.
|
||||
http.ServeFile(res, req, "fractal.png")
|
||||
})
|
||||
|
||||
err := (&service.HTTP { Mount: service.Mount {
|
||||
Path: "/fractal.png",
|
||||
Name: "Image",
|
||||
Description: "Displays an image of a fractal.",
|
||||
TLSConfig: &tls.Config { InsecureSkipVerify: true },
|
||||
}}).Run()
|
||||
|
||||
if err != nil { log.Println("XXX", err) }
|
||||
}
|
24
examples/kamikaze/main.go
Normal file
@ -0,0 +1,24 @@
|
||||
package main
|
||||
|
||||
import "log"
|
||||
import "net/http"
|
||||
import "crypto/tls"
|
||||
import "hnakra/service"
|
||||
|
||||
func main () {
|
||||
http.HandleFunc("/kamikaze/", hellorld)
|
||||
err := (&service.HTTP { Mount: service.Mount {
|
||||
Path: "/kamikaze/",
|
||||
Name: "Kamikaze",
|
||||
Description: "A service that abrupltly closes upon any request, for testing",
|
||||
TLSConfig: &tls.Config { InsecureSkipVerify: true },
|
||||
}}).Run()
|
||||
|
||||
if err != nil {
|
||||
log.Println("XXX", err)
|
||||
}
|
||||
}
|
||||
|
||||
func hellorld (res http.ResponseWriter, req *http.Request) {
|
||||
log.Fatal("Goodbye!")
|
||||
}
|
8
go.mod
Normal file
@ -0,0 +1,8 @@
|
||||
module hnakra
|
||||
|
||||
go 1.20
|
||||
|
||||
require (
|
||||
git.tebibyte.media/sashakoshka/ezprof v0.0.0-20230309044548-401cba83602b
|
||||
golang.org/x/crypto v0.9.0
|
||||
)
|
4
go.sum
Normal file
@ -0,0 +1,4 @@
|
||||
git.tebibyte.media/sashakoshka/ezprof v0.0.0-20230309044548-401cba83602b h1:vPFKR7vjN1VrMdMtpATMrKQobz/cqbPiRrA1EbtG6PM=
|
||||
git.tebibyte.media/sashakoshka/ezprof v0.0.0-20230309044548-401cba83602b/go.mod h1:cpXX8SAUDEvZX5m7scoyruavUhEqQ1SByfWzPFHkTbg=
|
||||
golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g=
|
||||
golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0=
|
70
protocol/buf.go
Normal file
@ -0,0 +1,70 @@
|
||||
package protocol
|
||||
|
||||
import "io"
|
||||
import "fmt"
|
||||
|
||||
// ReadBuf reads a size-prefixed buffer.
|
||||
func ReadBuf (sizeBytes int, reader io.Reader) (buf []byte, err error) {
|
||||
size, err := ReadInt(reader, sizeBytes)
|
||||
if err != nil { return nil, err }
|
||||
buf = make([]byte, size)
|
||||
_, err = io.ReadFull(reader, buf)
|
||||
return buf, err
|
||||
}
|
||||
|
||||
// ReadBuf8 reads a size-prefixed buffer with an 8-bit size.
|
||||
func ReadBuf8 (reader io.Reader) (buf []byte, err error) {
|
||||
return ReadBuf(1, reader)
|
||||
}
|
||||
|
||||
// ReadBuf16 reads a size-prefixed buffer with a 16-bit size.
|
||||
func ReadBuf16 (reader io.Reader) (buf []byte, err error) {
|
||||
return ReadBuf(2, reader)
|
||||
}
|
||||
|
||||
// ReadString reads a size-prefixed string.
|
||||
func ReadString (sizeBytes int, reader io.Reader) (str string, err error) {
|
||||
buf, err := ReadBuf(sizeBytes, reader)
|
||||
return string(buf), err
|
||||
}
|
||||
|
||||
// ReadString8 reads a size-prefixed string with an 8-bit size.
|
||||
func ReadString8 (reader io.Reader) (str string, err error) {
|
||||
return ReadString(1, reader)
|
||||
}
|
||||
|
||||
// ReadString16 reads a size-prefixed string with a 16-bit size.
|
||||
func ReadString16 (reader io.Reader) (str string, err error) {
|
||||
return ReadString(2, reader)
|
||||
}
|
||||
|
||||
func WriteBuf (writer io.Writer, sizeBytes int, buf []byte) (err error) {
|
||||
if uint(len(buf)) > MaxIntOfSize(sizeBytes) {
|
||||
panic(fmt.Sprintf("len %d cannot fit in U%d", len(buf), sizeBytes * 8))
|
||||
}
|
||||
|
||||
err = WriteInt(writer, sizeBytes, uint(len(buf)))
|
||||
if err != nil { return }
|
||||
_, err = writer.Write(buf)
|
||||
return
|
||||
}
|
||||
|
||||
func WriteBuf8 (writer io.Writer, buf []byte) error {
|
||||
return WriteBuf(writer, 1, buf)
|
||||
}
|
||||
|
||||
func WriteBuf16 (writer io.Writer, buf []byte) error {
|
||||
return WriteBuf(writer, 2, buf)
|
||||
}
|
||||
|
||||
func WriteString (writer io.Writer, sizeBytes int, str string) (err error) {
|
||||
return WriteBuf(writer, sizeBytes, []byte(str))
|
||||
}
|
||||
|
||||
func WriteString8 (writer io.Writer, str string) (err error) {
|
||||
return WriteBuf8(writer, []byte(str))
|
||||
}
|
||||
|
||||
func WriteString16 (writer io.Writer, str string) (err error) {
|
||||
return WriteBuf16(writer, []byte(str))
|
||||
}
|
144
protocol/buf_test.go
Normal file
@ -0,0 +1,144 @@
|
||||
package protocol
|
||||
|
||||
import "bytes"
|
||||
import "testing"
|
||||
|
||||
func makeTestBuffer (length int) (buffer []byte) {
|
||||
buffer = make([]byte, length)
|
||||
for index := range buffer {
|
||||
buffer[index] = byte(index)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func sliceEqual[T comparable] (left, right []T) bool {
|
||||
if len(left) != len(right) { return false }
|
||||
|
||||
for index, item := range left {
|
||||
if item != right[index] { return false }
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func TestBuf8 (test *testing.T) {
|
||||
var conduit bytes.Buffer
|
||||
input := makeTestBuffer(97)
|
||||
test.Log("generated buffer")
|
||||
|
||||
err := WriteBuf8(&conduit, input)
|
||||
if err != nil {
|
||||
test.Fatal(err)
|
||||
return
|
||||
}
|
||||
test.Log("wrote buffer")
|
||||
|
||||
output, err := ReadBuf8(&conduit)
|
||||
if err != nil {
|
||||
test.Fatal(err)
|
||||
return
|
||||
}
|
||||
test.Log("read buffer")
|
||||
|
||||
if len(input) != len(output) {
|
||||
test.Fatalf("len(input) %d != len(output) %d", len(input), len(output))
|
||||
return
|
||||
}
|
||||
|
||||
if !sliceEqual(input, output) {
|
||||
test.Fatal("input != output")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuf16 (test *testing.T) {
|
||||
var conduit bytes.Buffer
|
||||
input := makeTestBuffer(1731)
|
||||
test.Log("generated buffer")
|
||||
|
||||
err := WriteBuf16(&conduit, input)
|
||||
if err != nil {
|
||||
test.Fatal(err)
|
||||
return
|
||||
}
|
||||
test.Log("wrote buffer")
|
||||
|
||||
output, err := ReadBuf16(&conduit)
|
||||
if err != nil {
|
||||
test.Fatal(err)
|
||||
return
|
||||
}
|
||||
test.Log("read buffer")
|
||||
|
||||
if len(input) != len(output) {
|
||||
test.Fatalf("len(input) %d != len(output) %d", len(input), len(output))
|
||||
return
|
||||
}
|
||||
|
||||
if !sliceEqual(input, output) {
|
||||
test.Fatal("input != output")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func TestString8 (test *testing.T) {
|
||||
var conduit bytes.Buffer
|
||||
input := "The quick brown fox jumped over the lazy dog."
|
||||
test.Log("generated string")
|
||||
|
||||
err := WriteString8(&conduit, input)
|
||||
if err != nil {
|
||||
test.Fatal(err)
|
||||
return
|
||||
}
|
||||
test.Log("wrote buffer")
|
||||
|
||||
output, err := ReadString8(&conduit)
|
||||
if err != nil {
|
||||
test.Fatal(err)
|
||||
return
|
||||
}
|
||||
test.Log("read buffer")
|
||||
|
||||
if len(input) != len(output) {
|
||||
test.Fatalf("len(input) %d != len(output) %d", len(input), len(output))
|
||||
return
|
||||
}
|
||||
|
||||
if input != output {
|
||||
test.Fatal("input != output")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func TestString16 (test *testing.T) {
|
||||
var conduit bytes.Buffer
|
||||
input := `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Blandit aliquam etiam erat velit scelerisque. Euismod elementum nisi quis eleifend. Lorem ipsum dolor sit amet. Pellentesque diam volutpat commodo sed egestas egestas fringilla phasellus. Tristique sollicitudin nibh sit amet commodo nulla facilisi nullam vehicula. Lacus vel facilisis volutpat est velit egestas dui id. Mi quis hendrerit dolor magna. Sed ullamcorper morbi tincidunt ornare massa eget egestas purus viverra. Purus gravida quis blandit turpis cursus in hac. Enim nulla aliquet porttitor lacus luctus.
|
||||
|
||||
Cras adipiscing enim eu turpis egestas pretium aenean pharetra. Mauris vitae ultricies leo integer malesuada nunc vel risus. Quis enim lobortis scelerisque fermentum dui faucibus in ornare. Amet dictum sit amet justo donec enim diam. Vulputate ut pharetra sit amet. Tellus integer feugiat scelerisque varius morbi enim. Pulvinar etiam non quam lacus suspendisse faucibus interdum posuere. Mauris in aliquam sem fringilla ut. Sagittis id consectetur purus ut faucibus pulvinar elementum integer enim. Fermentum odio eu feugiat pretium nibh. Arcu risus quis varius quam quisque.`
|
||||
test.Log("generated buffer")
|
||||
|
||||
err := WriteString16(&conduit, input)
|
||||
if err != nil {
|
||||
test.Fatal(err)
|
||||
return
|
||||
}
|
||||
test.Log("wrote buffer")
|
||||
|
||||
output, err := ReadString16(&conduit)
|
||||
if err != nil {
|
||||
test.Fatal(err)
|
||||
return
|
||||
}
|
||||
test.Log("read buffer")
|
||||
|
||||
if len(input) != len(output) {
|
||||
test.Fatalf("len(input) %d != len(output) %d", len(input), len(output))
|
||||
return
|
||||
}
|
||||
|
||||
if input != output {
|
||||
test.Fatal("input != output")
|
||||
return
|
||||
}
|
||||
}
|
1
protocol/database.go
Normal file
@ -0,0 +1 @@
|
||||
package protocol
|
112
protocol/gemini.go
Normal file
@ -0,0 +1,112 @@
|
||||
package protocol
|
||||
|
||||
import "io"
|
||||
|
||||
// MessageGeminiRequest represents a gemini request. It is sent from the router
|
||||
// to the service.
|
||||
type MessageGeminiRequest struct {
|
||||
ID
|
||||
Address string
|
||||
URL string
|
||||
}
|
||||
|
||||
func ReadMessageGeminiRequest (reader io.Reader) (message MessageGeminiRequest, err error) {
|
||||
message.ID, err = ReadID(reader)
|
||||
if err != nil { return }
|
||||
message.Address, err = ReadString8(reader)
|
||||
if err != nil { return }
|
||||
message.URL, err = ReadString16(reader)
|
||||
return
|
||||
}
|
||||
func (message MessageGeminiRequest) Serialize (writer io.Writer) (err error) {
|
||||
err = message.ID.Serialize(writer)
|
||||
if err != nil { return }
|
||||
err = WriteString8(writer, message.Address)
|
||||
if err != nil { return }
|
||||
return WriteString16(writer, message.URL)
|
||||
}
|
||||
|
||||
func (message MessageGeminiRequest) Send (writer io.Writer) (err error) {
|
||||
err = TypeGeminiRequest.Serialize(writer)
|
||||
if err != nil { return }
|
||||
return message.Serialize(writer)
|
||||
}
|
||||
|
||||
// MessageGeminiResponse represents a gemini response. It is sent from the
|
||||
// service to the router.
|
||||
type MessageGeminiResponse struct {
|
||||
ID
|
||||
Status uint8
|
||||
Meta string
|
||||
}
|
||||
|
||||
func ReadMessageGeminiResponse (reader io.Reader) (message MessageGeminiResponse, err error) {
|
||||
message.ID, err = ReadID(reader)
|
||||
if err != nil { return }
|
||||
message.Status, err = ReadU8(reader)
|
||||
if err != nil { return }
|
||||
message.Meta, err = ReadString16(reader)
|
||||
return
|
||||
}
|
||||
|
||||
func (message MessageGeminiResponse) Serialize (writer io.Writer) (err error) {
|
||||
err = message.ID.Serialize(writer)
|
||||
if err != nil { return }
|
||||
err = WriteU8(writer, message.Status)
|
||||
if err != nil { return }
|
||||
return WriteString16(writer, message.Meta)
|
||||
}
|
||||
|
||||
func (message MessageGeminiResponse) Send (writer io.Writer) (err error) {
|
||||
err = TypeGeminiResponse.Serialize(writer)
|
||||
if err != nil { return }
|
||||
return message.Serialize(writer)
|
||||
}
|
||||
|
||||
// MessageGeminiBodySegment is a segment of a gemini response body. It is sent
|
||||
// from the service to the router.
|
||||
type MessageGeminiBodySegment struct {
|
||||
ID
|
||||
Data []byte
|
||||
}
|
||||
|
||||
func ReadMessageGeminiBodySegment (reader io.Reader) (message MessageGeminiBodySegment, err error) {
|
||||
message.ID, err = ReadID(reader)
|
||||
if err != nil { return }
|
||||
message.Data, err = ReadBuf16(reader)
|
||||
return
|
||||
}
|
||||
|
||||
func (message MessageGeminiBodySegment) Serialize (writer io.Writer) (err error) {
|
||||
err = message.ID.Serialize(writer)
|
||||
if err != nil { return }
|
||||
return WriteBuf16(writer, message.Data)
|
||||
}
|
||||
|
||||
func (message MessageGeminiBodySegment) Send (writer io.Writer) (err error) {
|
||||
err = TypeGeminiBodySegment.Serialize(writer)
|
||||
if err != nil { return }
|
||||
return message.Serialize(writer)
|
||||
}
|
||||
|
||||
// MessageGeminiBodyEnd denotes the end of a gemini response body. It is sent
|
||||
// from the service to the router. This must always be sent by the service to
|
||||
// properly close the sequence, even if no response body segments were sent.
|
||||
type MessageGeminiBodyEnd struct {
|
||||
ID
|
||||
}
|
||||
|
||||
func ReadMessageGeminiBodyEnd (reader io.Reader) (message MessageGeminiBodyEnd, err error) {
|
||||
message.ID, err = ReadID(reader)
|
||||
return
|
||||
}
|
||||
|
||||
func (message MessageGeminiBodyEnd) Serialize (writer io.Writer) (err error) {
|
||||
return message.ID.Serialize(writer)
|
||||
}
|
||||
|
||||
func (message MessageGeminiBodyEnd) Send (writer io.Writer) (err error) {
|
||||
err = TypeGeminiBodyEnd.Serialize(writer)
|
||||
if err != nil { return }
|
||||
return message.Serialize(writer)
|
||||
}
|
151
protocol/http.go
Normal file
@ -0,0 +1,151 @@
|
||||
package protocol
|
||||
|
||||
import "io"
|
||||
|
||||
// MessageHTTPRequest represents an HTTP or HTTPS request. It is sent from the
|
||||
// router to the service.
|
||||
type MessageHTTPRequest struct {
|
||||
ID
|
||||
Address string
|
||||
Method string
|
||||
URL string
|
||||
Header Map
|
||||
}
|
||||
|
||||
func ReadMessageHTTPRequest (reader io.Reader) (message MessageHTTPRequest, err error) {
|
||||
message.ID, err = ReadID(reader)
|
||||
if err != nil { return }
|
||||
message.Address, err = ReadString8(reader)
|
||||
if err != nil { return }
|
||||
message.Method, err = ReadString8(reader)
|
||||
if err != nil { return }
|
||||
message.URL, err = ReadString16(reader)
|
||||
if err != nil { return }
|
||||
message.Header, err = ReadMap(reader)
|
||||
return
|
||||
}
|
||||
|
||||
func (message MessageHTTPRequest) Serialize (writer io.Writer) (err error) {
|
||||
err = message.ID.Serialize(writer)
|
||||
if err != nil { return }
|
||||
err = WriteString8(writer, message.Address)
|
||||
if err != nil { return }
|
||||
err = WriteString8(writer, message.Method)
|
||||
if err != nil { return }
|
||||
err = WriteString16(writer, message.URL)
|
||||
if err != nil { return }
|
||||
return message.Header.Serialize(writer)
|
||||
}
|
||||
|
||||
func (message MessageHTTPRequest) Send (writer io.Writer) (err error) {
|
||||
err = TypeHTTPRequest.Serialize(writer)
|
||||
if err != nil { return }
|
||||
return message.Serialize(writer)
|
||||
}
|
||||
|
||||
// MessageHTTPResponse represents an HTTP or HTTPS response. It is sent from the
|
||||
// service to the router.
|
||||
type MessageHTTPResponse struct {
|
||||
ID
|
||||
Status uint16
|
||||
Header Map
|
||||
}
|
||||
|
||||
func ReadMessageHTTPResponse (reader io.Reader) (message MessageHTTPResponse, err error) {
|
||||
message.ID, err = ReadID(reader)
|
||||
if err != nil { return }
|
||||
message.Status, err = ReadU16(reader)
|
||||
if err != nil { return }
|
||||
message.Header, err = ReadMap(reader)
|
||||
return
|
||||
}
|
||||
|
||||
func (message MessageHTTPResponse) Serialize (writer io.Writer) (err error) {
|
||||
err = message.ID.Serialize(writer)
|
||||
if err != nil { return }
|
||||
err = WriteU16(writer, message.Status)
|
||||
if err != nil { return }
|
||||
return message.Header.Serialize(writer)
|
||||
}
|
||||
|
||||
func (message MessageHTTPResponse) Send (writer io.Writer) (err error) {
|
||||
err = TypeHTTPResponse.Serialize(writer)
|
||||
if err != nil { return }
|
||||
return message.Serialize(writer)
|
||||
}
|
||||
|
||||
// MessageHTTPBodyRequest is sent by the service to the router to ask it to
|
||||
// begin transmitting the request body as a series of MessageHTTPBodySegment.
|
||||
// The router will not give the service the request body unless the service
|
||||
// sends it this message.
|
||||
type MessageHTTPBodyRequest struct {
|
||||
ID
|
||||
}
|
||||
|
||||
func ReadMessageHTTPBodyRequest (reader io.Reader) (message MessageHTTPBodyRequest, err error) {
|
||||
message.ID, err = ReadID(reader)
|
||||
return
|
||||
}
|
||||
|
||||
func (message MessageHTTPBodyRequest) Serialize (writer io.Writer) error {
|
||||
return message.ID.Serialize(writer)
|
||||
}
|
||||
|
||||
func (message MessageHTTPBodyRequest) Send (writer io.Writer) (err error) {
|
||||
err = TypeHTTPBodyRequest.Serialize(writer)
|
||||
if err != nil { return }
|
||||
return message.Serialize(writer)
|
||||
}
|
||||
|
||||
// MessageHTTPBodySegment is sent by both the router and the service. When the
|
||||
// router sends this message, it is a segment of the request body. When the
|
||||
// service sends this message, it is a segment of the response body.
|
||||
type MessageHTTPBodySegment struct {
|
||||
ID
|
||||
Data []byte
|
||||
}
|
||||
|
||||
func ReadMessageHTTPBodySegment (reader io.Reader) (message MessageHTTPBodySegment, err error) {
|
||||
message.ID, err = ReadID(reader)
|
||||
if err != nil { return }
|
||||
message.Data, err = ReadBuf16(reader)
|
||||
return
|
||||
}
|
||||
|
||||
func (message MessageHTTPBodySegment) Serialize (writer io.Writer) (err error) {
|
||||
err = message.ID.Serialize(writer)
|
||||
if err != nil { return }
|
||||
return WriteBuf16(writer, message.Data)
|
||||
}
|
||||
|
||||
func (message MessageHTTPBodySegment) Send (writer io.Writer) (err error) {
|
||||
err = TypeHTTPBodySegment.Serialize(writer)
|
||||
if err != nil { return }
|
||||
return message.Serialize(writer)
|
||||
}
|
||||
|
||||
// MessageHTTPBodySegment is sent by both the router and the service. When the
|
||||
// router sends this message, it means that the HTTP request body has been sent
|
||||
// in its entirety. The router will not send this message unless the service has
|
||||
// sent a MessageHTTPBodyRequest first. When the service sends this message, it
|
||||
// means that the HTTP resposne body has been sent in its entirety. The service
|
||||
// must always sends this message when it fulfills a request, as it properly
|
||||
// terminates the sequence.
|
||||
type MessageHTTPBodyEnd struct {
|
||||
ID
|
||||
}
|
||||
|
||||
func ReadMessageHTTPBodyEnd (reader io.Reader) (message MessageHTTPBodyEnd, err error) {
|
||||
message.ID, err = ReadID(reader)
|
||||
return
|
||||
}
|
||||
|
||||
func (message MessageHTTPBodyEnd) Serialize (writer io.Writer) error {
|
||||
return message.ID.Serialize(writer)
|
||||
}
|
||||
|
||||
func (message MessageHTTPBodyEnd) Send (writer io.Writer) (err error) {
|
||||
err = TypeHTTPBodyEnd.Serialize(writer)
|
||||
if err != nil { return }
|
||||
return message.Serialize(writer)
|
||||
}
|
114
protocol/int.go
Normal file
@ -0,0 +1,114 @@
|
||||
package protocol
|
||||
|
||||
import "io"
|
||||
import "fmt"
|
||||
|
||||
// ReadInt reads a little-endian integer from a reader and returns it as result.
|
||||
// It will read the amount of bytes specified by bytes.
|
||||
func ReadInt (reader io.Reader, bytes int) (result uint, err error) {
|
||||
buf := [1]byte { }
|
||||
shift := 0
|
||||
for {
|
||||
justRead := 0
|
||||
for justRead == 0 && err == nil {
|
||||
justRead, err = reader.Read(buf[:])
|
||||
if err != nil { break }
|
||||
}
|
||||
|
||||
result += uint(buf[0]) << shift
|
||||
|
||||
bytes --
|
||||
shift += 8
|
||||
if bytes == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func MaxIntOfSize (bytes int) (max uint) {
|
||||
for {
|
||||
max |= 0xFF
|
||||
bytes --
|
||||
if bytes > 0 {
|
||||
max <<= 8
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ReadU8 reads an 8-bit integer.
|
||||
func ReadU8 (reader io.Reader) (result uint8, err error) {
|
||||
untypedResult, err := ReadInt(reader, 1)
|
||||
return uint8(untypedResult), err
|
||||
}
|
||||
|
||||
// ReadU16 reads a 16-bit integer.
|
||||
func ReadU16 (reader io.Reader) (result uint16, err error) {
|
||||
untypedResult, err := ReadInt(reader, 2)
|
||||
return uint16(untypedResult), err
|
||||
}
|
||||
|
||||
// ReadU24 reads a 24-bit integer.
|
||||
func ReadU24 (reader io.Reader) (result uint32, err error) {
|
||||
untypedResult, err := ReadInt(reader, 3)
|
||||
return uint32(untypedResult), err
|
||||
}
|
||||
|
||||
// ReadU32 reads a 32-bit integer.
|
||||
func ReadU32 (reader io.Reader) (result uint32, err error) {
|
||||
untypedResult, err := ReadInt(reader, 4)
|
||||
return uint32(untypedResult), err
|
||||
}
|
||||
|
||||
// WriteInt writes a little-endian integer to a writer. It will write the amount
|
||||
// of bytes specified by bytes.
|
||||
func WriteInt (writer io.Writer, bytes int, integer uint) (err error) {
|
||||
if integer > MaxIntOfSize(bytes) {
|
||||
panic(fmt.Sprintf("uint %d cannot fit in %d bytes", integer, bytes))
|
||||
}
|
||||
|
||||
buf := [1]byte { }
|
||||
for {
|
||||
buf[0] = byte(integer & 0xFF)
|
||||
|
||||
justWrote := 0
|
||||
for justWrote == 0 {
|
||||
justWrote, err = writer.Write(buf[:])
|
||||
if err != nil { return }
|
||||
}
|
||||
|
||||
bytes --
|
||||
if bytes > 0 {
|
||||
integer >>= 8
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// WriteU8 writes an 8-bit integer.
|
||||
func WriteU8 (writer io.Writer, integer uint8) error {
|
||||
return WriteInt(writer, 1, uint(integer))
|
||||
}
|
||||
|
||||
// WriteU16 writes an 16-bit integer.
|
||||
func WriteU16 (writer io.Writer, integer uint16) error {
|
||||
return WriteInt(writer, 2, uint(integer))
|
||||
}
|
||||
|
||||
// WriteU24 writes an 24-bit integer.
|
||||
func WriteU24 (writer io.Writer, integer uint32) error {
|
||||
return WriteInt(writer, 3, uint(integer))
|
||||
}
|
||||
|
||||
// WriteU32 writes an 32-bit integer.
|
||||
func WriteU32 (writer io.Writer, integer uint32) error {
|
||||
return WriteInt(writer, 4, uint(integer))
|
||||
}
|
59
protocol/int_test.go
Normal file
@ -0,0 +1,59 @@
|
||||
package protocol
|
||||
|
||||
import "bytes"
|
||||
import "testing"
|
||||
|
||||
func TestU8 (test *testing.T) {
|
||||
var conduit bytes.Buffer
|
||||
numbers := []uint8 { 0, 1, 255, 100, 18, 16, 127, 99 }
|
||||
|
||||
for _, number := range numbers {
|
||||
err := WriteU8(&conduit, number)
|
||||
if err != nil { test.Fatal(err) }
|
||||
}
|
||||
|
||||
for _, correct := range numbers {
|
||||
number, err := ReadU8(&conduit)
|
||||
if err != nil { test.Fatal(err) }
|
||||
if number != correct {
|
||||
test.Fatalf("expected %d, read back %d", correct, number)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestU16 (test *testing.T) {
|
||||
var conduit bytes.Buffer
|
||||
numbers := []uint16 { 0, 57, 900, 1000, 10000, 7881, 50023 }
|
||||
|
||||
for _, number := range numbers {
|
||||
err := WriteU16(&conduit, number)
|
||||
if err != nil { test.Fatal(err) }
|
||||
}
|
||||
|
||||
for _, correct := range numbers {
|
||||
number, err := ReadU16(&conduit)
|
||||
if err != nil { test.Fatal(err) }
|
||||
if number != correct {
|
||||
test.Fatalf("expected %d, read back %d", correct, number)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func TestU32 (test *testing.T) {
|
||||
var conduit bytes.Buffer
|
||||
numbers := []uint32 { 0, 57, 901239, 1000, 3480238490, 10000, 7881, 50023 }
|
||||
|
||||
for _, number := range numbers {
|
||||
err := WriteU32(&conduit, number)
|
||||
if err != nil { test.Fatal(err) }
|
||||
}
|
||||
|
||||
for _, correct := range numbers {
|
||||
number, err := ReadU32(&conduit)
|
||||
if err != nil { test.Fatal(err) }
|
||||
if number != correct {
|
||||
test.Fatalf("expected %d, read back %d", correct, number)
|
||||
}
|
||||
}
|
||||
}
|
174
protocol/login.go
Normal file
@ -0,0 +1,174 @@
|
||||
package protocol
|
||||
|
||||
import "io"
|
||||
import "fmt"
|
||||
|
||||
// Status is an 8-bit code that routers and services can send to each-other to
|
||||
// inform the other about issues (or lack thereof) with the last recieved
|
||||
// message in a given sequence. This is not to be confused with an HTTP status
|
||||
// code.
|
||||
type Status uint8; const (
|
||||
StatusOk Status = iota
|
||||
StatusBadMessageType
|
||||
StatusMalformedMessage
|
||||
StatusBadVersion
|
||||
StatusBadCredentials
|
||||
StatusBadMount
|
||||
)
|
||||
|
||||
// ReadStatus reads a Status code from a Reader.
|
||||
func ReadStatus (reader io.Reader) (status Status, err error) {
|
||||
untyped, err := ReadU8(reader)
|
||||
return Status(untyped), err
|
||||
}
|
||||
|
||||
// Serialize writes a Status code to a Writer.
|
||||
func (status Status) Serialize (writer io.Writer) error {
|
||||
return WriteU8(writer, uint8(status))
|
||||
}
|
||||
|
||||
// String returns a human-readable representation of a status code.
|
||||
func (status Status) String () string {
|
||||
switch status {
|
||||
case StatusOk: return "ok"
|
||||
case StatusBadMessageType: return "invalid message type"
|
||||
case StatusMalformedMessage: return "malformed message"
|
||||
case StatusBadVersion: return "unsupported protocol version"
|
||||
case StatusBadCredentials: return "invalid credentials"
|
||||
case StatusBadMount: return "invalid mount"
|
||||
}
|
||||
return fmt.Sprintf("Status(%d)", status)
|
||||
}
|
||||
|
||||
// Error is equivalent to String. This lets a status be returned as an error.
|
||||
func (status Status) Error () string {
|
||||
return status.String()
|
||||
}
|
||||
|
||||
// Version represents a Hnakra protocol version.
|
||||
type Version struct {
|
||||
Major uint8
|
||||
Minor uint8
|
||||
}
|
||||
|
||||
// ReadVersion reads version information from a Reader.
|
||||
func ReadVersion (reader io.Reader) (version Version, err error) {
|
||||
version.Major, err = ReadU8(reader)
|
||||
if err != nil { return }
|
||||
version.Minor, err = ReadU8(reader)
|
||||
return
|
||||
}
|
||||
|
||||
// Serialize writes version information to a Writer.
|
||||
func (version Version) Serialize (writer io.Writer) error {
|
||||
err := WriteU8(writer, uint8(version.Major))
|
||||
if err != nil { return err }
|
||||
return WriteU8(writer, uint8(version.Minor))
|
||||
}
|
||||
|
||||
// String returns a human-readable representation of a version.
|
||||
func (version Version) String () string {
|
||||
return fmt.Sprintf("%d.%d", version.Major, version.Minor)
|
||||
}
|
||||
|
||||
// MessageLogin is a message sent to a router by a service requesting to log in
|
||||
// and mount on a path. The service should not send anything before this
|
||||
// message. The router must reply with a MessageStatus containing StatusOk if
|
||||
// the login and mount suceeded. or some other code if it did not. While waiting
|
||||
// for this message to be sent, the service should not send anything.
|
||||
type MessageLogin struct {
|
||||
ID
|
||||
Version
|
||||
|
||||
User string
|
||||
Key []byte
|
||||
Name string
|
||||
Description string
|
||||
|
||||
Scheme string
|
||||
Host string
|
||||
Path string
|
||||
}
|
||||
|
||||
// ReadMessageLogin reads a login message from a Reader, starting after the type
|
||||
// code.
|
||||
func ReadMessageLogin (reader io.Reader) (message MessageLogin, err error) {
|
||||
message.ID, err = ReadID(reader)
|
||||
if err != nil { return }
|
||||
message.Version, err = ReadVersion(reader)
|
||||
if err != nil { return }
|
||||
message.User, err = ReadString8(reader)
|
||||
if err != nil { return }
|
||||
message.Key, err = ReadBuf8(reader)
|
||||
if err != nil { return }
|
||||
message.Name, err = ReadString8(reader)
|
||||
if err != nil { return }
|
||||
message.Description, err = ReadString8(reader)
|
||||
if err != nil { return }
|
||||
message.Scheme, err = ReadString8(reader)
|
||||
if err != nil { return }
|
||||
message.Host, err = ReadString16(reader)
|
||||
if err != nil { return }
|
||||
message.Path, err = ReadString16(reader)
|
||||
return
|
||||
}
|
||||
|
||||
// Serialize writes the login message to a Writer, starting after the type code.
|
||||
func (message MessageLogin) Serialize (writer io.Writer) (err error) {
|
||||
err = message.ID.Serialize(writer)
|
||||
if err != nil { return }
|
||||
err = message.Version.Serialize(writer)
|
||||
if err != nil { return }
|
||||
err = WriteString8(writer, message.User)
|
||||
if err != nil { return }
|
||||
err = WriteBuf8(writer, message.Key)
|
||||
if err != nil { return }
|
||||
err = WriteString8(writer, message.Name)
|
||||
if err != nil { return }
|
||||
err = WriteString8(writer, message.Description)
|
||||
if err != nil { return }
|
||||
err = WriteString8(writer, message.Scheme)
|
||||
if err != nil { return }
|
||||
err = WriteString16(writer, message.Host)
|
||||
if err != nil { return }
|
||||
err = WriteString16(writer, message.Path)
|
||||
return
|
||||
}
|
||||
|
||||
// Send writes the type code and the message to a Writer.
|
||||
func (message MessageLogin) Send (writer io.Writer) (err error) {
|
||||
err = TypeLogin.Serialize(writer)
|
||||
if err != nil { return }
|
||||
return message.Serialize(writer)
|
||||
}
|
||||
|
||||
// MessageStatus is a message that carries a Status code. If sent, it must be in
|
||||
// reply to the last recieved message with an equivalent ID.
|
||||
type MessageStatus struct {
|
||||
ID
|
||||
Status
|
||||
}
|
||||
|
||||
// ReadMessageStatus reads a status message from a Reader, starting after the
|
||||
// type code.
|
||||
func ReadMessageStatus (reader io.Reader) (message MessageStatus, err error) {
|
||||
message.ID, err = ReadID(reader)
|
||||
if err != nil { return }
|
||||
message.Status, err = ReadStatus(reader)
|
||||
return
|
||||
}
|
||||
|
||||
// Serialize writes the status message to a Writer, starting after the type
|
||||
// code.
|
||||
func (message MessageStatus) Serialize (writer io.Writer) (err error) {
|
||||
err = message.ID.Serialize(writer)
|
||||
if err != nil { return }
|
||||
return message.Status.Serialize(writer)
|
||||
}
|
||||
|
||||
// Send writes the type code and the message to a Writer.
|
||||
func (message MessageStatus) Send (writer io.Writer) (err error) {
|
||||
err = TypeStatus.Serialize(writer)
|
||||
if err != nil { return }
|
||||
return message.Serialize(writer)
|
||||
}
|
58
protocol/map.go
Normal file
@ -0,0 +1,58 @@
|
||||
package protocol
|
||||
|
||||
import "io"
|
||||
import "fmt"
|
||||
|
||||
// Map is a string-to-string map with non-unique keys. Each key can be
|
||||
// associated with multiple values. This is typically used for things like HTTP
|
||||
// headers.
|
||||
type Map map[string] []string
|
||||
|
||||
// ReadMap reads a map with a 16-bit length containing strings which have a
|
||||
// 16-bit size. The length of the map corresponds to how many key/value pairs
|
||||
// it has, and not how long the map is.
|
||||
func ReadMap (reader io.Reader) (m Map, err error) {
|
||||
length, err := ReadU16(reader)
|
||||
if err != nil { return nil, err }
|
||||
|
||||
m = make(Map)
|
||||
for length > 0 {
|
||||
key, err := ReadString16(reader)
|
||||
if err != nil { return m, err }
|
||||
value, err := ReadString16(reader)
|
||||
if err != nil { return m, err }
|
||||
m.Add(key, value)
|
||||
length --
|
||||
}
|
||||
|
||||
return m, err
|
||||
}
|
||||
|
||||
func (m Map) Serialize (writer io.Writer) (err error) {
|
||||
if uint(len(m)) > MaxIntOfSize(2) {
|
||||
panic(fmt.Sprintf("len(%d) cannot fit in U16", len(m)))
|
||||
}
|
||||
|
||||
length := 0
|
||||
for _, item := range m {
|
||||
length += len(item)
|
||||
}
|
||||
|
||||
err = WriteU16(writer, uint16(length))
|
||||
if err != nil { return }
|
||||
|
||||
for key, values := range m {
|
||||
for _, value := range values {
|
||||
err = WriteString16(writer, key)
|
||||
if err != nil { return }
|
||||
err = WriteString16(writer, value)
|
||||
if err != nil { return }
|
||||
}}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Add adds a value to the map under the specified key.
|
||||
func (m Map) Add (key, value string) {
|
||||
m[key] = append(m[key], value)
|
||||
}
|
51
protocol/map_test.go
Normal file
@ -0,0 +1,51 @@
|
||||
package protocol
|
||||
|
||||
import "bytes"
|
||||
import "testing"
|
||||
|
||||
func mapEqual (left, right Map) bool {
|
||||
if len(left) != len(right) { return false }
|
||||
|
||||
for key, value := range left {
|
||||
if !sliceEqual(value, right[key]) { return false }
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func TestMap (test *testing.T) {
|
||||
var conduit bytes.Buffer
|
||||
input := Map {
|
||||
"thing1": []string { "asdkjas" },
|
||||
"thing2": []string { "ooo" },
|
||||
"multivalue": []string { "value 1", "value 2", "value 3" },
|
||||
"keysmash": []string { "dsijfhlsdkjfhlkjsahdflkjahsdlfjhsadlkfhaslkdjaslkdjlkashd" },
|
||||
"Lorem Ipsum\n": []string {`Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Blandit aliquam etiam erat velit scelerisque. Euismod elementum nisi quis eleifend. Lorem ipsum dolor sit amet. Pellentesque diam volutpat commodo sed egestas egestas fringilla phasellus. Tristique sollicitudin nibh sit amet commodo nulla facilisi nullam vehicula. Lacus vel facilisis volutpat est velit egestas dui id. Mi quis hendrerit dolor magna. Sed ullamcorper morbi tincidunt ornare massa eget egestas purus viverra. Purus gravida quis blandit turpis cursus in hac. Enim nulla aliquet porttitor lacus luctus.
|
||||
|
||||
Cras adipiscing enim eu turpis egestas pretium aenean pharetra. Mauris vitae ultricies leo integer malesuada nunc vel risus. Quis enim lobortis scelerisque fermentum dui faucibus in ornare. Amet dictum sit amet justo donec enim diam. Vulputate ut pharetra sit amet. Tellus integer feugiat scelerisque varius morbi enim. Pulvinar etiam non quam lacus suspendisse faucibus interdum posuere. Mauris in aliquam sem fringilla ut. Sagittis id consectetur purus ut faucibus pulvinar elementum integer enim. Fermentum odio eu feugiat pretium nibh. Arcu risus quis varius quam quisque.` },
|
||||
}
|
||||
|
||||
err := input.Serialize(&conduit)
|
||||
if err != nil {
|
||||
test.Fatal(err)
|
||||
return
|
||||
}
|
||||
test.Log("wrote map")
|
||||
|
||||
output, err := ReadMap(&conduit)
|
||||
if err != nil {
|
||||
test.Fatal(err)
|
||||
return
|
||||
}
|
||||
test.Log("read map")
|
||||
|
||||
if len(input) != len(output) {
|
||||
test.Fatalf("len(input) %d != len(output) %d", len(input), len(output))
|
||||
return
|
||||
}
|
||||
|
||||
if !mapEqual(input, output) {
|
||||
test.Fatal("input != output")
|
||||
return
|
||||
}
|
||||
}
|
70
protocol/message_base_test.go
Normal file
@ -0,0 +1,70 @@
|
||||
package protocol
|
||||
|
||||
import "bytes"
|
||||
import "testing"
|
||||
|
||||
func TestMessageLogin (test *testing.T) {
|
||||
conduit := new(bytes.Buffer)
|
||||
message := MessageLogin {
|
||||
ID: 0,
|
||||
Version: Version { 1, 3 },
|
||||
User: "SomeUser",
|
||||
Key: []byte { 100, 2, 49 },
|
||||
Name: "SomeName",
|
||||
Description: "SomeDescription",
|
||||
Scheme: "SomeScheme",
|
||||
Host: "SomeHost",
|
||||
Path: "SomePath",
|
||||
}
|
||||
message.Send(conduit)
|
||||
|
||||
ty, err := ReadType(conduit)
|
||||
if err != nil { test.Fatal("when reading type code:", err) }
|
||||
if ty != TypeLogin { test.Fatal("expected", TypeLogin, "got", ty) }
|
||||
|
||||
got, err := ReadMessageLogin(conduit)
|
||||
if err != nil { test.Fatal("when reading message:", err) }
|
||||
|
||||
equal :=
|
||||
message.ID == got.ID &&
|
||||
message.Version == got.Version &&
|
||||
message.User == got.User &&
|
||||
sliceEqual(message.Key, got.Key) &&
|
||||
message.Name == got.Name &&
|
||||
message.Description == got.Description &&
|
||||
message.Scheme == got.Scheme &&
|
||||
message.Host == got.Host &&
|
||||
message.Path == got.Path
|
||||
|
||||
if !equal { test.Fatal("structures not equal") }
|
||||
|
||||
if conduit.Len() != 0 {
|
||||
test.Fatal("buffer len", conduit.Len(), "instead of 0")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageStatus (test *testing.T) {
|
||||
conduit := new(bytes.Buffer)
|
||||
message := MessageStatus {
|
||||
ID: 0,
|
||||
Status: StatusBadMount,
|
||||
}
|
||||
message.Send(conduit)
|
||||
|
||||
ty, err := ReadType(conduit)
|
||||
if err != nil { test.Fatal("when reading type code:", err) }
|
||||
if ty != TypeStatus { test.Fatal("expected", TypeStatus, "got", ty) }
|
||||
|
||||
got, err := ReadMessageStatus(conduit)
|
||||
if err != nil { test.Fatal("when reading message:", err) }
|
||||
|
||||
equal :=
|
||||
message.ID == got.ID &&
|
||||
message.Status == got.Status
|
||||
|
||||
if !equal { test.Fatal("structures not equal") }
|
||||
|
||||
if conduit.Len() != 0 {
|
||||
test.Fatal("buffer len", conduit.Len(), "instead of 0")
|
||||
}
|
||||
}
|
109
protocol/message_gemini_test.go
Normal file
@ -0,0 +1,109 @@
|
||||
package protocol
|
||||
|
||||
import "bytes"
|
||||
import "testing"
|
||||
|
||||
func TestMessageGeminiBodyEnd (test *testing.T) {
|
||||
conduit := new(bytes.Buffer)
|
||||
message := MessageGeminiBodyEnd {
|
||||
ID: 493234,
|
||||
}
|
||||
message.Send(conduit)
|
||||
|
||||
ty, err := ReadType(conduit)
|
||||
if err != nil { test.Fatal("when reading type code:", err) }
|
||||
if ty != TypeGeminiBodyEnd { test.Fatal("expected", TypeGeminiBodyEnd, "got", ty) }
|
||||
|
||||
got, err := ReadMessageGeminiBodyEnd(conduit)
|
||||
if err != nil { test.Fatal("when reading message:", err) }
|
||||
|
||||
equal := message.ID == got.ID
|
||||
|
||||
if !equal { test.Fatal("structures not equal") }
|
||||
|
||||
if conduit.Len() != 0 {
|
||||
test.Fatal("buffer len", conduit.Len(), "instead of 0")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageGeminiBodySegment (test *testing.T) {
|
||||
conduit := new(bytes.Buffer)
|
||||
message := MessageGeminiBodySegment {
|
||||
ID: 22441,
|
||||
Data: makeTestBuffer(10301),
|
||||
}
|
||||
message.Send(conduit)
|
||||
|
||||
ty, err := ReadType(conduit)
|
||||
if err != nil { test.Fatal("when reading type code:", err) }
|
||||
if ty != TypeGeminiBodySegment { test.Fatal("expected", TypeGeminiBodySegment, "got", ty) }
|
||||
|
||||
got, err := ReadMessageGeminiBodySegment(conduit)
|
||||
if err != nil { test.Fatal("when reading message:", err) }
|
||||
|
||||
equal :=
|
||||
message.ID == got.ID &&
|
||||
sliceEqual(message.Data, got.Data)
|
||||
|
||||
if !equal { test.Fatal("structures not equal") }
|
||||
|
||||
if conduit.Len() != 0 {
|
||||
test.Fatal("buffer len", conduit.Len(), "instead of 0")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageGeminiRequest (test *testing.T) {
|
||||
conduit := new(bytes.Buffer)
|
||||
message := MessageGeminiRequest {
|
||||
ID: 9994562,
|
||||
Address: "some.thing",
|
||||
URL: "gemini://example.com/hahaha",
|
||||
}
|
||||
message.Send(conduit)
|
||||
|
||||
ty, err := ReadType(conduit)
|
||||
if err != nil { test.Fatal("when reading type code:", err) }
|
||||
if ty != TypeGeminiRequest { test.Fatal("expected", TypeGeminiRequest, "got", ty) }
|
||||
|
||||
got, err := ReadMessageGeminiRequest(conduit)
|
||||
if err != nil { test.Fatal("when reading message:", err) }
|
||||
|
||||
equal :=
|
||||
message.ID == got.ID &&
|
||||
message.Address == got.Address &&
|
||||
message.URL == got.URL
|
||||
|
||||
if !equal { test.Fatal("structures not equal") }
|
||||
|
||||
if conduit.Len() != 0 {
|
||||
test.Fatal("buffer len", conduit.Len(), "instead of 0")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageGeminiResponse (test *testing.T) {
|
||||
conduit := new(bytes.Buffer)
|
||||
message := MessageGeminiResponse {
|
||||
ID: 77777,
|
||||
Status: 20,
|
||||
Meta: "text/gemini",
|
||||
}
|
||||
message.Send(conduit)
|
||||
|
||||
ty, err := ReadType(conduit)
|
||||
if err != nil { test.Fatal("when reading type code:", err) }
|
||||
if ty != TypeGeminiResponse { test.Fatal("expected", TypeGeminiResponse, "got", ty) }
|
||||
|
||||
got, err := ReadMessageGeminiResponse(conduit)
|
||||
if err != nil { test.Fatal("when reading message:", err) }
|
||||
|
||||
equal :=
|
||||
message.ID == got.ID &&
|
||||
message.Status == got.Status &&
|
||||
message.Meta == got.Meta
|
||||
|
||||
if !equal { test.Fatal("structures not equal") }
|
||||
|
||||
if conduit.Len() != 0 {
|
||||
test.Fatal("buffer len", conduit.Len(), "instead of 0")
|
||||
}
|
||||
}
|
142
protocol/message_http_test.go
Normal file
@ -0,0 +1,142 @@
|
||||
package protocol
|
||||
|
||||
import "bytes"
|
||||
import "testing"
|
||||
|
||||
func TestMessageHTTPBodyEnd (test *testing.T) {
|
||||
conduit := new(bytes.Buffer)
|
||||
message := MessageHTTPBodyEnd {
|
||||
ID: 493234,
|
||||
}
|
||||
message.Send(conduit)
|
||||
|
||||
ty, err := ReadType(conduit)
|
||||
if err != nil { test.Fatal("when reading type code:", err) }
|
||||
if ty != TypeHTTPBodyEnd { test.Fatal("expected", TypeHTTPBodyEnd, "got", ty) }
|
||||
|
||||
got, err := ReadMessageHTTPBodyEnd(conduit)
|
||||
if err != nil { test.Fatal("when reading message:", err) }
|
||||
|
||||
equal := message.ID == got.ID
|
||||
|
||||
if !equal { test.Fatal("structures not equal") }
|
||||
|
||||
if conduit.Len() != 0 {
|
||||
test.Fatal("buffer len", conduit.Len(), "instead of 0")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageHTTPBodyRequest (test *testing.T) {
|
||||
conduit := new(bytes.Buffer)
|
||||
message := MessageHTTPBodyRequest {
|
||||
ID: 493234,
|
||||
}
|
||||
message.Send(conduit)
|
||||
|
||||
ty, err := ReadType(conduit)
|
||||
if err != nil { test.Fatal("when reading type code:", err) }
|
||||
if ty != TypeHTTPBodyRequest { test.Fatal("expected", TypeHTTPBodyRequest, "got", ty) }
|
||||
|
||||
got, err := ReadMessageHTTPBodyRequest(conduit)
|
||||
if err != nil { test.Fatal("when reading message:", err) }
|
||||
|
||||
equal := message.ID == got.ID
|
||||
|
||||
if !equal { test.Fatal("structures not equal") }
|
||||
|
||||
if conduit.Len() != 0 {
|
||||
test.Fatal("buffer len", conduit.Len(), "instead of 0")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageHTTPBodySegment (test *testing.T) {
|
||||
conduit := new(bytes.Buffer)
|
||||
message := MessageHTTPBodySegment {
|
||||
ID: 22441,
|
||||
Data: makeTestBuffer(10301),
|
||||
}
|
||||
message.Send(conduit)
|
||||
|
||||
ty, err := ReadType(conduit)
|
||||
if err != nil { test.Fatal("when reading type code:", err) }
|
||||
if ty != TypeHTTPBodySegment { test.Fatal("expected", TypeHTTPBodySegment, "got", ty) }
|
||||
|
||||
got, err := ReadMessageHTTPBodySegment(conduit)
|
||||
if err != nil { test.Fatal("when reading message:", err) }
|
||||
|
||||
equal :=
|
||||
message.ID == got.ID &&
|
||||
sliceEqual(message.Data, got.Data)
|
||||
|
||||
if !equal { test.Fatal("structures not equal") }
|
||||
|
||||
if conduit.Len() != 0 {
|
||||
test.Fatal("buffer len", conduit.Len(), "instead of 0")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageHTTPRequest (test *testing.T) {
|
||||
conduit := new(bytes.Buffer)
|
||||
message := MessageHTTPRequest {
|
||||
ID: 9994562,
|
||||
Address: "some.thing",
|
||||
Method: "GET",
|
||||
URL: "https://example.com/hahaha",
|
||||
Header: Map {
|
||||
"Bird": []string { "Bird1", "Bird2" },
|
||||
"Tree": []string { "Tree1" },
|
||||
},
|
||||
}
|
||||
message.Send(conduit)
|
||||
|
||||
ty, err := ReadType(conduit)
|
||||
if err != nil { test.Fatal("when reading type code:", err) }
|
||||
if ty != TypeHTTPRequest { test.Fatal("expected", TypeHTTPRequest, "got", ty) }
|
||||
|
||||
got, err := ReadMessageHTTPRequest(conduit)
|
||||
if err != nil { test.Fatal("when reading message:", err) }
|
||||
|
||||
equal :=
|
||||
message.ID == got.ID &&
|
||||
message.Address == got.Address &&
|
||||
message.Method == got.Method &&
|
||||
message.URL == got.URL &&
|
||||
mapEqual(message.Header, got.Header)
|
||||
|
||||
if !equal { test.Fatal("structures not equal") }
|
||||
|
||||
if conduit.Len() != 0 {
|
||||
test.Fatal("buffer len", conduit.Len(), "instead of 0")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageHTTPResponse (test *testing.T) {
|
||||
conduit := new(bytes.Buffer)
|
||||
message := MessageHTTPResponse {
|
||||
ID: 77777,
|
||||
Status: 200,
|
||||
Header: Map {
|
||||
"Bird": []string { "Bird1", "Bird2" },
|
||||
"Tree": []string { "Tree1" },
|
||||
},
|
||||
}
|
||||
message.Send(conduit)
|
||||
|
||||
ty, err := ReadType(conduit)
|
||||
if err != nil { test.Fatal("when reading type code:", err) }
|
||||
if ty != TypeHTTPResponse { test.Fatal("expected", TypeHTTPResponse, "got", ty) }
|
||||
|
||||
got, err := ReadMessageHTTPResponse(conduit)
|
||||
if err != nil { test.Fatal("when reading message:", err) }
|
||||
|
||||
equal :=
|
||||
message.ID == got.ID &&
|
||||
message.Status == got.Status &&
|
||||
mapEqual(message.Header, got.Header)
|
||||
|
||||
if !equal { test.Fatal("structures not equal") }
|
||||
|
||||
if conduit.Len() != 0 {
|
||||
test.Fatal("buffer len", conduit.Len(), "instead of 0")
|
||||
}
|
||||
}
|
237
protocol/protocol.go
Normal file
@ -0,0 +1,237 @@
|
||||
// Package protocol defines what is sent accross the TCP connection between the
|
||||
// router and service. It provides primitives for serializing various integer
|
||||
// types and data structures, as well as entire messages for the protocols it
|
||||
// supports.
|
||||
package protocol
|
||||
|
||||
import "io"
|
||||
import "fmt"
|
||||
import "sync"
|
||||
|
||||
// Message represents a message that can be sent along an io.Writer, and read
|
||||
// back when it comes out the other end. All messages must prefix themselves
|
||||
// with a Type code.
|
||||
type Message interface {
|
||||
// Send serializes the message to a writer, prefixed with its Type code.
|
||||
Send (io.Writer) error
|
||||
}
|
||||
|
||||
// Serializer represents anything who's *content* can be serialized to a byte
|
||||
// stream. This does not include type information (such as a message Type code
|
||||
// prefix).
|
||||
type Serializer interface {
|
||||
// Serialize serializes the object's content to a writer.
|
||||
Serialize (io.Writer) error
|
||||
}
|
||||
|
||||
// ID is a number that identifies an ongoing sequence. It is similar to a cookie
|
||||
// in the X11 protocol. All messages that are a part of the same sequence have
|
||||
// the same ID. ID zero is the initial ID which is generated by the service upon
|
||||
// sending a MessageLogin to the router. The corresponding sequence must always
|
||||
// be treated as active as long as the connection is open, and must never be
|
||||
// reused for something else.
|
||||
//
|
||||
// If the leftmost bit of an ID is set, that means it was generated by
|
||||
// the router. If the leftmost bit of an ID is unset, that means it was
|
||||
// generated by the service. When generating IDs, the service will start at 1
|
||||
// and progressively increment the ID number. If the next ID would have its
|
||||
// leftmost bit set, it must loop back around to 1. Similarly, the router must
|
||||
// start at the maximum unsigned 32 bit integer (0xFFFFFFFF) and decrement until
|
||||
// the leftmost bit of the ID would be unset, and then loop back around to the
|
||||
// initial value.
|
||||
//
|
||||
// If either router or service generate an ID that is currently
|
||||
// in use by a sequence, that ID must be skipped over. For this reason, both
|
||||
// router and service must maintain a list of ongoing sequences along with their
|
||||
// active IDs. These lists (and corresponding generators) must be
|
||||
// connection-specific.
|
||||
//
|
||||
// Sequences are implicitly started by a message of the first type in any
|
||||
// particular protocol sector (see the documentation for Type in this package),
|
||||
// and must be sent with a newly generated ID as described above. The sequence
|
||||
// must consist only of messages that are part of the same protocol sector as
|
||||
// the message that started it (i.e. you cannot send a MessageGeminiResponse in
|
||||
// a sequence that was started by a MessageHTTPRequest). The only exception to
|
||||
// this is MessageStatus, which can be sent in any context. If this rule is
|
||||
// violated in any other capacity, the router or service should send a
|
||||
// MessageStatus with StatusBadMessageType and close the connection.
|
||||
//
|
||||
// The termination of any given sequence is determined by the rules of the
|
||||
// particular protocol sector it is a part of.
|
||||
type ID uint32
|
||||
|
||||
const RouterIDStart ID = 0xFFFFFFFF
|
||||
const ServiceIDStart ID = 0
|
||||
|
||||
// ReadID reads an ID from a Reader.
|
||||
func ReadID (reader io.Reader) (id ID, err error) {
|
||||
untyped, err := ReadU32(reader)
|
||||
return ID(untyped), err
|
||||
}
|
||||
|
||||
// Serialize writes an ID to a Writer.
|
||||
func (id ID) Serialize (writer io.Writer) error {
|
||||
return WriteU32(writer, uint32(id))
|
||||
}
|
||||
|
||||
// IsRouter returns true if this ID was generated by a router.
|
||||
func (id ID) IsRouter () bool {
|
||||
return id >> 31 == 1
|
||||
}
|
||||
|
||||
// IsService returns true if this ID was generated by a service.
|
||||
func (id ID) IsService () bool {
|
||||
return !id.IsRouter()
|
||||
}
|
||||
|
||||
// IDFactory generates IDs and keeps track of which ones are active. Its methods
|
||||
// can be called concurrently.
|
||||
type IDFactory struct {
|
||||
lock sync.Mutex
|
||||
|
||||
next ID
|
||||
router bool
|
||||
active map[ID] struct { }
|
||||
}
|
||||
|
||||
// NewRouterIDFactory returns a new IDFactory that generates router IDs.
|
||||
func NewRouterIDFactory () (factory *IDFactory) {
|
||||
factory = new(IDFactory)
|
||||
factory.active = make(map[ID] struct { })
|
||||
factory.router = true
|
||||
factory.next = RouterIDStart
|
||||
return
|
||||
}
|
||||
|
||||
// NewServiceIDFactory returns a new IDFactory that generates service IDs.
|
||||
func NewServiceIDFactory () (factory *IDFactory) {
|
||||
factory = new(IDFactory)
|
||||
factory.active = make(map[ID] struct { })
|
||||
factory.next = ServiceIDStart
|
||||
return
|
||||
}
|
||||
|
||||
// Next generates a new ID and returns it. The ID will be marked as active, and
|
||||
// a call to Free() is required to mark it as inactive when its corresponding
|
||||
// sequence has completed.
|
||||
func (factory *IDFactory) Next () ID {
|
||||
// FIXME: this is not the best way of doing it. it is unlikely that this
|
||||
// will ever cause problems, but the possibility is there.
|
||||
|
||||
factory.lock.Lock()
|
||||
defer factory.lock.Unlock()
|
||||
|
||||
id := factory.next
|
||||
if factory.router {
|
||||
next := id - 1
|
||||
for factory.isActive(id) {
|
||||
next --
|
||||
if next.IsService() {
|
||||
next = RouterIDStart
|
||||
}
|
||||
}
|
||||
factory.next = next
|
||||
} else {
|
||||
next := id + 1
|
||||
for factory.isActive(id) {
|
||||
next ++
|
||||
if next.IsRouter() {
|
||||
next = ServiceIDStart
|
||||
}
|
||||
}
|
||||
factory.next = next
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Free marks an ID as inactive. Note that calling Free(0) is in violation of
|
||||
// the protocol.
|
||||
func (factory *IDFactory) Free (id ID) {
|
||||
factory.lock.Lock()
|
||||
defer factory.lock.Unlock()
|
||||
|
||||
delete(factory.active, id)
|
||||
}
|
||||
|
||||
func (factory *IDFactory) isActive (id ID) bool {
|
||||
_, active := factory.active[id]
|
||||
return active
|
||||
}
|
||||
|
||||
// Type is an 8-bit code that comes before each message, and determines which
|
||||
// kind of message it is. The 256 type code values are divided into eight
|
||||
// 32-code sectors, where each sector corresponds to a different protocol.
|
||||
type Type uint8; const (
|
||||
// Initial sector
|
||||
TypeNone Type = iota + 0x00
|
||||
TypeLogin
|
||||
TypeStatus
|
||||
|
||||
// HTTP/HTTPS protocol sector
|
||||
TypeHTTPRequest Type = iota + 0x20
|
||||
TypeHTTPResponse
|
||||
TypeHTTPBodyRequest
|
||||
TypeHTTPBodySegment
|
||||
TypeHTTPBodyEnd
|
||||
|
||||
// Gemini protocol sector TODO implement
|
||||
TypeGeminiRequest Type = iota + 0x40
|
||||
TypeGeminiResponse
|
||||
TypeGeminiBodySegment
|
||||
TypeGeminiBodyEnd
|
||||
|
||||
// Database access sector TODO implement
|
||||
TypeDatabaseGet Type = iota + 0x40
|
||||
TypeDatabaseSet
|
||||
TypeDatabaseValue
|
||||
)
|
||||
|
||||
// ReadType reads a Type code from a Reader.
|
||||
func ReadType (reader io.Reader) (ty Type, err error) {
|
||||
untyped, err := ReadU8(reader)
|
||||
return Type(untyped), err
|
||||
}
|
||||
|
||||
// Serialize writes a Type code to a Writer.
|
||||
func (ty Type) Serialize (writer io.Writer) error {
|
||||
return WriteU8(writer, uint8(ty))
|
||||
}
|
||||
|
||||
// String returns the name of the type as a string.
|
||||
func (ty Type) String () string {
|
||||
switch ty {
|
||||
case TypeLogin: return "TypeLogin"
|
||||
case TypeStatus: return "TypeStatus"
|
||||
case TypeHTTPRequest: return "TypeHTTPRequest"
|
||||
case TypeHTTPResponse: return "TypeHTTPResponse"
|
||||
case TypeHTTPBodyRequest: return "TypeHTTPBodyRequest"
|
||||
case TypeHTTPBodySegment: return "TypeHTTPBodySegment"
|
||||
case TypeHTTPBodyEnd: return "TypeHTTPBodyEnd"
|
||||
case TypeGeminiRequest: return "TypeGeminiRequest"
|
||||
case TypeGeminiResponse: return "TypeGeminiResponse"
|
||||
case TypeGeminiBodySegment: return "TypeGeminiBodySegment"
|
||||
case TypeGeminiBodyEnd: return "TypeGeminiBodyEnd"
|
||||
}
|
||||
return fmt.Sprintf("Type(%d)", ty)
|
||||
}
|
||||
|
||||
// ReadMessage reads a Type code and its corresponding message from a Reader.
|
||||
// The type of message can be determined using a type switch.
|
||||
func ReadMessage (reader io.Reader) (Message, error) {
|
||||
ty, err := ReadType(reader)
|
||||
if err != nil { return nil, err }
|
||||
switch ty {
|
||||
case TypeLogin: return ReadMessageLogin(reader)
|
||||
case TypeStatus: return ReadMessageStatus(reader)
|
||||
case TypeHTTPRequest: return ReadMessageHTTPRequest(reader)
|
||||
case TypeHTTPResponse: return ReadMessageHTTPResponse(reader)
|
||||
case TypeHTTPBodyRequest: return ReadMessageHTTPBodyRequest(reader)
|
||||
case TypeHTTPBodySegment: return ReadMessageHTTPBodySegment(reader)
|
||||
case TypeHTTPBodyEnd: return ReadMessageHTTPBodyEnd(reader)
|
||||
case TypeGeminiRequest: return ReadMessageGeminiRequest(reader)
|
||||
case TypeGeminiResponse: return ReadMessageGeminiResponse(reader)
|
||||
case TypeGeminiBodySegment: return ReadMessageGeminiBodySegment(reader)
|
||||
case TypeGeminiBodyEnd: return ReadMessageGeminiBodyEnd(reader)
|
||||
}
|
||||
return nil, StatusBadMessageType
|
||||
}
|
353
rcon/rcon.go
Normal file
@ -0,0 +1,353 @@
|
||||
// Package rcon provices a password-protected remote web interface for managing
|
||||
// a Hnakra router. For a user to be able to access the control panel, the user
|
||||
// entry in the configuration file must have the special string (rcon) listed as
|
||||
// an allowed pattern.
|
||||
package rcon
|
||||
|
||||
import "io"
|
||||
import "fmt"
|
||||
import "net/url"
|
||||
import "net/http"
|
||||
import "hnakra/config"
|
||||
import "hnakra/router"
|
||||
import "hnakra/rotate"
|
||||
import "hnakra/protocol"
|
||||
|
||||
const css = `
|
||||
body { background-color: #161815; color: #aea894; margin: 3em; }
|
||||
h1 { font-size: 1.5em; }
|
||||
h2 { font-size: 1.2em; }
|
||||
a { color: #69905f; }
|
||||
table { border-collapse: collapse; }
|
||||
th, td {
|
||||
border: 1px solid #272d24;
|
||||
padding: 0.5em;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}`
|
||||
|
||||
type Rcon struct {
|
||||
root string
|
||||
config config.Config
|
||||
router *router.Router
|
||||
mux *http.ServeMux
|
||||
lines []string
|
||||
lineWriter io.Writer
|
||||
}
|
||||
|
||||
func New (root string) *Rcon {
|
||||
if len(root) > 0 && root[len(root) - 1] != '/' {
|
||||
root += "/"
|
||||
}
|
||||
rcon := &Rcon {
|
||||
root: root,
|
||||
mux: http.NewServeMux(),
|
||||
}
|
||||
rcon.lineWriter = rotate.LineWriter(rcon.pushLine)
|
||||
rcon.mux.HandleFunc(root + "", rcon.serveMainMenu)
|
||||
rcon.mux.HandleFunc(root + "log", rcon.serveLog)
|
||||
rcon.mux.HandleFunc(root + "services", rcon.serveServices)
|
||||
rcon.mux.HandleFunc(root + "config", rcon.serveConfig)
|
||||
rcon.mux.HandleFunc(root + "details", rcon.serveServiceDetails)
|
||||
return rcon
|
||||
}
|
||||
|
||||
func (rcon *Rcon) SetConfig (config config.Config) {
|
||||
rcon.config = config
|
||||
}
|
||||
|
||||
func (rcon *Rcon) SetRouter (router *router.Router) {
|
||||
rcon.router = router
|
||||
}
|
||||
|
||||
func (rcon *Rcon) pushLine (buffer []byte) (n int, err error) {
|
||||
const LEN_CAP = 128
|
||||
|
||||
n = len(buffer)
|
||||
line := string(buffer)
|
||||
rcon.lines = append(rcon.lines, line)
|
||||
if len(rcon.lines) > LEN_CAP {
|
||||
rcon.lines = rcon.lines[len(rcon.lines) - LEN_CAP:]
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (rcon *Rcon) Write (buffer []byte) (int, error) {
|
||||
return rcon.lineWriter.Write(buffer)
|
||||
}
|
||||
|
||||
func (rcon *Rcon) ServeHTTP (res http.ResponseWriter, req *http.Request) {
|
||||
// disallow accessing rcon over an insecure connection
|
||||
if req.TLS == nil {
|
||||
res.Header().Add("content-type", "text/html")
|
||||
res.WriteHeader(http.StatusTeapot)
|
||||
res.Write([]byte (
|
||||
`<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>HTTP Not Allowed</title>
|
||||
<style>` + css + `</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>HTTP Not Allowed</h1>
|
||||
<p>RCON is not available over HTTP for security reasons.
|
||||
Please try again with HTTPS.</p>
|
||||
</body>
|
||||
</html>`))
|
||||
return
|
||||
}
|
||||
|
||||
fail := func () {
|
||||
res.Header().Add("WWW-Authenticate", "Basic realm=rcon")
|
||||
res.WriteHeader(http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
// need authentication for accessing rcon menu
|
||||
name, key, ok := req.BasicAuth()
|
||||
if ok {
|
||||
user := rcon.config.User(name)
|
||||
if !user.Validate([]byte(key)) { fail(); return }
|
||||
} else {
|
||||
fail(); return
|
||||
}
|
||||
|
||||
// if the user is authorized, serve page as normal
|
||||
rcon.mux.ServeHTTP(res, req)
|
||||
}
|
||||
|
||||
func (rcon *Rcon) serveMainMenu (res http.ResponseWriter, req *http.Request) {
|
||||
if req.URL.Path != rcon.root {
|
||||
http.NotFoundHandler().ServeHTTP(res, req)
|
||||
return
|
||||
}
|
||||
|
||||
res.Header().Add("content-type", "text/html")
|
||||
res.WriteHeader(http.StatusFound)
|
||||
res.Write([]byte (
|
||||
`<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>RCON Menu</title>
|
||||
<style>` + css + `</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>RCON Menu</h1>
|
||||
<ul>
|
||||
<li><a href=log>log</a></li>
|
||||
<li><a href=services>services</a></li>
|
||||
<li><a href=config>config</a></li>
|
||||
</ul>
|
||||
</body>
|
||||
</html>`))
|
||||
}
|
||||
|
||||
func (rcon *Rcon) serveLog (res http.ResponseWriter, req *http.Request) {
|
||||
res.Header().Add("content-type", "text/html")
|
||||
res.WriteHeader(http.StatusFound)
|
||||
res.Write([]byte (
|
||||
`<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Router Log</title>
|
||||
<style>` + css + `</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Router Log</h1><pre>`))
|
||||
|
||||
for _, line := range rcon.lines {
|
||||
res.Write([]byte(line))
|
||||
}
|
||||
|
||||
res.Write([]byte (
|
||||
`</pre></body>
|
||||
</html>`))
|
||||
}
|
||||
|
||||
func (rcon *Rcon) serveServices (res http.ResponseWriter, req *http.Request) {
|
||||
if rcon.router == nil {
|
||||
rcon.serveRouterOffline(res, req)
|
||||
return
|
||||
}
|
||||
|
||||
res.Header().Add("content-type", "text/html")
|
||||
res.WriteHeader(http.StatusFound)
|
||||
res.Write([]byte (
|
||||
`<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Connected Services</title>
|
||||
<style>` + css + `</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Connected Services</h1>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>user</th>
|
||||
<th>name</th>
|
||||
<th>description</th>
|
||||
<th>pattern</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
`))
|
||||
|
||||
rcon.router.OverServices(func (service *router.Service) bool {
|
||||
res.Write([]byte(fmt.Sprintf (
|
||||
`<tr><td>%s</td><td><a href="details?service=%s">%s</a></td><td>%s</td><td>%s</td></tr>`,
|
||||
service.User(),
|
||||
service.Name(),
|
||||
service.Name(),
|
||||
service.Description(),
|
||||
service.Pattern())))
|
||||
return true
|
||||
})
|
||||
|
||||
res.Write([]byte (
|
||||
`</tbody></table></body>
|
||||
</html>`))
|
||||
}
|
||||
|
||||
func (rcon *Rcon) serveConfig (res http.ResponseWriter, req *http.Request) {
|
||||
res.Header().Add("content-type", "text/html")
|
||||
res.WriteHeader(http.StatusFound)
|
||||
res.Write([]byte (
|
||||
`<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Router Config</title>
|
||||
<style>` + css + `</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Router Config</h1>
|
||||
<h2>Users</h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>name</th>
|
||||
<th>rcon</th>
|
||||
<th>patterns</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>`))
|
||||
|
||||
rcon.config.OverUsers(func (name string, user config.User) bool {
|
||||
patterns := ""
|
||||
user.OverPatterns (func (pattern string) bool {
|
||||
if patterns != "" {
|
||||
patterns += " "
|
||||
}
|
||||
patterns += pattern
|
||||
return true
|
||||
})
|
||||
res.Write([]byte(fmt.Sprintf (
|
||||
"<tr><td>%s</td><td>%v</td><td>%s</td></tr>",
|
||||
name, user.RconAllow(), patterns)))
|
||||
return true
|
||||
})
|
||||
|
||||
res.Write([]byte(`</tbody></table><h2>Aliases</h2>`))
|
||||
fallback := rcon.config.AliasFallback()
|
||||
if fallback != "" {
|
||||
res.Write([]byte(`<p>Fallback: ` + fallback + `</p>`))
|
||||
}
|
||||
res.Write([]byte(`
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>alias</th>
|
||||
<th>target</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>`))
|
||||
rcon.config.OverAliases(func (alias, target string) bool {
|
||||
res.Write([]byte(fmt.Sprintf (
|
||||
"<tr><td>%s</td><td>%s</td></tr>",
|
||||
alias, target)))
|
||||
return true
|
||||
})
|
||||
|
||||
res.Write([]byte (
|
||||
`</tbody></table>
|
||||
<h2>Protocols</h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>scheme</th>
|
||||
<th>port</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>`))
|
||||
listProtocol := func (protocol string, port int) {
|
||||
res.Write([]byte(fmt.Sprintf (
|
||||
"<tr><td>%s</td><td>%d</td></tr>",
|
||||
protocol, port)))
|
||||
}
|
||||
if rcon.config.HTTPSEnable() {
|
||||
listProtocol("https", rcon.config.HTTPSPort())
|
||||
}
|
||||
if rcon.config.HTTPEnable() {
|
||||
listProtocol("http", rcon.config.HTTPPort())
|
||||
}
|
||||
if rcon.config.GeminiEnable() {
|
||||
listProtocol("gemini", rcon.config.GeminiPort())
|
||||
}
|
||||
res.Write([]byte(`</tbody></table></body></html>`))
|
||||
}
|
||||
|
||||
func (rcon *Rcon) serveServiceDetails (res http.ResponseWriter, req *http.Request) {
|
||||
name := req.URL.Query().Get("service")
|
||||
service := rcon.router.Service(name)
|
||||
if service == nil {
|
||||
http.NotFoundHandler().ServeHTTP(res, req)
|
||||
return
|
||||
}
|
||||
|
||||
res.Header().Add("content-type", "text/html")
|
||||
res.WriteHeader(http.StatusFound)
|
||||
res.Write([]byte (
|
||||
`<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Details of ` + service.Name() + `</title>
|
||||
<style>` + css + `</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Details of ` + service.Name() + `</h1>
|
||||
<h2>Requests</h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>id</th>
|
||||
<th>url</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>`))
|
||||
|
||||
service.OverRequests(func (id protocol.ID, url *url.URL) bool {
|
||||
res.Write([]byte(fmt.Sprintf (
|
||||
"<tr><td>%v</td><td>%v</td></tr>",
|
||||
id, url)))
|
||||
return true
|
||||
})
|
||||
|
||||
res.Write([]byte(`</tbody></table></body></html>`))
|
||||
}
|
||||
|
||||
func (rcon *Rcon) serveRouterOffline (res http.ResponseWriter, req *http.Request) {
|
||||
res.Header().Add("content-type", "text/html")
|
||||
res.WriteHeader(http.StatusNotFound)
|
||||
res.Write([]byte (
|
||||
`<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Router Offline</title>
|
||||
<style>` + css + `</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Router Offline</h1>
|
||||
<p>The router has not been started yet.</p>
|
||||
</body>
|
||||
</html>`))
|
||||
}
|
116
rotate/rotate.go
Normal file
@ -0,0 +1,116 @@
|
||||
// Package rotate provides an io.Writer that changes the file it writes to based
|
||||
// on the current date. It always writes to a file inside of the directory it is
|
||||
// given, and only switches files once it has finished writing a line and the
|
||||
// date has changed. It is intended to be used with log.SetOutput().
|
||||
package rotate
|
||||
|
||||
import "os"
|
||||
import "io"
|
||||
import "time"
|
||||
import "errors"
|
||||
import "path/filepath"
|
||||
|
||||
type logger struct {
|
||||
directory string
|
||||
file io.WriteCloser
|
||||
previousDay int
|
||||
closed bool
|
||||
}
|
||||
|
||||
// New returns a new logger that will always log to directory/YYYY-MM-DD.log.
|
||||
// When its close method is called, it will close any open file and stop
|
||||
// accepting calls to Write. A closed logger may not be re-opened.
|
||||
func New (directory string) (io.WriteCloser, error) {
|
||||
logger := &logger { directory: directory }
|
||||
err := logger.updateCurrentFile()
|
||||
if err != nil { return nil, err }
|
||||
return logger, nil
|
||||
}
|
||||
|
||||
func (logger *logger) Write (buffer []byte) (n int, err error) {
|
||||
if logger.closed {
|
||||
return 0, errors.New("rotate: attempt to write to closed logger")
|
||||
}
|
||||
|
||||
if logger.file == nil {
|
||||
err = logger. updateCurrentFile()
|
||||
if err != nil { return }
|
||||
}
|
||||
|
||||
for buffer != nil {
|
||||
var outgoing []byte
|
||||
var justWrote int
|
||||
outgoing, buffer = splitLine(buffer)
|
||||
justWrote, err = logger.file.Write(outgoing)
|
||||
n += justWrote
|
||||
if err != nil { return }
|
||||
|
||||
err = logger.updateCurrentFile()
|
||||
if err != nil { return }
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (logger *logger) Close () error {
|
||||
return logger.file.Close()
|
||||
}
|
||||
|
||||
func (logger *logger) updateCurrentFile() (err error) {
|
||||
if logger.closed { return }
|
||||
|
||||
// yes this is not a correct measure of days since 1970 but all we need
|
||||
// to know is "has the date changed?"
|
||||
now := time.Now()
|
||||
currentDay := (now.Year() - 1970) * 366 + now.YearDay()
|
||||
|
||||
if currentDay > logger.previousDay || logger.file == nil {
|
||||
if logger.file != nil { logger.file.Close() }
|
||||
|
||||
logger.file, err = os.OpenFile(
|
||||
filepath.Join(logger.directory, now.Format("2006-01-02.log")),
|
||||
os.O_WRONLY | os.O_APPEND | os.O_CREATE,
|
||||
0660)
|
||||
if err != nil { return }
|
||||
}
|
||||
|
||||
logger.previousDay = currentDay
|
||||
return
|
||||
}
|
||||
|
||||
func splitLine (buffer []byte) (left, right []byte) {
|
||||
index := indexOf(buffer, '\n')
|
||||
if index < 1 { return buffer, nil }
|
||||
index += 1
|
||||
return buffer[:index], buffer[index:]
|
||||
}
|
||||
|
||||
func indexOf[T comparable] (haystack []T, needle T) int {
|
||||
for index, element := range haystack {
|
||||
if element == needle {
|
||||
return index
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
type lineWriter struct {
|
||||
destination func (line []byte) (int, error)
|
||||
}
|
||||
|
||||
func LineWriter (destination func (line []byte) (int, error)) io.Writer {
|
||||
return &lineWriter { destination: destination }
|
||||
}
|
||||
|
||||
func (writer lineWriter) Write (buffer []byte) (n int, err error) {
|
||||
for buffer != nil {
|
||||
var outgoing []byte
|
||||
var justWrote int
|
||||
outgoing, buffer = splitLine(buffer)
|
||||
justWrote, err = writer.destination(outgoing)
|
||||
n += justWrote
|
||||
if err != nil { return }
|
||||
}
|
||||
|
||||
return
|
||||
}
|
37
router/mux/http.go
Normal file
@ -0,0 +1,37 @@
|
||||
package mux
|
||||
|
||||
import "net/url"
|
||||
import "net/http"
|
||||
|
||||
type HTTP struct {
|
||||
Mux[http.Handler]
|
||||
}
|
||||
|
||||
func NewHTTP (resolver Resolver) *HTTP {
|
||||
mux := &HTTP { }
|
||||
mux.Mux.Redirect = mux.newRedirect
|
||||
mux.Mux.NotFound = mux.newNotFound
|
||||
mux.Mux.Resolver = resolver
|
||||
return mux
|
||||
}
|
||||
|
||||
func (mux *HTTP) ServeHTTP (res http.ResponseWriter, req *http.Request) {
|
||||
if req.RequestURI == "*" {
|
||||
if req.ProtoAtLeast(1, 1) {
|
||||
res.Header().Set("Connection", "close")
|
||||
}
|
||||
res.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
handler, _ := mux.Handler(req.URL)
|
||||
handler.ServeHTTP(res, req)
|
||||
}
|
||||
|
||||
func (mux *HTTP) newNotFound (where *url.URL) http.Handler {
|
||||
return http.NotFoundHandler()
|
||||
}
|
||||
|
||||
func (mux *HTTP) newRedirect (where *url.URL) http.Handler {
|
||||
return http.RedirectHandler(where.String(), http.StatusMovedPermanently)
|
||||
}
|
245
router/mux/mux.go
Normal file
@ -0,0 +1,245 @@
|
||||
package mux
|
||||
|
||||
import "net"
|
||||
import "sync"
|
||||
import "path"
|
||||
import "sort"
|
||||
import "errors"
|
||||
import "strings"
|
||||
import "net/url"
|
||||
|
||||
type Resolver interface {
|
||||
ResolveAlias (alias string) string
|
||||
}
|
||||
|
||||
// Mux is a generic request multiplexer based off of http.ServeMux. It can be
|
||||
// adapted to any protocol where requests to a URL are handled.
|
||||
type Mux[HANDLER any] struct {
|
||||
// These must be non-nil!
|
||||
Redirect func (*url.URL) HANDLER
|
||||
NotFound func (*url.URL) HANDLER
|
||||
Resolver Resolver
|
||||
|
||||
mutex sync.RWMutex
|
||||
exactEntries map[string]muxEntry[HANDLER]
|
||||
sortedEntries []muxEntry[HANDLER] // slice of entries sorted from longest to shortest.
|
||||
}
|
||||
|
||||
type muxEntry[HANDLER any] struct {
|
||||
handler HANDLER
|
||||
pattern string
|
||||
}
|
||||
|
||||
func cleanPath (p string) string {
|
||||
if p == "" {
|
||||
return "/"
|
||||
}
|
||||
|
||||
if p[0] != '/' {
|
||||
p = "/" + p
|
||||
}
|
||||
|
||||
np := path.Clean(p)
|
||||
// path.Clean removes trailing slash except for root;
|
||||
// put the trailing slash back if necessary.
|
||||
if p[len(p)-1] == '/' && np != "/" {
|
||||
// Fast path for common case of p being the string we want:
|
||||
if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
|
||||
np = p
|
||||
} else {
|
||||
np += "/"
|
||||
}
|
||||
}
|
||||
|
||||
return np
|
||||
}
|
||||
|
||||
func stripHostPort (h string) string {
|
||||
// If no port on host, return unchanged
|
||||
if !strings.Contains(h, ":") {
|
||||
return h
|
||||
}
|
||||
|
||||
host, _, err := net.SplitHostPort(h)
|
||||
if err != nil {
|
||||
return h // on error, return unchanged
|
||||
}
|
||||
|
||||
return host
|
||||
}
|
||||
|
||||
func (mux *Mux[HANDLER]) Handler (where *url.URL) (h HANDLER, pattern string) {
|
||||
// All other requests have any port stripped and path cleaned
|
||||
// before passing to mux.handler.
|
||||
host := stripHostPort(where.Host)
|
||||
path := cleanPath(where.Path)
|
||||
host = mux.Resolver.ResolveAlias(host)
|
||||
pat := host + path
|
||||
|
||||
// If the given path is /tree and its handler is not registered,
|
||||
// redirect for /tree/.
|
||||
u, shouldRedirect := mux.redirectToPathSlash(host, path, where)
|
||||
if shouldRedirect {
|
||||
return mux.Redirect(u), u.Path
|
||||
}
|
||||
|
||||
if path != where.Path {
|
||||
_, pattern = mux.match(pat, where)
|
||||
u := &url.URL{Path: path, RawQuery: where.RawQuery}
|
||||
return mux.Redirect(u), pattern
|
||||
}
|
||||
|
||||
return mux.match(pat, where)
|
||||
}
|
||||
|
||||
func (mux *Mux[HANDLER]) redirectToPathSlash (host, path string, u *url.URL) (*url.URL, bool) {
|
||||
mux.mutex.RLock()
|
||||
shouldRedirect := mux.shouldRedirectRLocked(host, path)
|
||||
mux.mutex.RUnlock()
|
||||
if !shouldRedirect {
|
||||
return u, false
|
||||
}
|
||||
path = path + "/"
|
||||
u = &url.URL{Path: path, RawQuery: u.RawQuery}
|
||||
return u, true
|
||||
}
|
||||
|
||||
func (mux *Mux[HANDLER]) shouldRedirectRLocked (host, path string) bool {
|
||||
p := []string{path, host + path}
|
||||
|
||||
for _, c := range p {
|
||||
if _, exist := mux.exactEntries[c]; exist {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
n := len(path)
|
||||
if n == 0 {
|
||||
return false
|
||||
}
|
||||
for _, c := range p {
|
||||
if _, exist := mux.exactEntries[c+"/"]; exist {
|
||||
return path[n-1] != '/'
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (mux *Mux[HANDLER]) match (path string, original *url.URL) (h HANDLER, pattern string) {
|
||||
// Check for exact match first.
|
||||
entry, matchExists := mux.exactEntries[path]
|
||||
if matchExists {
|
||||
return entry.handler, entry.pattern
|
||||
}
|
||||
|
||||
// Check for longest valid match. mux.es contains all patterns
|
||||
// that end in / sorted from longest to shortest.
|
||||
for _, entry := range mux.sortedEntries {
|
||||
if strings.HasPrefix(path, entry.pattern) {
|
||||
return entry.handler, entry.pattern
|
||||
}
|
||||
}
|
||||
|
||||
return mux.NotFound(original), ""
|
||||
}
|
||||
|
||||
func (mux *Mux[HANDLER]) Handle (pattern string, handler HANDLER) error {
|
||||
mux.mutex.Lock()
|
||||
defer mux.mutex.Unlock()
|
||||
|
||||
if pattern == "" {
|
||||
return errors.New(
|
||||
"mux: invalid pattern " + pattern +
|
||||
", cannot be empty.")
|
||||
}
|
||||
|
||||
if pattern[0] == '/' {
|
||||
return errors.New(
|
||||
"mux: invalid pattern " + pattern +
|
||||
", must be host specific.")
|
||||
}
|
||||
|
||||
if _, exist := mux.exactEntries[pattern]; exist {
|
||||
return errors.New("mux: existing mount on " + pattern)
|
||||
}
|
||||
|
||||
if mux.exactEntries == nil {
|
||||
mux.exactEntries = make(map[string] muxEntry[HANDLER])
|
||||
}
|
||||
|
||||
entry := muxEntry[HANDLER] { handler: handler, pattern: pattern }
|
||||
mux.exactEntries[pattern] = entry
|
||||
if pattern[len(pattern)-1] == '/' {
|
||||
mux.sortedEntries = appendSorted(mux.sortedEntries, entry)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mux *Mux[HANDLER]) Unhandle (pattern string) error {
|
||||
mux.mutex.Lock()
|
||||
defer mux.mutex.Unlock()
|
||||
|
||||
// delete from exact match list
|
||||
if _, registered := mux.exactEntries[pattern]; !registered {
|
||||
return errors.New(
|
||||
"mux: pattern " + pattern + " is not mounted")
|
||||
}
|
||||
delete(mux.exactEntries, pattern)
|
||||
|
||||
// delete from sorted list, if its in there.
|
||||
newLen := 0
|
||||
for index, entry := range mux.sortedEntries {
|
||||
if entry.pattern != pattern {
|
||||
mux.sortedEntries[newLen] = mux.sortedEntries[index]
|
||||
newLen++
|
||||
}
|
||||
}
|
||||
mux.sortedEntries = mux.sortedEntries[:newLen]
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mux *Mux[HANDLER]) OverHandlers (callback func (pattern string, handler HANDLER) bool) {
|
||||
overSorted (mux.exactEntries, func (pattern string, entry muxEntry[HANDLER]) bool {
|
||||
return callback(pattern, entry.handler)
|
||||
})
|
||||
}
|
||||
|
||||
func appendSorted[HANDLER any] (entries []muxEntry[HANDLER], entry muxEntry[HANDLER]) []muxEntry[HANDLER] {
|
||||
entriesLen := len(entries)
|
||||
index := sort.Search(entriesLen, func(index int) bool {
|
||||
return len(entries[index].pattern) < len(entry.pattern)
|
||||
})
|
||||
|
||||
if index == entriesLen {
|
||||
return append(entries, entry)
|
||||
}
|
||||
|
||||
// we now know that i points at where we want to insert
|
||||
// try to grow the slice in place, any entry works
|
||||
entries = append(entries, muxEntry[HANDLER] { })
|
||||
copy(entries[index+1:], entries[index:]) // Move shorter entries down
|
||||
entries[index] = entry
|
||||
return entries
|
||||
}
|
||||
|
||||
func overSorted[V any] (unsorted map[string] V, fn func (string, V) bool) {
|
||||
keys := sortKeys(unsorted)
|
||||
for _, key := range keys {
|
||||
if !fn(key, unsorted[key]) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sortKeys[V any] (unsorted map[string] V) []string {
|
||||
sortedKeys := make([]string, len(unsorted))
|
||||
index := 0
|
||||
for key, _ := range unsorted {
|
||||
sortedKeys[index] = key
|
||||
index ++
|
||||
}
|
||||
sort.Strings(sortedKeys)
|
||||
|
||||
return sortedKeys
|
||||
}
|
93
router/router.go
Normal file
@ -0,0 +1,93 @@
|
||||
package router
|
||||
|
||||
import "log"
|
||||
import "net"
|
||||
// import "errors"
|
||||
import "net/http"
|
||||
import "hnakra/config"
|
||||
import "hnakra/protocol"
|
||||
import "hnakra/router/mux"
|
||||
|
||||
type Pattern struct {
|
||||
Scheme string
|
||||
Host string
|
||||
Path string
|
||||
}
|
||||
|
||||
func (pattern Pattern) MuxPattern () string {
|
||||
return pattern.Host + pattern.Path
|
||||
}
|
||||
|
||||
func (pattern Pattern) String () string {
|
||||
return pattern.Scheme + "://" + pattern.Host + pattern.Path
|
||||
}
|
||||
|
||||
func (pattern *Pattern) FillDefaults () {
|
||||
if pattern.Scheme == "" { pattern.Scheme = "https" }
|
||||
if pattern.Host == "" { pattern.Host = "@" }
|
||||
if pattern.Path == "" { pattern.Path = "/" }
|
||||
}
|
||||
|
||||
type Router struct {
|
||||
config config.Config
|
||||
http *mux.HTTP
|
||||
services map[*Service] struct { }
|
||||
}
|
||||
|
||||
func New (config config.Config) *Router {
|
||||
router := &Router {
|
||||
config: config,
|
||||
http: mux.NewHTTP(config),
|
||||
services: make(map[*Service] struct { }),
|
||||
}
|
||||
return router
|
||||
}
|
||||
|
||||
func (router *Router) HTTPMux () *mux.HTTP {
|
||||
return router.http
|
||||
}
|
||||
|
||||
func (router *Router) Accept (conn net.Conn) {
|
||||
router.newService(conn)
|
||||
}
|
||||
|
||||
func (router *Router) ServeHTTP (res http.ResponseWriter, req *http.Request) {
|
||||
log.Println("->?", req.RemoteAddr, "requests", req.URL.String())
|
||||
router.http.ServeHTTP(res, req)
|
||||
}
|
||||
|
||||
// TODO: uniquely identify connected services by an ID
|
||||
|
||||
func (router *Router) Service (name string) *Service {
|
||||
for service := range router.services {
|
||||
if service.Name() == name {
|
||||
return service
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (router *Router) OverServices (callback func (service *Service) bool) {
|
||||
for service := range router.services {
|
||||
if !callback(service) { break }
|
||||
}
|
||||
}
|
||||
|
||||
func (router *Router) list (service *Service) {
|
||||
router.services[service] = struct { } { }
|
||||
}
|
||||
|
||||
func (router *Router) unlist (service *Service) {
|
||||
delete(router.services, service)
|
||||
}
|
||||
|
||||
func (router *Router) Validate (name string, key []byte, pattern Pattern) protocol.Status {
|
||||
user := router.config.User(name)
|
||||
if user == nil || !user.Validate(key) {
|
||||
return protocol.StatusBadCredentials
|
||||
}
|
||||
if !user.CanMountOn(pattern.Scheme, pattern.Host, pattern.Path) {
|
||||
return protocol.StatusBadMount
|
||||
}
|
||||
return protocol.StatusOk
|
||||
}
|
392
router/service.go
Normal file
@ -0,0 +1,392 @@
|
||||
package router
|
||||
|
||||
import "io"
|
||||
import "log"
|
||||
import "net"
|
||||
import "sync"
|
||||
import "bufio"
|
||||
import "net/url"
|
||||
import "net/http"
|
||||
import "hnakra/protocol"
|
||||
|
||||
type activeRequest struct {
|
||||
service *Service
|
||||
body chan []byte
|
||||
requestBody io.ReadCloser
|
||||
header http.Header
|
||||
status int
|
||||
url *url.URL
|
||||
|
||||
res http.ResponseWriter
|
||||
wroteHeader bool
|
||||
headerMutex sync.Mutex
|
||||
}
|
||||
|
||||
func (request *activeRequest) ensureHeader () {
|
||||
request.headerMutex.Lock()
|
||||
defer request.headerMutex.Unlock()
|
||||
if request.wroteHeader { return }
|
||||
|
||||
for key, values := range request.header {
|
||||
for _, value := range values {
|
||||
request.res.Header().Add(key, value)
|
||||
}
|
||||
}
|
||||
request.res.WriteHeader(request.status)
|
||||
request.wroteHeader = true
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
router *Router
|
||||
validate func (user string, key []byte, pattern Pattern) protocol.Status
|
||||
pattern Pattern
|
||||
|
||||
user, name, description string
|
||||
|
||||
idFactory *protocol.IDFactory
|
||||
requests map[protocol.ID] *activeRequest
|
||||
requestsLock sync.RWMutex
|
||||
|
||||
conn net.Conn
|
||||
connLock sync.Mutex
|
||||
connReadWriter *bufio.ReadWriter
|
||||
connErr error
|
||||
}
|
||||
|
||||
func (router *Router) newService (conn net.Conn) (service *Service) {
|
||||
service = &Service {
|
||||
idFactory: protocol.NewRouterIDFactory(),
|
||||
router: router,
|
||||
validate: router.Validate,
|
||||
conn: conn,
|
||||
requests: make(map[protocol.ID] *activeRequest),
|
||||
connReadWriter: bufio.NewReadWriter (
|
||||
bufio.NewReader(conn),
|
||||
bufio.NewWriter(conn)),
|
||||
}
|
||||
go service.work()
|
||||
return
|
||||
}
|
||||
|
||||
func (service *Service) OverRequests (callback func (protocol.ID, *url.URL) bool) {
|
||||
service.requestsLock.RLock()
|
||||
defer service.requestsLock.RUnlock()
|
||||
for id, request := range service.requests {
|
||||
if !callback(id, request.url) { break }
|
||||
}
|
||||
}
|
||||
|
||||
func (service *Service) User () string {
|
||||
return service.user
|
||||
}
|
||||
|
||||
func (service *Service) Name () string {
|
||||
return service.name
|
||||
}
|
||||
|
||||
func (service *Service) Description () string {
|
||||
return service.description
|
||||
}
|
||||
|
||||
func (service *Service) Pattern () Pattern {
|
||||
return service.pattern
|
||||
}
|
||||
|
||||
func (service *Service) Close () error {
|
||||
return service.conn.Close()
|
||||
}
|
||||
|
||||
func (service *Service) Shutdown () error {
|
||||
// TODO: wait for all requests to finish
|
||||
return service.conn.Close()
|
||||
}
|
||||
|
||||
func (service *Service) ServeHTTP (res http.ResponseWriter, req *http.Request) {
|
||||
// if we are only accepting https requests and we recieve an http one,
|
||||
// redirect to the https version
|
||||
if req.TLS == nil && service.pattern.Scheme == "https" {
|
||||
newURL := req.URL
|
||||
newURL.Scheme = service.pattern.Scheme
|
||||
http.Redirect(res, req, newURL.String(), http.StatusPermanentRedirect)
|
||||
return
|
||||
}
|
||||
|
||||
// create a new request
|
||||
request, id := service.generateActiveRequest(res, req)
|
||||
defer service.freeRequest(id)
|
||||
|
||||
// ask the service to fulfill it
|
||||
err := service.send(protocol.MessageHTTPRequest {
|
||||
ID: id,
|
||||
Address: req.RemoteAddr,
|
||||
Method: req.Method,
|
||||
URL: req.URL.String(),
|
||||
Header: protocol.Map(req.Header),
|
||||
})
|
||||
if err != nil {
|
||||
http.Error (
|
||||
res, "connection to service closed abruptly: " +
|
||||
err.Error(), http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
|
||||
// read in the body chunk bu chunk from the channel, and finalize the
|
||||
// request when the channel is closed
|
||||
for chunk := range request.body {
|
||||
request.ensureHeader()
|
||||
res.Write(chunk)
|
||||
}
|
||||
|
||||
// if we have stopped serving the page prematurely due to an error,
|
||||
// inform the user (if possible)
|
||||
if service.connErr != nil && !request.wroteHeader {
|
||||
http.Error (
|
||||
res, "connection to service closed abruptly: " +
|
||||
service.connErr.Error(), http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (service *Service) generateActiveRequest (
|
||||
res http.ResponseWriter,
|
||||
req *http.Request,
|
||||
) (
|
||||
*activeRequest,
|
||||
protocol.ID,
|
||||
) {
|
||||
service.requestsLock.Lock()
|
||||
defer service.requestsLock.Unlock()
|
||||
|
||||
id := service.idFactory.Next()
|
||||
request := &activeRequest {
|
||||
service: service,
|
||||
body: make(chan []byte),
|
||||
header: make(http.Header),
|
||||
status: http.StatusOK,
|
||||
url: req.URL,
|
||||
requestBody: req.Body,
|
||||
res: res,
|
||||
}
|
||||
service.requests[id] = request
|
||||
return request, id
|
||||
}
|
||||
|
||||
func (service *Service) freeRequest (id protocol.ID) {
|
||||
service.requestsLock.Lock()
|
||||
defer service.requestsLock.Unlock()
|
||||
delete(service.requests, id)
|
||||
service.idFactory.Free(id)
|
||||
}
|
||||
|
||||
func (service *Service) work () {
|
||||
defer log.Println("X=- connection to", service.conn.RemoteAddr(), "closed")
|
||||
unhandle, ok := service.authenticate()
|
||||
if !ok { return }
|
||||
|
||||
// dismantle service when we exit
|
||||
defer func () {
|
||||
unhandle()
|
||||
service.conn.Close()
|
||||
|
||||
closedRequest := false
|
||||
service.requestsLock.Lock()
|
||||
for _, request := range service.requests {
|
||||
closedRequest = true
|
||||
close(request.body)
|
||||
}
|
||||
service.requestsLock.Unlock()
|
||||
|
||||
if service.connErr != nil && closedRequest {
|
||||
log.Println("!!! service connection error:", service.connErr)
|
||||
}
|
||||
} ()
|
||||
|
||||
// respond to requests
|
||||
for {
|
||||
message, err := protocol.ReadMessage(service.connReadWriter)
|
||||
if err != nil {
|
||||
service.connErr = err
|
||||
return
|
||||
}
|
||||
|
||||
switch message.(type) {
|
||||
// set the header and status code of the request. when the first
|
||||
// body chunk is sent or the body is ended without any chunks
|
||||
// being sent, the serving goroutine will send the header data.
|
||||
case protocol.MessageHTTPResponse:
|
||||
response := message.(protocol.MessageHTTPResponse)
|
||||
service.requestsLock.RLock()
|
||||
if _, ok := service.requests[response.ID]; ok {
|
||||
service.requests[response.ID].header = http.Header(response.Header)
|
||||
service.requests[response.ID].status = int(response.Status)
|
||||
service.requests[response.ID].ensureHeader()
|
||||
}
|
||||
service.requestsLock.RUnlock()
|
||||
|
||||
// send the body chunk along the body channel to the goroutine
|
||||
// serving the request.
|
||||
case protocol.MessageHTTPBodySegment:
|
||||
segment := message.(protocol.MessageHTTPBodySegment)
|
||||
service.requestsLock.RLock()
|
||||
if _, ok := service.requests[segment.ID]; ok {
|
||||
service.requests[segment.ID].body <- segment.Data
|
||||
} else {
|
||||
log.Println("!!! service sent segment for nonexistent request", segment.ID)
|
||||
}
|
||||
service.requestsLock.RUnlock()
|
||||
|
||||
// close the body channel and remove the request from the list,
|
||||
// signaling to the goroutine serving the request that the body
|
||||
// has been read entirely.
|
||||
case protocol.MessageHTTPBodyEnd:
|
||||
end := message.(protocol.MessageHTTPBodyEnd)
|
||||
service.requestsLock.Lock()
|
||||
if _, ok := service.requests[end.ID]; ok {
|
||||
close(service.requests[end.ID].body)
|
||||
service.requests[end.ID].body = nil
|
||||
} else {
|
||||
log.Println("!!! service ended nonexistent request", end.ID)
|
||||
}
|
||||
service.requestsLock.Unlock()
|
||||
|
||||
// the client wants the reqeust body
|
||||
case protocol.MessageHTTPBodyRequest:
|
||||
id := message.(protocol.MessageHTTPBodyRequest).ID
|
||||
service.requestsLock.RLock()
|
||||
if request, ok := service.requests[id]; ok {
|
||||
body := request.requestBody
|
||||
request.requestBody = nil
|
||||
|
||||
if body == nil {
|
||||
// TODO: send an error to the service bc this
|
||||
// means either the implementation of
|
||||
// http.Request is broken or the service has
|
||||
// requested the body twice.
|
||||
} else {
|
||||
go service.sendRequestBody(body, id)
|
||||
}
|
||||
} else {
|
||||
log.Println("!!! service requested body for nonexistent request", id)
|
||||
}
|
||||
service.requestsLock.RUnlock()
|
||||
|
||||
// a message from the client.
|
||||
case protocol.MessageStatus:
|
||||
status := message.(protocol.MessageStatus)
|
||||
log.Println("(i)", service.name, "says:", status.Status)
|
||||
|
||||
default:
|
||||
log.Println("ERR service sent unknown type code")
|
||||
service.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (service *Service) sendRequestBody (body io.ReadCloser, id protocol.ID) {
|
||||
// FIXME: is this a good max buffer size? maybe make it configurable
|
||||
buffer := [2048]byte { }
|
||||
for {
|
||||
n, err := body.Read(buffer[:])
|
||||
|
||||
if n > 0 {
|
||||
if service.send(protocol.MessageHTTPBodySegment {
|
||||
ID: id,
|
||||
Data: buffer[:n],
|
||||
}) != nil { return }
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
// TODO: send the service an error
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
service.send(protocol.MessageHTTPBodyEnd { ID: id })
|
||||
}
|
||||
|
||||
func (service *Service) authenticate () (func(), bool) {
|
||||
// get login details
|
||||
message, err := protocol.ReadMessage(service.connReadWriter)
|
||||
if err != nil {
|
||||
service.Close()
|
||||
return nil, false
|
||||
}
|
||||
login, ok := message.(protocol.MessageLogin)
|
||||
if !ok {
|
||||
log.Println (
|
||||
"ERR", service.conn.RemoteAddr(),
|
||||
"sent wrong type code, expected",
|
||||
protocol.TypeLogin)
|
||||
service.send(protocol.MessageStatus {
|
||||
Status: protocol.StatusBadMessageType,
|
||||
})
|
||||
service.Close()
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// create pattern
|
||||
service.pattern = Pattern {
|
||||
Scheme: login.Scheme,
|
||||
Host: login.Host,
|
||||
Path: login.Path,
|
||||
}
|
||||
service.pattern.FillDefaults()
|
||||
|
||||
// validate credentials
|
||||
status := service.validate(login.User, login.Key, service.pattern)
|
||||
service.send(protocol.MessageStatus { Status: status })
|
||||
if status == protocol.StatusOk {
|
||||
service.user = login.User
|
||||
service.name = login.Name
|
||||
service.description = login.Description
|
||||
|
||||
log.Println (
|
||||
"-->", service.conn.RemoteAddr(),
|
||||
"logged in as", login.User, "on", service.pattern)
|
||||
} else {
|
||||
log.Println (
|
||||
"ERR", service.conn.RemoteAddr(),
|
||||
"failed login as", login.User, "on", service.pattern)
|
||||
service.conn.Close()
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// mount service on the mux.
|
||||
var unhandle func ()
|
||||
muxPattern := service.pattern.MuxPattern()
|
||||
switch service.pattern.Scheme {
|
||||
case "http", "https":
|
||||
err = service.router.HTTPMux().Handle(muxPattern, service)
|
||||
unhandle = func () {
|
||||
service.router.HTTPMux().Unhandle(muxPattern)
|
||||
}
|
||||
default:
|
||||
err = protocol.StatusBadMount
|
||||
}
|
||||
if err != nil {
|
||||
log.Println (
|
||||
"ERR", service.name,
|
||||
"sent bad mount pattern:", service.pattern)
|
||||
service.send(protocol.MessageStatus {
|
||||
Status: protocol.StatusBadMount,
|
||||
})
|
||||
service.Close()
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// list the service in the router
|
||||
service.router.list(service)
|
||||
return func () {
|
||||
unhandle()
|
||||
service.router.unlist(service)
|
||||
}, true
|
||||
}
|
||||
|
||||
func (service *Service) send (message protocol.Message) (err error) {
|
||||
service.connLock.Lock()
|
||||
defer service.connLock.Unlock()
|
||||
err = message.Send(service.connReadWriter)
|
||||
if err != nil { return }
|
||||
return service.connReadWriter.Flush()
|
||||
}
|
104
service/handle.go
Normal file
@ -0,0 +1,104 @@
|
||||
package service
|
||||
|
||||
import "io"
|
||||
import "log"
|
||||
import "net/http"
|
||||
import "hnakra/protocol"
|
||||
|
||||
func (mount *HTTP) handle (request protocol.MessageHTTPRequest) {
|
||||
log.Println("->?", request.Address, "requests", request.URL)
|
||||
bodyReader := &bodyReader {
|
||||
id: request.ID,
|
||||
reader: mount.requests.readerFor(request.ID),
|
||||
send: mount.send,
|
||||
close: func () { mount.requests.end(request.ID) },
|
||||
}
|
||||
defer mount.requests.remove(request.ID)
|
||||
|
||||
handler := mount.Handler
|
||||
if handler == nil {
|
||||
handler = http.DefaultServeMux
|
||||
}
|
||||
|
||||
// TODO possibly populate the http version and ContentLength
|
||||
// TODO: if there is an error, send an error status to the server
|
||||
httpRequest, _ := http.NewRequest(request.Method, request.URL, bodyReader)
|
||||
httpRequest.Header = http.Header(request.Header)
|
||||
|
||||
handler.ServeHTTP(&responseWriter {
|
||||
id: request.ID,
|
||||
header: make(http.Header),
|
||||
send: mount.send,
|
||||
}, httpRequest)
|
||||
|
||||
mount.send(protocol.MessageHTTPBodyEnd { ID: request.ID })
|
||||
}
|
||||
|
||||
type bodyReader struct {
|
||||
reader io.Reader
|
||||
requested bool
|
||||
id protocol.ID
|
||||
send func (protocol.Message) error
|
||||
close func ()
|
||||
}
|
||||
|
||||
func (reader *bodyReader) Read (buffer []byte) (amount int, err error) {
|
||||
if !reader.requested {
|
||||
err = reader.send(protocol.MessageHTTPBodyRequest {
|
||||
ID: reader.id,
|
||||
})
|
||||
if err != nil { return }
|
||||
reader.requested = true
|
||||
}
|
||||
return reader.reader.Read(buffer)
|
||||
}
|
||||
|
||||
func (reader *bodyReader) Close () error {
|
||||
// TODO: possibly make this mthd ask the server to stop sending body
|
||||
// segments
|
||||
reader.close()
|
||||
return nil
|
||||
}
|
||||
|
||||
type responseWriter struct {
|
||||
header http.Header
|
||||
wroteHeader bool
|
||||
id protocol.ID
|
||||
send func (protocol.Message) error
|
||||
}
|
||||
|
||||
func (writer *responseWriter) Header () http.Header {
|
||||
return writer.header
|
||||
}
|
||||
|
||||
func (writer *responseWriter) Write (buffer []byte) (amount int, err error) {
|
||||
if !writer.wroteHeader {
|
||||
writer.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
for len(buffer) > 0 {
|
||||
sent := int(protocol.MaxIntOfSize(2) - 1)
|
||||
if len(buffer) < sent {
|
||||
sent = len(buffer)
|
||||
}
|
||||
err = writer.send(protocol.MessageHTTPBodySegment {
|
||||
ID: writer.id,
|
||||
Data: buffer[:sent],
|
||||
})
|
||||
if err != nil { return }
|
||||
buffer = buffer[sent:]
|
||||
amount += sent
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (writer *responseWriter) WriteHeader (statusCode int) {
|
||||
if writer.wroteHeader { return }
|
||||
|
||||
writer.wroteHeader = true
|
||||
writer.send(protocol.MessageHTTPResponse {
|
||||
ID: writer.id,
|
||||
Status: uint16(statusCode),
|
||||
Header: protocol.Map(writer.header),
|
||||
})
|
||||
}
|
100
service/http.go
Normal file
@ -0,0 +1,100 @@
|
||||
package service
|
||||
|
||||
import "log"
|
||||
import "net"
|
||||
import "sync"
|
||||
import "bufio"
|
||||
import "errors"
|
||||
import "net/http"
|
||||
import "hnakra/protocol"
|
||||
|
||||
// HTTP is an https:// mount.
|
||||
type HTTP struct {
|
||||
Mount
|
||||
|
||||
// AllowInsecure allows this mount to respond to plain-text HTTP
|
||||
// requests. You can get a TLS cert for free nowadays so there are very
|
||||
// few cases where you'd want this on.
|
||||
AllowInsecure bool
|
||||
|
||||
// Handler specifies the handler to invoke. If it is nil,
|
||||
// http.DefaultServeMux is used.
|
||||
Handler http.Handler
|
||||
|
||||
conn net.Conn
|
||||
connLock sync.Mutex
|
||||
connReadWriter *bufio.ReadWriter
|
||||
requests requestManager
|
||||
}
|
||||
|
||||
// Close closes the mount abruptly, interrupting any active connections.
|
||||
func (mount *HTTP) Close () error {
|
||||
mount.connLock.Lock()
|
||||
defer mount.connLock.Unlock()
|
||||
return mount.conn.Close()
|
||||
}
|
||||
|
||||
// Shutdown gracefully shuts down the service without interrupting any active
|
||||
// connections.
|
||||
func (mount *HTTP) Shutdown () error {
|
||||
// TODO
|
||||
return mount.Close()
|
||||
}
|
||||
|
||||
// Run connects to the router, and blocks while fulfilling requests. This method
|
||||
// will only return when the connection to the router has been closed.
|
||||
func (mount *HTTP) Run () (err error) {
|
||||
if mount.AllowInsecure {
|
||||
mount.conn, err = mount.connect("http")
|
||||
} else {
|
||||
mount.conn, err = mount.connect("https")
|
||||
}
|
||||
if err != nil { return }
|
||||
|
||||
mount.connReadWriter = bufio.NewReadWriter (
|
||||
bufio.NewReader(mount.conn),
|
||||
bufio.NewWriter(mount.conn))
|
||||
mount.requests.init()
|
||||
|
||||
for {
|
||||
message, err := protocol.ReadMessage(mount.connReadWriter)
|
||||
if err != nil { return err }
|
||||
|
||||
switch message.(type) {
|
||||
case protocol.MessageHTTPRequest:
|
||||
request := message.(protocol.MessageHTTPRequest)
|
||||
mount.requests.add(request.ID)
|
||||
go mount.handle(request)
|
||||
|
||||
case protocol.MessageHTTPBodySegment:
|
||||
segment := message.(protocol.MessageHTTPBodySegment)
|
||||
mount.requests.feed(segment.ID, segment.Data)
|
||||
|
||||
case protocol.MessageHTTPBodyEnd:
|
||||
end := message.(protocol.MessageHTTPBodyEnd)
|
||||
mount.requests.end(end.ID)
|
||||
|
||||
case protocol.MessageStatus:
|
||||
status := message.(protocol.MessageStatus)
|
||||
log.Println("router says:", status.Status)
|
||||
|
||||
default:
|
||||
mount.Close()
|
||||
return errors.New("router sent unknown type code")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NewHTTP creates a very basic https:// mount with the specified name and
|
||||
// description.
|
||||
func NewHTTP (name, description string) HTTP {
|
||||
return HTTP { Mount: M(name, description) }
|
||||
}
|
||||
|
||||
func (mount *HTTP) send (message protocol.Message) (err error) {
|
||||
mount.connLock.Lock()
|
||||
defer mount.connLock.Unlock()
|
||||
err = message.Send(mount.connReadWriter)
|
||||
if err != nil { return }
|
||||
return mount.connReadWriter.Flush()
|
||||
}
|
75
service/requestmanager.go
Normal file
@ -0,0 +1,75 @@
|
||||
package service
|
||||
|
||||
import "io"
|
||||
import "sync"
|
||||
import "hnakra/protocol"
|
||||
|
||||
const HTTP_BODY_CHANNEL_BUFFER_SIZE = 32
|
||||
|
||||
type requestManager struct {
|
||||
requests map[protocol.ID] chan []byte
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
func (manager *requestManager) init () {
|
||||
manager.requests = make(map[protocol.ID] chan []byte)
|
||||
}
|
||||
|
||||
func (manager *requestManager) add (id protocol.ID) {
|
||||
manager.lock.Lock()
|
||||
manager.requests[id] = make(chan []byte)
|
||||
manager.lock.Unlock()
|
||||
}
|
||||
|
||||
func (manager *requestManager) feed (id protocol.ID, buffer []byte) {
|
||||
manager.lock.RLock()
|
||||
if manager.requests[id] != nil {
|
||||
manager.requests[id] <- buffer
|
||||
}
|
||||
manager.lock.RUnlock()
|
||||
}
|
||||
|
||||
func (manager *requestManager) end (id protocol.ID) {
|
||||
manager.lock.RLock()
|
||||
if manager.requests[id] != nil {
|
||||
close(manager.requests[id])
|
||||
manager.requests[id] = nil
|
||||
}
|
||||
manager.lock.RUnlock()
|
||||
}
|
||||
|
||||
func (manager *requestManager) remove (id protocol.ID) {
|
||||
manager.lock.Lock()
|
||||
delete(manager.requests, id)
|
||||
manager.lock.Unlock()
|
||||
}
|
||||
|
||||
func (manager *requestManager) readerFor (id protocol.ID) io.Reader {
|
||||
manager.lock.RLock()
|
||||
channel := manager.requests[id]
|
||||
manager.lock.RUnlock()
|
||||
return byteChannelReader { channel: channel }
|
||||
}
|
||||
|
||||
type byteChannelReader struct {
|
||||
channel <- chan []byte
|
||||
leftover []byte
|
||||
}
|
||||
|
||||
func (reader byteChannelReader) Read (buffer []byte) (amount int, err error) {
|
||||
// first, try to fill the buffer with leftover data
|
||||
amount = copy(buffer, reader.leftover)
|
||||
if amount > 0 {
|
||||
reader.leftover = reader.leftover[amount:]
|
||||
return
|
||||
}
|
||||
|
||||
// if there is no leftover data, read from the channel
|
||||
incoming, open := <- reader.channel
|
||||
if !open { return 0, io.EOF }
|
||||
amount = copy(buffer, incoming)
|
||||
|
||||
// save any data we could not fit into the buffer
|
||||
reader.leftover = incoming[amount:]
|
||||
return
|
||||
}
|
187
service/service.go
Normal file
@ -0,0 +1,187 @@
|
||||
package service
|
||||
|
||||
import "os"
|
||||
import "log"
|
||||
import "fmt"
|
||||
import "net"
|
||||
import "errors"
|
||||
import "strings"
|
||||
import "crypto/tls"
|
||||
import "encoding/base64"
|
||||
import "hnakra/protocol"
|
||||
|
||||
// M creates a very basic mount with the specified name and description.
|
||||
func M (name, description string) Mount {
|
||||
return Mount {
|
||||
Name: name,
|
||||
Description: description,
|
||||
}
|
||||
}
|
||||
|
||||
// Mount contains generic information common to all mounts.
|
||||
type Mount struct {
|
||||
// Host specifies the host to mount on. If the host is left empty, it
|
||||
// will default to @ (meaning default/any host). The port is entirely up
|
||||
// to the router. Maximum length for host portion: 255 bytes
|
||||
Host string
|
||||
|
||||
// Path specifies the path to mount on. If the path ends with a /, then
|
||||
// all requests under the path will be sent to this service. If there is
|
||||
// no trailing /, this service will only recieve requests that match the
|
||||
// path exactly (when normalized).
|
||||
// Maximum length: 2^16-1 bytes
|
||||
Path string
|
||||
|
||||
// Router specifies the host:port of the router to connect to. This
|
||||
// defaults to $HNAKRA_ROUTER_HOST:$HNAKRA_ROUTER_PORT if left empty.
|
||||
// The default value of these environment variables (if not set) is
|
||||
// localhost:2048. If you are giving this service to other people, it is
|
||||
// a good idea to leave this empty.
|
||||
Router string
|
||||
|
||||
// Name should be set to a human-readable name of the service.
|
||||
// Maximum length: 255 bytes
|
||||
Name string
|
||||
|
||||
// Description should be set to a human-readable description of what the
|
||||
// service does.
|
||||
// Maximum length: 255 bytes
|
||||
Description string
|
||||
|
||||
// User is an optional string that specifies who is connecting to the
|
||||
// router. This can be used by routers in conjunction with the key
|
||||
// bytes in order to enforce rules about which service can do what. This
|
||||
// defaults to $HNAKRA_USER if left empty. If you are giving this
|
||||
// service to other people, it is a good idea to leave this empty.
|
||||
// Maximum length: 255 bytes
|
||||
User string
|
||||
|
||||
// Key is an optional byte slice that is sent to the router in order for
|
||||
// it to authorize the connection. If nil, this defaults to the contents
|
||||
// of $HNAKRA_KEY interpreted as base64. Do not embed a key in your
|
||||
// code - you should only use this if your service reads the key from a
|
||||
// safe source upon startup. In addition to this, If you choose to set
|
||||
// the key via the aforementioned enviroment variable, ensure that it
|
||||
// can only be read by the service.
|
||||
// Maximum length: 255 bytes
|
||||
Key []byte
|
||||
|
||||
// TLSConfig is an optional TLS configuration.
|
||||
TLSConfig *tls.Config
|
||||
|
||||
idFactory *protocol.IDFactory
|
||||
}
|
||||
|
||||
func (mount *Mount) connect (scheme string) (conn net.Conn, err error) {
|
||||
log.Println("(i) service", mount.Name)
|
||||
mount.idFactory = protocol.NewServiceIDFactory()
|
||||
|
||||
defaultRouterHost := os.Getenv("HNAKRA_ROUTER_HOST")
|
||||
if defaultRouterHost == "" {
|
||||
defaultRouterHost = "localhost"
|
||||
}
|
||||
defaultRouterPort := os.Getenv("HNAKRA_ROUTER_PORT")
|
||||
if defaultRouterPort == "" {
|
||||
defaultRouterPort = "2048"
|
||||
}
|
||||
|
||||
// parse router host/port
|
||||
routerHost, routerPort, _ := strings.Cut(mount.Router, ":")
|
||||
if routerHost == "" {
|
||||
routerHost = defaultRouterHost
|
||||
}
|
||||
if routerPort == "" {
|
||||
routerPort = defaultRouterPort
|
||||
}
|
||||
|
||||
// get mount point
|
||||
host := mount.Host
|
||||
if host == "" {
|
||||
host = "@"
|
||||
}
|
||||
if len(host) > 255 {
|
||||
return nil, errors.New("mount point host cannot be longer than 255 bytes")
|
||||
}
|
||||
path := mount.Path
|
||||
if path == "" {
|
||||
path = "/"
|
||||
}
|
||||
if len(path) > int(protocol.MaxIntOfSize(2)) {
|
||||
return nil, errors.New(fmt.Sprint (
|
||||
"mount point path cannot be longer than ",
|
||||
protocol.MaxIntOfSize(2), " bytes"))
|
||||
}
|
||||
|
||||
// get user
|
||||
user := mount.User
|
||||
if user == "" {
|
||||
user = os.Getenv("HNAKRA_USER")
|
||||
}
|
||||
if len(user) > 255 {
|
||||
return nil, errors.New("user cannot be longer than 255 bytes")
|
||||
}
|
||||
|
||||
// get key
|
||||
key := mount.Key
|
||||
if key == nil {
|
||||
key, err = base64.StdEncoding.DecodeString(os.Getenv("HNAKRA_KEY"))
|
||||
if err != nil { return nil, err }
|
||||
}
|
||||
if len(key) > 255 {
|
||||
return nil, errors.New("key cannot be longer than 255 bytes")
|
||||
}
|
||||
|
||||
// ensure name/description aren't too big
|
||||
if len(mount.Name) > 255 {
|
||||
return nil, errors.New("service name cannot be longer than 255 bytes")
|
||||
}
|
||||
if len(mount.Description) > 255 {
|
||||
return nil, errors.New("service description cannot be longer than 255 bytes")
|
||||
}
|
||||
|
||||
// connect to router
|
||||
routerAddr := fmt.Sprint(routerHost, ":", routerPort)
|
||||
log.Println("... dialing", routerAddr)
|
||||
conn, err = tls.Dial("tcp", routerAddr, mount.TLSConfig)
|
||||
if err != nil { return nil, err }
|
||||
|
||||
// log in
|
||||
log.Println (
|
||||
"... logging in as", user,
|
||||
"on", scheme + "://" + host + path)
|
||||
err = protocol.MessageLogin {
|
||||
ID: mount.idFactory.Next(),
|
||||
Version: protocol.Version { Major: 0, Minor: 0 },
|
||||
User: user,
|
||||
Key: key,
|
||||
Name: mount.Name,
|
||||
Description: mount.Description,
|
||||
Scheme: scheme,
|
||||
Host: host,
|
||||
Path: path,
|
||||
}.Send(conn)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// read status
|
||||
message, err := protocol.ReadMessage(conn)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
status, ok := message.(protocol.MessageStatus)
|
||||
if !ok {
|
||||
conn.Close()
|
||||
return nil, errors.New(fmt.Sprint("router sent unknown type, expecting", protocol.TypeStatus))
|
||||
}
|
||||
if status.Status != protocol.StatusOk {
|
||||
return nil, status
|
||||
}
|
||||
|
||||
log.Println(".// logged in")
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// TODO: other protocols like gemini, websocket, ftp, etc
|
34
srvhnakra/hnakra.go
Normal file
@ -0,0 +1,34 @@
|
||||
package srvhnakra
|
||||
|
||||
import "log"
|
||||
import "fmt"
|
||||
import "net"
|
||||
import "crypto/tls"
|
||||
import "hnakra/router"
|
||||
import "hnakra/config"
|
||||
|
||||
type Server struct {
|
||||
underlying net.Listener
|
||||
Config config.Config
|
||||
Router *router.Router
|
||||
}
|
||||
|
||||
func (server *Server) ListenAndServe () (err error) {
|
||||
server.underlying, err = tls.Listen (
|
||||
"tcp", fmt.Sprint(":", server.Config.RouterPort()),
|
||||
config.TLSConfigFor(server.Config))
|
||||
if err != nil { return err }
|
||||
|
||||
log.Println(".// router on", server.underlying.Addr())
|
||||
|
||||
for {
|
||||
conn, err := server.underlying.Accept()
|
||||
if err != nil { return err }
|
||||
log.Println("-=E incoming connection from", conn.RemoteAddr())
|
||||
server.Router.Accept(conn)
|
||||
}
|
||||
}
|
||||
|
||||
func (server *Server) Close () error {
|
||||
return server.underlying.Close()
|
||||
}
|
31
srvhttps/https.go
Normal file
@ -0,0 +1,31 @@
|
||||
package srvhttps
|
||||
|
||||
import "fmt"
|
||||
import "log"
|
||||
import "net/http"
|
||||
import "hnakra/config"
|
||||
|
||||
type Server struct {
|
||||
underlying *http.Server
|
||||
Config config.Config
|
||||
Handler http.Handler
|
||||
}
|
||||
|
||||
func (server *Server) ListenAndServe () error {
|
||||
server.underlying = &http.Server {
|
||||
Addr: fmt.Sprint(":", server.Config.HTTPSPort()),
|
||||
// ReadHeaderTimeout: timeoutReadHeader * time.Second,
|
||||
// ReadTimeout: timeoutRead * time.Second,
|
||||
// WriteTimeout: timeoutWrite * time.Second,
|
||||
// IdleTimeout: timeoutIdle * time.Second,
|
||||
TLSConfig: config.TLSConfigFor(server.Config),
|
||||
Handler: server.Handler,
|
||||
}
|
||||
|
||||
log.Println(".// https on", server.underlying.Addr)
|
||||
return server.underlying.ListenAndServeTLS("", "")
|
||||
}
|
||||
|
||||
func (server *Server) Close () error {
|
||||
return server.underlying.Close()
|
||||
}
|