Imported Debian version 1.2.2~svn3653

This commit is contained in:
cristian paul peñaranda rojas 2008-11-29 00:31:58 -05:00 committed by root
commit ce56f3183d
35 changed files with 12965 additions and 0 deletions

674
COPYING Normal file
View file

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

196
HACKING Normal file
View file

@ -0,0 +1,196 @@
file: HACKING
Last updated: 2008-04-10
--------
(C) 2008 - Richard Andrews <bbmaj7@yahoo.com.au>
This program and document 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 see <http://www.gnu.org/licenses/>
--------
This file describes the internals of n2n. Read this before starting to modify
the code. Because coding examples may be present in this document it is licensed
under the GPL rather than FDL.
SYMMETRIC NAT
-------------
Symmetric NAT is a form of firewall NAT in which an UDP packets are only passed
back to an inside host socket when the return packets originate from the outside
socket to which the initiating UDP packets were sent. This means that when an
inside host sends UDP to some outside socket; other hosts cannot piggyback on
this opening in the firewall to send data to the inside host.
When two inside hosts are both behind symmetric NAT, peer-to-peer packet
exchange is not possible via n2n. These hosts will require the supernode to
relay packets.
ARP CACHE
---------
n2n makes use of the host operating system's own ARP cache. Each edge node
allocates a random MAC address to itself. This MAC is constant for the life of
the edge process. ARP packets are passed around as broadcast ethernet packets
over n2n and these packets cause the native ARP cache to be updated.
Edge nodes send gratuitous ARP packets on startup. See GRATUITOUS ARP below.
REGISTRATION AND PEER-TO-PEER COMMUNICATION SETUP
-------------------------------------------------
A and B are edge nodes with public sockets Apub and Bpub; and private network
addresses A and B respectively. S is the supernode.
A sends {REGISTER,Amac} to S. S registers {Amac->Apub}.
B sends {REGISTER,Bmac} to S. S registers {Bmac->Bpub}.
Now ping from A to B.
A sends broadcast "arp who-has B" to S. S relays the packet to all known edge
nodes. B replies "B at Bmac" to supernode which forwards this to A. So now ping
A->B is known to be ping Amac(A)->Bmac(B). Note: gratuitous arp also requires
discussion.
In response to receiving the arp reply, Apub sends {REGISTER,Amac} to Bpub. If
Bpub receives the request it sends back {REGISTER_ACK,Amac} and also sends its
own {REGISTER,Bmac} request.
In response to receiving the "arp who-has", Bpub sends {REGISTER,Bmac} to Apub.
Now the OS has received the arp reply and sends ICMP to Bmac(B) via the tunnel
on A. A looks up Bmac in the peers list and encapsulates the packet to Bpub or
the supernode if the MAC is not found.
We assume that between two edge nodes, if Bpub receives a packet from Apub then
Apub can receive a packet from Bpub. This is the symmetric NAT case. Note: In
the symmetric NAT case, the public socket for a MAC address will be different
for direct contact when compared to information from the supernode.
When two edge nodes are both behind symmetric NAT they cannot establish direct
communication.
If A receives {REGISTER,Bmac} from B, A adds {Bmac->Bpub} to its peers list
knowing that Bmac is now reachable via that public socket. Similarly if B
receives {REGISTER,Amac} from A.
The supernode never forwards REGISTER messages because the public socket seen by
the supervisor for some edge (eg. A) may be different to the socket seen by
another edge due to the actions of symmetric NAT (alocating a new public socket
for the new outbound UDP "connection").
EDGE REGISTRATION DESIGN AMMENDMENTS (starting from 2008-04-10)
------------------------------------
* Send REGISTER on rx of PACKET or REGISTER only when dest_mac == device MAC
(do not send REGISTER on Rx of broadcast packets).
* After sending REGISTER add the new peer to pending_peers list; but
* Don't send REGISTER to a peer in pending_peers list
* Remove old entries from pending_peers at regular intervals
* On rx of REGISTER_ACK, move peer from pending_peers to known_peers for direct
comms and set last_seen=now
* On rx of any packet set last_seen=now in the known_peers entry (if it
exists); but do not add a new entry.
* If the public socket address for a known_peers entry changes, deleted it and
restart registration to the new peer.
* Peer sockets provided by the supernode are ignored unless no other entry
exists. Direct peer-to-peer sockets are always given more priority as the
supernode socket will not be usable for direct contact if the peer is behind
symmetric NAT.
The pending_peers list concept is to prevent massive registration traffic when
supernode relay is in force - this would occur if REGISTER was sent for every
incident packet sent via supernode. Periodic REGISTER attempts will still occur;
not for every received packet. In the case where the peer cannot be contacted
(eg. both peers behind symmetric NAT), then there will still be periodic
attempts. Suggest a pending timeout of about 60 sec.
A peer is only considered operational for peer-to-peer sending when a
REGISTER_ACK is returned. Once operational the peer is kept operational while
any direct packet communications are occurring. REGISTER is not required to
keep the path open through any firewalls; just some activity in one direction.
After an idle period; the peer should be deleted from the known_peers list. We
should not try to re-register when this time expires. If there is no data to
send then forget the peer. This helps scalability.
If a peer wants to be remembered it can send gratuitous ARP traffic which will
keep its entry in the known_peers list of any peers which already have the
entry.
peer = find_by_src_mac( hdr, known_peers ); /* return NULL or entry */
if ( peer )
{
peer_last_seen = time(NULL);
}
else
{
if ( ! is_broadcast( hdr ) ) /* ignore broadcasts */
{
if ( IS_REGISTER_ACK( hdr ) )
{
/* move from pending to known_peers */
set_peer_operational( hdr );
}
else
{
/* add to pending and send REGISTER - ignore if in pending. */
try_send_register( hdr )
}
}
}
(Notes):
* In testing it was noted that if a symmetric NAT firewall shuts down the UDP
association but the known_peers registration is still active, then the peer
becomes unreachable until the known_peers registration is deleted. Suggest two
ways to mitigate this problem:
(a) make the known_peers purge timeout a config paramter;
(b) send packets direct and via supernode if the registration is older than
eg. 60 sec.
GRATUITOUS ARP
--------------
In addition to the ARP who-has mechanism noted above, two edge nodes can become
aware of one another by gratuitous ARP. A gratuitous ARP packet is a broadcast
packet sent by a node for no other purpose than to announce its presence and
identify its MAC and IP address. Gratuitous ARP packets are to keep ARP caches
up to date so contacting the host will be faster after an long idle time.
MAN PAGES
---------
Look at a non-installed man page like this (linux):
nroff -man edge.8 | less
-------
April 2008 - Richard Andrews <bbmaj7@yahoo.com.au>

50
INSTALL Normal file
View file

@ -0,0 +1,50 @@
INSTALL
To build the programs:
$ make
To install the programs and man pages:
$ make install
or
$ make PREFIX=/usr/local install
RPM Package
-----------
These steps should work with RPM based Linux distributions since rpmbuild was
split from the rpm utility (c RedHat 9).
To build an RPM the easy way follow these steps.
1. Build SRPM
$ cd n2n
$ scripts/mk_SRPM.sh
Look for where the src.rpm file was put ( "Wrote:" ).
2. Build binary RPM from SRPM
$ rpm -i path/to/n2n-<ver>.src.rpm
$ rpmbuild -bb n2n.spec
All this can be done as non-root user if you have a ~/.rpmmacros file with this
line in it:
%_topdir /home/username/rpmtopdir
To build an RPM the hard way follow these steps.
$ cp -a n2ndir n2n-1.2
$ tar czf n2n-1.2.tar.gz n2n-1.2
$ mv n2n-1.2.tar.gz /usr/src/redhat/SOURCES
$ cp n2ndir/n2n.spec /usr/src/redhat/SPECS
$ rpmbuild -bb n2n.spec

64
Makefile Normal file
View file

@ -0,0 +1,64 @@
N2N_VERSION="1.2.2"
########
CC=gcc
CFLAGS+=-g -Wall -Wshadow -Wpointer-arith -Wmissing-declarations -Wnested-externs #-static
INSTALL=install
MKDIR=mkdir -p
INSTALL_PROG=$(INSTALL) -m755
INSTALL_DOC=$(INSTALL) -m644
# DESTDIR set in debian make system
PREFIX?=$(DESTDIR)/usr
BINDIR=$(PREFIX)/bin
SBINDIR=$(PREFIX)/sbin
MANDIR?=$(PREFIX)/share/man
MAN1DIR=$(MANDIR)/man1
MAN8DIR=$(MANDIR)/man8
N2N_LIB=n2n.a
N2N_OBJS=n2n.o minilzo.o twofish.o tuntap_freebsd.o tuntap_linux.o tuntap_osx.o version.o
LIBS=-lpthread
APPS=edge supernode
DOCS=edge.8.gz supernode.1.gz
all: $(APPS) #$(DOCS)
edge: edge.c $(N2N_LIB) n2n.h Makefile
$(CC) $(CFLAGS) edge.c $(N2N_LIB) $(LIBS) -o edge
supernode: supernode.c $(N2N_LIB) n2n.h Makefile
$(CC) $(CFLAGS) supernode.c $(N2N_LIB) $(LIBS) -o supernode
.c.o: n2n.h Makefile
$(CC) $(CFLAGS) -c $<
%.gz : %
gzip -c $< > $@
$(N2N_LIB): $(N2N_OBJS)
ar rcs $(N2N_LIB) $(N2N_OBJS)
# $(RANLIB) $@
version.c:
echo $(N2N_VERSION) | sed -e 's/.*/char * version = "&";/' > version.c
uname -p | sed -e 's/.*/char * osName = "&";/' >> version.c
date +"%D %r" | sed -e 's/.*/char * buildDate = "&";/' >> version.c
clean:
rm -rf $(N2N_OBJS) $(N2N_LIB) $(APPS) $(DOCS) *.dSYM *~ version.c
install: edge supernode edge.8.gz supernode.1.gz
echo "MANDIR=$(MANDIR)"
$(MKDIR) $(BINDIR) $(SBINDIR) $(MAN1DIR) $(MAN8DIR)
$(INSTALL_PROG) supernode $(BINDIR)/
$(INSTALL_PROG) edge $(SBINDIR)/
$(INSTALL_DOC) edge.8.gz $(MAN8DIR)/
$(INSTALL_DOC) supernode.1.gz $(MAN1DIR)/

95
README Normal file
View file

@ -0,0 +1,95 @@
Edge node
---------
You need to start an egde node on each host you want to connect with the *same*
community.
0. become root
1. create tun device
# tunctl -t tun0
3. enable the edge process
# ./edge -d n2n0 -c mynetwork -k encryptme -u 99 -g 99 -m 3C:A0:12:34:56:78 -a 1.2.3.4 -l a.b.c.d:xyw
or
# N2N_KEY=encryptme ./edge -d n2n0 -c mynetwork -u 99 -g 99 -m 3C:A0:12:34:56:78 -a 1.2.3.4 -l a.b.c.d:xyw
Once you have this worked out, you can add the "-f" option to make edge detach
and run as a daemon.
Note that -u, -g and -f options are not available for Windows.
Supernode
--------
You need to start the supernode once
1. ./supernode -l 1234 -v
Dropping Root Privileges and SUID-Root Executables (UNIX)
--------------------------------------------------
The edge node uses superuser privileges to create a TAP network interface
device. Once this is created root privileges are not required and can constitute
a security hazard if there is some way for an attacker to take control of an
edge process while it is running. Edge will drop to a non-privileged user if you
specify the -u <uid> and -g <gid> options. These are numeric IDs. Consult
/etc/passwd.
You may choose to install edge SUID-root to do this:
1. Become root
2. chown root:root edge
3. chmod +s edge
done
Any user can now run edge. You may not want this, but it may be convenient and
safe if your host has only one login user.
Running As a Daemon (UNIX)
-------------------
When given "-f" as a command line option, edge will call daemon(3) after
successful setup. This causes the process to fork a child which closes stdin,
stdout and stderr then sets itself as process group leader. When this is done,
the edge command returns immediately and you will only see the edge process in
the process listings, eg. from ps or top.
If the edge command returns 0 then the daemon started successfully. If it
returns non-zero then edge failed to start up for some reason. When edge starts
running as a daemon, all logging goes to syslog daemon.info facility.
IPv6 Support (added r3650)
------------
n2n supports the carriage of IPv6 packets within the n2n tunnel. N2n does not
yet use IPv6 for transport between edges and supernodes.
To make IPv6 carriage work you need to manually add IPv6 addresses to the TAP
interfaces at each end. There is currently no way to specify an IPv6 address on
the edge command line.
eg. under linux:
on hostA:
[hostA] # /sbin/ip -6 addr add fc00:abcd:1234::7/48 dev n2n0
on hostB:
[hostB] # /sbin/ip -6 addr add fc00:abcd:1234::6/48 dev n2n0
You may find it useful to make use of tunctl from the uml-utilities
package. Tunctl allow you to bring up a TAP interface and configure addressing
prior to starting edge. It also allows edge to be restarted without the
interface closing (which would normally affect routing tables).
Once the IPv6 addresses are configured and edge started, IPv6 neighbor discovery
packets flow (get broadcast) and IPv6 entities self arrange. Test your IPv6
setup with ping6 - the IPv6 ping command.
(C) 2007,2008 - Luca Deri <deri@ntop.org>, Richard Andrews <andrews@ntop.org>

34
debian/README.Debian vendored Normal file
View file

@ -0,0 +1,34 @@
n2n for Debian
--------------
This package depends on the kernel having the TUN/TAP driver configured in using
CONFIG_TUN=yes.
Quickstart
----------
* Decide where to place your supernode. Suppose you put it on host a.b.c.d
at port xyw.
* Decide what encryption password you want to use to secure your data.
Suppose you use the password encryptme
* Decide the network name you want to use. Suppose you call it mynetwork.
Note that you can use your supernode/edge nodes to handle multiple networks,
not just one.
* Decide what IP address you plan to use on your edge nodes. Suppose you
use IP address 10.1.2.0/24
* Start your applications:
o #supernode > supernode -l xyw
o #edge node1> edge -a 10.1.2.1 -c mynetwork -k encryptme -l a.b.c.d:xyw
o #edge node2> edge -a 10.1.2.2 -c mynetwork -k encryptme -l a.b.c.d:xyw
Now test your n2n network:
o #edge node1> ping 10.1.2.2
o #edge node2> ping 10.1.2.1
For more info check http://www.ntop.org/n2n
-- cristian paul peñaranda rojas <kristian.paul@gmail.com> Sat, 29 Nov 2008 00:31:58 -0500

6
debian/changelog vendored Normal file
View file

@ -0,0 +1,6 @@
n2n (1.2.2~svn3653) unstable; urgency=low
* Initial release (closes: Bug#507750)
-- cristian paul peñaranda rojas <kristian.paul@gmail.com> Sat, 29 Nov 2008 00:31:58 -0500

1
debian/compat vendored Normal file
View file

@ -0,0 +1 @@
5

14
debian/control vendored Normal file
View file

@ -0,0 +1,14 @@
Source: n2n
Section: net
Priority: extra
Maintainer: cristian paul peñaranda rojas <kristian.paul@gmail.com>
Build-Depends: debhelper (>= 5), libc6-dev (>= 2.0), quilt
Standards-Version: 3.8.0
Package: n2n
Architecture: any
Depends: ${shlibs:Depends}
Description: Peer-to-Peer VPN network daemon
n2n is an open source VPN application which utilizes
a Peer-to-peer architecture for network membership
and routing.

110
debian/copyright vendored Normal file
View file

@ -0,0 +1,110 @@
This package was debianized by cristian paul peñaranda rojas <kristian.paul@gmail.com> on
and is licensed under the GNU General Public License (GPL) version 3.
A copy of the GNU GPL version 2 is in `/usr/share/common-licenses/GPL-3'.
Sat, 29 Nov 2008 00:31:58 -0500.
The current Debian maintainer is cristian paul peñaranda rojas <kristian.paul@gmail.com>
It was downloaded from https://svn.ntop.org/svn/ntop/trunk/n2n
Upstream Author: Luca Deri deri@ntop.org
Copyright:
Copyright (C) 2008 Luca Deri
Copyright (C) 2008 Richard Andrews
License:
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 with
the Debian GNU/Linux distribution in file /usr/share/common-licenses/GPL;
if not, write to the Free Software Foundation, Inc., 51 Franklin St,
Fifth Floor, Boston, MA 02110-1301, USA.
On Debian systems, the complete text of the GNU General Public
License, version 3, can be found in /usr/share/common-licenses/GPL-3.
The Files:
twofish.c
twofish.h
Copyright (C) 1997-2000 The Cryptix Foundation Limited.
Copyright (C) 2000 Farm9.
Copyright (C) 2001 Frank Knobbe.
All rights reserved.
For Cryptix code:
Use, modification, copying and distribution of this software is subject
the terms and conditions of the Cryptix General Licence.
Cryptix General License
Copyright (c) 1995 -2005 The Cryptix Foundation Limited.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE CRYPTIX FOUNDATION LIMITED AND
CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE CRYPTIX FOUNDATION LIMITED OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The Files:
minilzo.c
minilzo.h
lzodefs.h
Copyright (C) 1996 - 2005 Markus Franz Xaver Johannes Oberhumer
These file are part of the LZO real-time data compression library.
All Rights Reserved.
The LZO library is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
The LZO library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the LZO library; see the file COPYING.
If not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

2
debian/dirs vendored Normal file
View file

@ -0,0 +1,2 @@
usr/bin
usr/sbin

1
debian/docs vendored Normal file
View file

@ -0,0 +1 @@
README

8
debian/patches/01-edge.8.diff vendored Normal file
View file

@ -0,0 +1,8 @@
--- a/edge.8.old 2008-12-02 20:33:54.000000000 -0500
+++ b/edge.8 2008-12-02 20:34:13.000000000 -0500
@@ -1,4 +1,4 @@
-.TH edge 1 "May 3, 2008" "revision 3472" "SUPERUSER COMMANDS"
+.TH edge 8 "May 3, 2008" "revision 3472" "SUPERUSER COMMANDS"
.SH NAME
edge \- n2n edge node daemon
.SH SYNOPSIS

1
debian/patches/series vendored Normal file
View file

@ -0,0 +1 @@
01-edge.8.diff

79
debian/rules vendored Executable file
View file

@ -0,0 +1,79 @@
#!/usr/bin/make -f
# -*- makefile -*-
# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1
include /usr/share/quilt/quilt.make
CFLAGS = -Wall -g
ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
CFLAGS += -O0
else
CFLAGS += -O2
endif
configure: configure-stamp
configure-stamp:
dh_testdir
# Add here commands to configure the package.
touch configure-stamp
build: patch build-stamp
build-stamp: configure-stamp
dh_testdir
# Add here commands to compile the package.
$(MAKE)
#docbook-to-man debian/n2n.sgml > n2n.1
touch $@
clean: unpatch
dh_testdir
dh_testroot
rm -f build-stamp configure-stamp
# Add here commands to clean up after the build process.
[ ! -f Makefile ] || $(MAKE) clean
dh_clean
install: build
dh_testdir
dh_testroot
dh_clean -k
dh_installdirs
# Add here commands to install the package into debian/n2n.
$(MAKE) DESTDIR=$(CURDIR)/debian/n2n install
# Build architecture-independent files here.
binary-indep: build install
# We have nothing to do by default.
# Build architecture-dependent files here.
binary-arch: build install
dh_testdir
dh_testroot
dh_installchangelogs
dh_installdocs
dh_installexamples
dh_installman supernode.1 edge.8
dh_link
dh_strip
dh_compress
dh_fixperms
dh_installdeb
dh_shlibdeps
dh_gencontrol
dh_md5sums
dh_builddeb
binary: binary-indep binary-arch
.PHONY: build clean binary-indep binary-arch binary install configure

77
edge.8 Normal file
View file

@ -0,0 +1,77 @@
.TH edge 1 "May 3, 2008" "revision 3472" "SUPERUSER COMMANDS"
.SH NAME
edge \- n2n edge node daemon
.SH SYNOPSIS
.B edge
[\-d <tun device>] \-a <tun IP address> \-c <community> \-k <encrypt key> \-l <supernode host:port>
[\-p <local port>] [\-u <UID>] [\-g <GID>] [-f] [\-m <MAC address>] [\-t] [\-r] [\-v]
.SH DESCRIPTION
N2N is a peer-to-peer VPN system. Edge is the edge node daemon for n2n which
creates a TAP interface to expose the n2n virtual LAN. On startup n2n creates
the TAP interface and configures it then registers with the supernode so it can
begin to find other nodes in the community.
.PP
.SH OPTIONS
.TP
\-d
sets the TAP device name as seen in ifconfig.
.TP
\-a
sets the n2n LAN IP address being claimed.
.TP
\-c
sets the n2n community name.
.TP
\-k
sets the twofish encryption key from ASCII text (see also N2N_KEY in ENVIRONMENT)
.TP
\-l
sets the n2n supernode IP address and port to register to
.TP
\-p
binds to the given UDP port
.TP
\-u
causes the edge process to drop to the given user ID when privileges are no longer required
.TP
\-g
causes the edge process to drop to the given group ID when privileges are no longer required
.TP
\-f
causes the edge process to fork and run as a daemon, closing stdin, stdout, stderr and becoming a process group leader
.TP
\-m
start the TAP interface with the given MAC address. This is highly recommended
as it means the same address will be used if edge stops and restarts. If this is
not done, the ARP caches of all peers will be wrong and packets will not flow to
this edge until the next ARP refresh.
.TP
\-t
use HTTP tunneling instead of the normal UDP mechanism (experimental)
.TP
\-r
all packet forwarding/routing through the n2n virtual LAN
.TP
\-v
use verbose logging
.SH ENVIRONMENT
.TP
.B N2N_KEY
set the encryption key so it is not visible on the command line
.SH EXAMPLES
.TP
.B edge \-d n2n0 \-c mynetwork \-k encryptme \-u 99 \-g 99 \-m DE:AD:BE:EF:01:23 \-a 192.168.254.7 \-l 123.121.120.119:7654
Start edge with TAP device n2n0 on community "mynetwork" with community
supernode at 123.121.120.119 UDP port 7654. Use "encryptme" as the shared
encryption key. Assign MAC address DE:AD:BE:EF:01:23 to the n2n interface and
drop to user=99 and group=99 after the TAP device is successfull configured.
.PP
Add the -f option to make it run as a daemon
.PP
.SH EXIT STATUS
edge is a daemon and any exit is an error
.SH AUTHOR
Luca Deri ( deri (at) ntop.org ), Richard Andrews ( andrews (at) ntop.org ), Don Bindner
.SH SEE ALSO
ifconfig(1) supernode(1) tunctl(1)

1407
edge.c Normal file

File diff suppressed because it is too large Load diff

417
lzoconf.h Normal file
View file

@ -0,0 +1,417 @@
/* lzoconf.h -- configuration for the LZO real-time data compression library
This file is part of the LZO real-time data compression library.
Copyright (C) 2008 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2007 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2006 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2005 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2004 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2003 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2002 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2001 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2000 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 1999 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 1998 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 1997 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 1996 Markus Franz Xaver Johannes Oberhumer
All Rights Reserved.
The LZO library is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
The LZO library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the LZO library; see the file COPYING.
If not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Markus F.X.J. Oberhumer
<markus@oberhumer.com>
http://www.oberhumer.com/opensource/lzo/
*/
#ifndef __LZOCONF_H_INCLUDED
#define __LZOCONF_H_INCLUDED
#define LZO_VERSION 0x2030
#define LZO_VERSION_STRING "2.03"
#define LZO_VERSION_DATE "Apr 30 2008"
/* internal Autoconf configuration file - only used when building LZO */
#if defined(LZO_HAVE_CONFIG_H)
# include <config.h>
#endif
#include <limits.h>
#include <stddef.h>
/***********************************************************************
// LZO requires a conforming <limits.h>
************************************************************************/
#if !defined(CHAR_BIT) || (CHAR_BIT != 8)
# error "invalid CHAR_BIT"
#endif
#if !defined(UCHAR_MAX) || !defined(UINT_MAX) || !defined(ULONG_MAX)
# error "check your compiler installation"
#endif
#if (USHRT_MAX < 1) || (UINT_MAX < 1) || (ULONG_MAX < 1)
# error "your limits.h macros are broken"
#endif
/* get OS and architecture defines */
#ifndef __LZODEFS_H_INCLUDED
#include "lzodefs.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
/***********************************************************************
// some core defines
************************************************************************/
#if !defined(LZO_UINT32_C)
# if (UINT_MAX < LZO_0xffffffffL)
# define LZO_UINT32_C(c) c ## UL
# else
# define LZO_UINT32_C(c) ((c) + 0U)
# endif
#endif
/* memory checkers */
#if !defined(__LZO_CHECKER)
# if defined(__BOUNDS_CHECKING_ON)
# define __LZO_CHECKER 1
# elif defined(__CHECKER__)
# define __LZO_CHECKER 1
# elif defined(__INSURE__)
# define __LZO_CHECKER 1
# elif defined(__PURIFY__)
# define __LZO_CHECKER 1
# endif
#endif
/***********************************************************************
// integral and pointer types
************************************************************************/
/* lzo_uint should match size_t */
#if !defined(LZO_UINT_MAX)
# if defined(LZO_ABI_LLP64) /* WIN64 */
# if defined(LZO_OS_WIN64)
typedef unsigned __int64 lzo_uint;
typedef __int64 lzo_int;
# else
typedef unsigned long long lzo_uint;
typedef long long lzo_int;
# endif
# define LZO_UINT_MAX 0xffffffffffffffffull
# define LZO_INT_MAX 9223372036854775807LL
# define LZO_INT_MIN (-1LL - LZO_INT_MAX)
# elif defined(LZO_ABI_IP32L64) /* MIPS R5900 */
typedef unsigned int lzo_uint;
typedef int lzo_int;
# define LZO_UINT_MAX UINT_MAX
# define LZO_INT_MAX INT_MAX
# define LZO_INT_MIN INT_MIN
# elif (ULONG_MAX >= LZO_0xffffffffL)
typedef unsigned long lzo_uint;
typedef long lzo_int;
# define LZO_UINT_MAX ULONG_MAX
# define LZO_INT_MAX LONG_MAX
# define LZO_INT_MIN LONG_MIN
# else
# error "lzo_uint"
# endif
#endif
/* Integral types with 32 bits or more. */
#if !defined(LZO_UINT32_MAX)
# if (UINT_MAX >= LZO_0xffffffffL)
typedef unsigned int lzo_uint32;
typedef int lzo_int32;
# define LZO_UINT32_MAX UINT_MAX
# define LZO_INT32_MAX INT_MAX
# define LZO_INT32_MIN INT_MIN
# elif (ULONG_MAX >= LZO_0xffffffffL)
typedef unsigned long lzo_uint32;
typedef long lzo_int32;
# define LZO_UINT32_MAX ULONG_MAX
# define LZO_INT32_MAX LONG_MAX
# define LZO_INT32_MIN LONG_MIN
# else
# error "lzo_uint32"
# endif
#endif
/* The larger type of lzo_uint and lzo_uint32. */
#if (LZO_UINT_MAX >= LZO_UINT32_MAX)
# define lzo_xint lzo_uint
#else
# define lzo_xint lzo_uint32
#endif
/* Memory model that allows to access memory at offsets of lzo_uint. */
#if !defined(__LZO_MMODEL)
# if (LZO_UINT_MAX <= UINT_MAX)
# define __LZO_MMODEL
# elif defined(LZO_HAVE_MM_HUGE_PTR)
# define __LZO_MMODEL_HUGE 1
# define __LZO_MMODEL __huge
# else
# define __LZO_MMODEL
# endif
#endif
/* no typedef here because of const-pointer issues */
#define lzo_bytep unsigned char __LZO_MMODEL *
#define lzo_charp char __LZO_MMODEL *
#define lzo_voidp void __LZO_MMODEL *
#define lzo_shortp short __LZO_MMODEL *
#define lzo_ushortp unsigned short __LZO_MMODEL *
#define lzo_uint32p lzo_uint32 __LZO_MMODEL *
#define lzo_int32p lzo_int32 __LZO_MMODEL *
#define lzo_uintp lzo_uint __LZO_MMODEL *
#define lzo_intp lzo_int __LZO_MMODEL *
#define lzo_xintp lzo_xint __LZO_MMODEL *
#define lzo_voidpp lzo_voidp __LZO_MMODEL *
#define lzo_bytepp lzo_bytep __LZO_MMODEL *
/* deprecated - use `lzo_bytep' instead of `lzo_byte *' */
#define lzo_byte unsigned char __LZO_MMODEL
typedef int lzo_bool;
/***********************************************************************
// function types
************************************************************************/
/* name mangling */
#if !defined(__LZO_EXTERN_C)
# ifdef __cplusplus
# define __LZO_EXTERN_C extern "C"
# else
# define __LZO_EXTERN_C extern
# endif
#endif
/* calling convention */
#if !defined(__LZO_CDECL)
# define __LZO_CDECL __lzo_cdecl
#endif
/* DLL export information */
#if !defined(__LZO_EXPORT1)
# define __LZO_EXPORT1
#endif
#if !defined(__LZO_EXPORT2)
# define __LZO_EXPORT2
#endif
/* __cdecl calling convention for public C and assembly functions */
#if !defined(LZO_PUBLIC)
# define LZO_PUBLIC(_rettype) __LZO_EXPORT1 _rettype __LZO_EXPORT2 __LZO_CDECL
#endif
#if !defined(LZO_EXTERN)
# define LZO_EXTERN(_rettype) __LZO_EXTERN_C LZO_PUBLIC(_rettype)
#endif
#if !defined(LZO_PRIVATE)
# define LZO_PRIVATE(_rettype) static _rettype __LZO_CDECL
#endif
/* function types */
typedef int
(__LZO_CDECL *lzo_compress_t) ( const lzo_bytep src, lzo_uint src_len,
lzo_bytep dst, lzo_uintp dst_len,
lzo_voidp wrkmem );
typedef int
(__LZO_CDECL *lzo_decompress_t) ( const lzo_bytep src, lzo_uint src_len,
lzo_bytep dst, lzo_uintp dst_len,
lzo_voidp wrkmem );
typedef int
(__LZO_CDECL *lzo_optimize_t) ( lzo_bytep src, lzo_uint src_len,
lzo_bytep dst, lzo_uintp dst_len,
lzo_voidp wrkmem );
typedef int
(__LZO_CDECL *lzo_compress_dict_t)(const lzo_bytep src, lzo_uint src_len,
lzo_bytep dst, lzo_uintp dst_len,
lzo_voidp wrkmem,
const lzo_bytep dict, lzo_uint dict_len );
typedef int
(__LZO_CDECL *lzo_decompress_dict_t)(const lzo_bytep src, lzo_uint src_len,
lzo_bytep dst, lzo_uintp dst_len,
lzo_voidp wrkmem,
const lzo_bytep dict, lzo_uint dict_len );
/* Callback interface. Currently only the progress indicator ("nprogress")
* is used, but this may change in a future release. */
struct lzo_callback_t;
typedef struct lzo_callback_t lzo_callback_t;
#define lzo_callback_p lzo_callback_t __LZO_MMODEL *
/* malloc & free function types */
typedef lzo_voidp (__LZO_CDECL *lzo_alloc_func_t)
(lzo_callback_p self, lzo_uint items, lzo_uint size);
typedef void (__LZO_CDECL *lzo_free_func_t)
(lzo_callback_p self, lzo_voidp ptr);
/* a progress indicator callback function */
typedef void (__LZO_CDECL *lzo_progress_func_t)
(lzo_callback_p, lzo_uint, lzo_uint, int);
struct lzo_callback_t
{
/* custom allocators (set to 0 to disable) */
lzo_alloc_func_t nalloc; /* [not used right now] */
lzo_free_func_t nfree; /* [not used right now] */
/* a progress indicator callback function (set to 0 to disable) */
lzo_progress_func_t nprogress;
/* NOTE: the first parameter "self" of the nalloc/nfree/nprogress
* callbacks points back to this struct, so you are free to store
* some extra info in the following variables. */
lzo_voidp user1;
lzo_xint user2;
lzo_xint user3;
};
/***********************************************************************
// error codes and prototypes
************************************************************************/
/* Error codes for the compression/decompression functions. Negative
* values are errors, positive values will be used for special but
* normal events.
*/
#define LZO_E_OK 0
#define LZO_E_ERROR (-1)
#define LZO_E_OUT_OF_MEMORY (-2) /* [not used right now] */
#define LZO_E_NOT_COMPRESSIBLE (-3) /* [not used right now] */
#define LZO_E_INPUT_OVERRUN (-4)
#define LZO_E_OUTPUT_OVERRUN (-5)
#define LZO_E_LOOKBEHIND_OVERRUN (-6)
#define LZO_E_EOF_NOT_FOUND (-7)
#define LZO_E_INPUT_NOT_CONSUMED (-8)
#define LZO_E_NOT_YET_IMPLEMENTED (-9) /* [not used right now] */
#ifndef lzo_sizeof_dict_t
# define lzo_sizeof_dict_t ((unsigned)sizeof(lzo_bytep))
#endif
/* lzo_init() should be the first function you call.
* Check the return code !
*
* lzo_init() is a macro to allow checking that the library and the
* compiler's view of various types are consistent.
*/
#define lzo_init() __lzo_init_v2(LZO_VERSION,(int)sizeof(short),(int)sizeof(int),\
(int)sizeof(long),(int)sizeof(lzo_uint32),(int)sizeof(lzo_uint),\
(int)lzo_sizeof_dict_t,(int)sizeof(char *),(int)sizeof(lzo_voidp),\
(int)sizeof(lzo_callback_t))
LZO_EXTERN(int) __lzo_init_v2(unsigned,int,int,int,int,int,int,int,int,int);
/* version functions (useful for shared libraries) */
LZO_EXTERN(unsigned) lzo_version(void);
LZO_EXTERN(const char *) lzo_version_string(void);
LZO_EXTERN(const char *) lzo_version_date(void);
LZO_EXTERN(const lzo_charp) _lzo_version_string(void);
LZO_EXTERN(const lzo_charp) _lzo_version_date(void);
/* string functions */
LZO_EXTERN(int)
lzo_memcmp(const lzo_voidp _s1, const lzo_voidp _s2, lzo_uint _len);
LZO_EXTERN(lzo_voidp)
lzo_memcpy(lzo_voidp _dest, const lzo_voidp _src, lzo_uint _len);
LZO_EXTERN(lzo_voidp)
lzo_memmove(lzo_voidp _dest, const lzo_voidp _src, lzo_uint _len);
LZO_EXTERN(lzo_voidp)
lzo_memset(lzo_voidp _s, int _c, lzo_uint _len);
/* checksum functions */
LZO_EXTERN(lzo_uint32)
lzo_adler32(lzo_uint32 _adler, const lzo_bytep _buf, lzo_uint _len);
LZO_EXTERN(lzo_uint32)
lzo_crc32(lzo_uint32 _c, const lzo_bytep _buf, lzo_uint _len);
LZO_EXTERN(const lzo_uint32p)
lzo_get_crc32_table(void);
/* misc. */
LZO_EXTERN(int) _lzo_config_check(void);
typedef union { lzo_bytep p; lzo_uint u; } __lzo_pu_u;
typedef union { lzo_bytep p; lzo_uint32 u32; } __lzo_pu32_u;
typedef union { void *vp; lzo_bytep bp; lzo_uint32 u32; long l; } lzo_align_t;
/* align a char pointer on a boundary that is a multiple of `size' */
LZO_EXTERN(unsigned) __lzo_align_gap(const lzo_voidp _ptr, lzo_uint _size);
#define LZO_PTR_ALIGN_UP(_ptr,_size) \
((_ptr) + (lzo_uint) __lzo_align_gap((const lzo_voidp)(_ptr),(lzo_uint)(_size)))
/***********************************************************************
// deprecated macros - only for backward compatibility with LZO v1.xx
************************************************************************/
#if defined(LZO_CFG_COMPAT)
#define __LZOCONF_H 1
#if defined(LZO_ARCH_I086)
# define __LZO_i386 1
#elif defined(LZO_ARCH_I386)
# define __LZO_i386 1
#endif
#if defined(LZO_OS_DOS16)
# define __LZO_DOS 1
# define __LZO_DOS16 1
#elif defined(LZO_OS_DOS32)
# define __LZO_DOS 1
#elif defined(LZO_OS_WIN16)
# define __LZO_WIN 1
# define __LZO_WIN16 1
#elif defined(LZO_OS_WIN32)
# define __LZO_WIN 1
#endif
#define __LZO_CMODEL
#define __LZO_DMODEL
#define __LZO_ENTRY __LZO_CDECL
#define LZO_EXTERN_CDECL LZO_EXTERN
#define LZO_ALIGN LZO_PTR_ALIGN_UP
#define lzo_compress_asm_t lzo_compress_t
#define lzo_decompress_asm_t lzo_decompress_t
#endif /* LZO_CFG_COMPAT */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* already included */
/* vim:set ts=4 et: */

1807
lzodefs.h Normal file

File diff suppressed because it is too large Load diff

4112
minilzo.c Normal file

File diff suppressed because it is too large Load diff

106
minilzo.h Normal file
View file

@ -0,0 +1,106 @@
/* minilzo.h -- mini subset of the LZO real-time data compression library
This file is part of the LZO real-time data compression library.
Copyright (C) 2008 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2007 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2006 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2005 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2004 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2003 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2002 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2001 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2000 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 1999 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 1998 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 1997 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 1996 Markus Franz Xaver Johannes Oberhumer
All Rights Reserved.
The LZO library is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
The LZO library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the LZO library; see the file COPYING.
If not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Markus F.X.J. Oberhumer
<markus@oberhumer.com>
http://www.oberhumer.com/opensource/lzo/
*/
/*
* NOTE:
* the full LZO package can be found at
* http://www.oberhumer.com/opensource/lzo/
*/
#ifndef __MINILZO_H
#define __MINILZO_H
#define MINILZO_VERSION 0x2030
#ifdef __LZOCONF_H
# error "you cannot use both LZO and miniLZO"
#endif
#undef LZO_HAVE_CONFIG_H
#include "lzoconf.h"
#if !defined(LZO_VERSION) || (LZO_VERSION != MINILZO_VERSION)
# error "version mismatch in header files"
#endif
#ifdef __cplusplus
extern "C" {
#endif
/***********************************************************************
//
************************************************************************/
/* Memory required for the wrkmem parameter.
* When the required size is 0, you can also pass a NULL pointer.
*/
#define LZO1X_MEM_COMPRESS LZO1X_1_MEM_COMPRESS
#define LZO1X_1_MEM_COMPRESS ((lzo_uint32) (16384L * lzo_sizeof_dict_t))
#define LZO1X_MEM_DECOMPRESS (0)
/* compression */
LZO_EXTERN(int)
lzo1x_1_compress ( const lzo_bytep src, lzo_uint src_len,
lzo_bytep dst, lzo_uintp dst_len,
lzo_voidp wrkmem );
/* decompression */
LZO_EXTERN(int)
lzo1x_decompress ( const lzo_bytep src, lzo_uint src_len,
lzo_bytep dst, lzo_uintp dst_len,
lzo_voidp wrkmem /* NOT USED */ );
/* safe decompression with overrun testing */
LZO_EXTERN(int)
lzo1x_decompress_safe ( const lzo_bytep src, lzo_uint src_len,
lzo_bytep dst, lzo_uintp dst_len,
lzo_voidp wrkmem /* NOT USED */ );
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* already included */

892
n2n.c Normal file
View file

@ -0,0 +1,892 @@
/*
* (C) 2007-08 - Luca Deri <deri@ntop.org>
*
* 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 <http://www.gnu.org/licenses/>
*
* Code contributions courtesy of:
* Richard Andrews <bbmaj7@yahoo.com.au>
* Massimo Torquati <torquati@ntop.org>
*
*/
#include "n2n.h"
#include "minilzo.h"
#include <assert.h>
#if defined(DEBUG)
# define PURGE_REGISTRATION_FREQUENCY 60
# define REGISTRATION_TIMEOUT 120
#else /* #if defined(DEBUG) */
# define PURGE_REGISTRATION_FREQUENCY 60
# define REGISTRATION_TIMEOUT (60*5)
#endif /* #if defined(DEBUG) */
char broadcast_addr[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
char multicast_addr[6] = { 0x01, 0x00, 0x05, 0x00, 0x00, 0x00 }; /* First 3 bytes are meaningful */
/* ************************************** */
static void print_header( const char * msg, const struct n2n_packet_header * hdr )
{
ipstr_t buf;
ipstr_t buf2;
traceEvent(TRACE_INFO, "%s hdr: public_ip=(%d)%s:%d, private_ip=(%d)%s:%d", msg,
hdr->public_ip.family,
intoa(ntohl(hdr->public_ip.addr_type.v4_addr), buf, sizeof(buf)),
ntohs(hdr->public_ip.port),
hdr->private_ip.family,
intoa(ntohl(hdr->private_ip.addr_type.v4_addr), buf2, sizeof(buf2)),
ntohs(hdr->private_ip.port)
);
}
/* *********************************************** */
extern void sockaddr_in2peer_addr(struct sockaddr_in *in, struct peer_addr *out) {
out->family = (u_int8_t)in->sin_family;
out->port = in->sin_port;
out->addr_type.v4_addr = in->sin_addr.s_addr;
}
/* *********************************************** */
extern void peer_addr2sockaddr_in(const struct peer_addr *in, struct sockaddr_in *out) {
out->sin_family = in->family;
out->sin_port = in->port;
out->sin_addr.s_addr = in->addr_type.v4_addr;
}
/* ************************************** */
static
int marshall_peer_addr( u_int8_t * buf, const struct peer_addr * s )
{
memcpy( buf, s, sizeof(struct peer_addr));
buf += sizeof(struct peer_addr);
return sizeof(struct peer_addr); /* bytes written */
}
/* ************************************** */
static
int marshall_uint32( u_int8_t * buf, u_int32_t val )
{
u_int32_t * nu32 = (u_int32_t *)buf;
*nu32 = htonl(val);
return 4;
}
/* ************************************** */
int marshall_n2n_packet_header( u_int8_t * buf, const struct n2n_packet_header * hdr )
{
u_int8_t * bufStart = buf;
print_header( "Marshalling ", hdr );
*buf = hdr->version;
++buf;
*buf = hdr->msg_type;
++buf;
*buf = hdr->ttl;
++buf;
*buf = hdr->sent_by_supernode;
++buf;
memcpy( buf, hdr->community_name, COMMUNITY_LEN );
buf += COMMUNITY_LEN;
memcpy( buf, hdr->src_mac, 6 );
buf += 6;
memcpy( buf, hdr->dst_mac, 6 );
buf += 6;
buf += marshall_peer_addr( buf, &(hdr->public_ip) );
buf += marshall_peer_addr( buf, &(hdr->private_ip) );
*buf = (hdr->pkt_type & 0xff);
++buf;
buf += marshall_uint32( buf, hdr->sequence_id );
buf += marshall_uint32( buf, hdr->crc );
return (buf - bufStart);
}
/* ************************************** */
static
int unmarshall_peer_addr( struct peer_addr * s,
const u_int8_t * buf )
{
memcpy(s, buf, sizeof(struct peer_addr));
buf += sizeof(struct peer_addr);
return (sizeof(struct peer_addr)); /* bytes written */
}
/* ************************************** */
static
int unmarshall_uint32( u_int32_t * val, const u_int8_t * buf )
{
u_int32_t * nu32 = (u_int32_t *)buf;
*val = ntohl(*nu32);
return 4;
}
/* ************************************** */
int unmarshall_n2n_packet_header( struct n2n_packet_header * hdr, const u_int8_t * buf )
{
const u_int8_t * bufStart = buf;
hdr->version = *buf;
++buf;
hdr->msg_type = *buf;
++buf;
hdr->ttl = *buf;
++buf;
hdr->sent_by_supernode = *buf;
++buf;
memcpy( hdr->community_name, buf, COMMUNITY_LEN );
buf += COMMUNITY_LEN;
memcpy( hdr->src_mac, buf, 6 );
buf += 6;
memcpy( hdr->dst_mac, buf, 6 );
buf += 6;
buf += unmarshall_peer_addr( &(hdr->public_ip), buf );
buf += unmarshall_peer_addr( &(hdr->private_ip), buf );
hdr->pkt_type = (*buf & 0xff); /* Make sure only 8 bits are copied. */
++buf;
buf += unmarshall_uint32( &(hdr->sequence_id), buf );
buf += unmarshall_uint32( &(hdr->crc), buf );
print_header( "Unmarshalled ", hdr );
return (buf - bufStart);
}
/* ************************************** */
SOCKET open_socket(int local_port, int udp_sock, int server_mode) {
SOCKET sock_fd;
struct sockaddr_in local_address;
int sockopt = 1;
if((sock_fd = socket(PF_INET, udp_sock ? SOCK_DGRAM : SOCK_STREAM, 0)) < 0) {
traceEvent(TRACE_ERROR, "Unable to create socket [%s][%d]\n",
strerror(errno), sock_fd);
return(-1);
}
#ifndef WIN32
/* fcntl(sock_fd, F_SETFL, O_NONBLOCK); */
#endif
setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, (char *)&sockopt, sizeof(sockopt));
memset(&local_address, 0, sizeof(local_address));
local_address.sin_family = AF_INET;
local_address.sin_port = htons(local_port);
local_address.sin_addr.s_addr = INADDR_ANY;
if(bind(sock_fd, (struct sockaddr*) &local_address, sizeof(local_address)) == -1) {
traceEvent(TRACE_ERROR, "Bind error [%s]\n", strerror(errno));
return(-1);
}
if((!udp_sock) && server_mode) {
if(listen(sock_fd, 255) == -1) {
traceEvent(TRACE_ERROR, "Listen error [%s]\n", strerror(errno));
return(-1);
}
}
return(sock_fd);
}
/* ************************************** */
int connect_socket(int sock_fd, struct peer_addr* _dest) {
char *http_header;
int len, rc;
struct sockaddr_in dest;
peer_addr2sockaddr_in(_dest, &dest);
/* FIX: add IPv6 support */
rc = connect(sock_fd, (struct sockaddr*)&dest, sizeof(struct sockaddr_in));
if(rc == -1) {
traceEvent(TRACE_WARNING, "connect() error [%s]\n", strerror(errno));
return(-1);
}
/* Send dummy http header */
http_header = "GET / HTTP/1.0\r\n\r\n";
len = strlen(http_header);
rc = send(sock_fd, http_header, len, 0);
return((rc == len) ? 0 : -1);
}
/* *********************************************** */
void send_packet(n2n_sock_info_t * sinfo,
char *packet, size_t *packet_len,
const struct peer_addr *remote_peer, u_int8_t compress_data) {
int data_sent_len;
data_sent_len = unreliable_sendto(sinfo,
packet, packet_len, remote_peer, compress_data);
if(data_sent_len != *packet_len)
traceEvent(TRACE_WARNING,
"sendto() [sent=%d][attempted_to_send=%d] [%s]\n",
data_sent_len, *packet_len, strerror(errno));
}
/* *********************************************** */
int traceLevel = 2 /* NORMAL */;
int useSyslog = 0, syslog_opened = 0;
#define N2N_TRACE_DATESIZE 32
void traceEvent(int eventTraceLevel, char* file, int line, char * format, ...) {
va_list va_ap;
if(eventTraceLevel <= traceLevel) {
char buf[2048];
char out_buf[640];
char theDate[N2N_TRACE_DATESIZE];
char *extra_msg = "";
time_t theTime = time(NULL);
/* We have two paths - one if we're logging, one if we aren't
* Note that the no-log case is those systems which don't support it (WIN32),
* those without the headers !defined(USE_SYSLOG)
* those where it's parametrically off...
*/
memset(buf, 0, sizeof(buf));
strftime(theDate, N2N_TRACE_DATESIZE, "%d/%b/%Y %H:%M:%S", localtime(&theTime));
va_start (va_ap, format);
vsnprintf(buf, sizeof(buf)-1, format, va_ap);
va_end(va_ap);
if(eventTraceLevel == 0 /* TRACE_ERROR */)
extra_msg = "ERROR: ";
else if(eventTraceLevel == 1 /* TRACE_WARNING */)
extra_msg = "WARNING: ";
while(buf[strlen(buf)-1] == '\n') buf[strlen(buf)-1] = '\0';
#ifndef WIN32
if(useSyslog) {
if(!syslog_opened) {
openlog("n2n", LOG_PID, LOG_DAEMON);
syslog_opened = 1;
}
snprintf(out_buf, sizeof(out_buf), "%s%s", extra_msg, buf);
syslog(LOG_INFO, out_buf);
} else {
snprintf(out_buf, sizeof(out_buf), "%s [%11s:%4d] %s%s", theDate, file, line, extra_msg, buf);
printf("%s\n", out_buf);
fflush(stdout);
}
#else
/* this is the WIN32 code */
snprintf(out_buf, sizeof(out_buf), "%s [%11s:%4d] %s%s", theDate, file, line, extra_msg, buf);
printf("%s\n", out_buf);
fflush(stdout);
#endif
}
}
/* *********************************************** */
/* addr should be in network order. Things are so much simpler that way. */
char* intoa(u_int32_t /* host order */ addr, char* buf, u_short buf_len) {
char *cp, *retStr;
u_int byte;
int n;
cp = &buf[buf_len];
*--cp = '\0';
n = 4;
do {
byte = addr & 0xff;
*--cp = byte % 10 + '0';
byte /= 10;
if (byte > 0) {
*--cp = byte % 10 + '0';
byte /= 10;
if (byte > 0)
*--cp = byte + '0';
}
*--cp = '.';
addr >>= 8;
} while (--n > 0);
/* Convert the string to lowercase */
retStr = (char*)(cp+1);
return(retStr);
}
/* *********************************************** */
char* macaddr_str(const char *mac, char *buf, int buf_len) {
snprintf(buf, buf_len, "%02X:%02X:%02X:%02X:%02X:%02X",
mac[0] & 0xFF, mac[1] & 0xFF, mac[2] & 0xFF,
mac[3] & 0xFF, mac[4] & 0xFF, mac[5] & 0xFF);
return(buf);
}
/* *********************************************** */
void fill_standard_header_fields(n2n_sock_info_t * sinfo,
struct n2n_packet_header *hdr, char *src_mac) {
socklen_t len = sizeof(hdr->private_ip);
memset(hdr, 0, N2N_PKT_HDR_SIZE);
hdr->version = N2N_VERSION;
hdr->crc = 0; // FIX
if(src_mac != NULL) memcpy(hdr->src_mac, src_mac, 6);
getsockname(sinfo->sock, (struct sockaddr*)&hdr->private_ip, &len);
hdr->public_ip.family = AF_INET;
}
/* *********************************************** */
void send_ack(n2n_sock_info_t * sinfo,
u_int16_t last_rcvd_seq_id,
struct n2n_packet_header *header,
struct peer_addr *remote_peer,
char *src_mac) {
/* marshalling double-checked. */
struct n2n_packet_header hdr;
u_int8_t pkt[ N2N_PKT_HDR_SIZE ];
size_t len = sizeof(hdr);
size_t len2;
fill_standard_header_fields(sinfo, &hdr, src_mac);
hdr.msg_type = MSG_TYPE_ACK_RESPONSE;
hdr.sequence_id = last_rcvd_seq_id;
memcpy(hdr.community_name, header->community_name, COMMUNITY_LEN);
len2=marshall_n2n_packet_header( pkt, &hdr );
assert( len2 == len );
send_packet(sinfo, (char*)pkt, &len, remote_peer, 1);
}
/* *********************************************** */
u_int8_t is_multi_broadcast(char *dest_mac) {
return(((!memcmp(broadcast_addr, dest_mac, 6))
|| (!memcmp(multicast_addr, dest_mac, 3))) ? 1 : 0);
}
/* *********************************************** */
/* http://www.faqs.org/rfcs/rfc908.html */
u_int receive_data(n2n_sock_info_t * sinfo,
char *packet, size_t packet_len,
struct peer_addr *from, u_int8_t *discarded_pkt,
char *tun_mac_addr, u_int8_t decompress_data,
struct n2n_packet_header *hdr) {
socklen_t fromlen = sizeof(struct sockaddr_in);
int len;
char *payload, *pkt_type;
macstr_t src_mac_buf;
macstr_t dst_mac_buf;
ipstr_t ip_buf;
ipstr_t from_ip_buf;
if(sinfo->is_udp_socket) {
struct sockaddr_in _from;
len = recvfrom(sinfo->sock, packet, packet_len, 0, (struct sockaddr*)&_from, &fromlen);
sockaddr_in2peer_addr(&_from, from);
} else {
len = recv(sinfo->sock, packet, 4, 0);
if(len == 4) {
packet[4] = '\0';
len = atoi(packet);
len = recv(sinfo->sock, packet, len, 0);
} else {
traceEvent(TRACE_WARNING, "Unable to receive n2n packet length");
return(-1);
}
}
unmarshall_n2n_packet_header(hdr, (u_int8_t *)packet);
payload = &packet[N2N_PKT_HDR_SIZE];
if(len < 0) {
#ifdef WIN32
if(WSAGetLastError() != WSAECONNRESET /* http://support.microsoft.com/kb/263823 */ ) {
traceEvent(TRACE_WARNING, "recvfrom returned %d [err=%d]", len, WSAGetLastError());
}
#endif
return(0);
} else if(len > MIN_COMPRESSED_PKT_LEN) {
char decompressed[2048];
int rc;
lzo_uint decompressed_len;
if(decompress_data) {
rc = lzo1x_decompress((u_char*)&packet[N2N_PKT_HDR_SIZE],
len-N2N_PKT_HDR_SIZE,
(u_char*)decompressed, &decompressed_len, NULL);
if(rc == LZO_E_OK)
traceEvent(TRACE_INFO, "%u bytes decompressed into %u", len, decompressed_len);
if(packet_len > decompressed_len) {
memcpy(&packet[N2N_PKT_HDR_SIZE], decompressed, decompressed_len);
len = decompressed_len+N2N_PKT_HDR_SIZE;
} else {
traceEvent(TRACE_WARNING, "Uncompressed packet is too large [decompressed_len=%d]",
decompressed_len);
return(0);
}
}
(*discarded_pkt) = 0;
if(!hdr->sent_by_supernode) {
memcpy( &packet[offsetof(struct n2n_packet_header, public_ip)], from, sizeof(struct sockaddr_in) );
}
switch(hdr->pkt_type) {
case packet_unreliable_data:
pkt_type = "unreliable data";
break;
case packet_reliable_data:
pkt_type = "reliable data";
break;
case packet_ping:
pkt_type = "ping";
break;
case packet_pong:
pkt_type = "pong";
break;
default:
pkt_type = "???";
}
traceEvent(TRACE_INFO, "+++ Received %s packet [rcvd_from=%s:%d][msg_type=%s][seq_id=%d]",
pkt_type,
intoa(ntohl(from->addr_type.v4_addr), from_ip_buf, sizeof(from_ip_buf)),
ntohs(from->port), msg_type2str(hdr->msg_type),
hdr->sequence_id);
traceEvent(TRACE_INFO, " [src_mac=%s][dst_mac=%s][original_sender=%s:%d]",
macaddr_str(hdr->src_mac, src_mac_buf, sizeof(src_mac_buf)),
macaddr_str(hdr->dst_mac, dst_mac_buf, sizeof(dst_mac_buf)),
intoa(ntohl(hdr->public_ip.addr_type.v4_addr), ip_buf, sizeof(ip_buf)),
ntohs(hdr->public_ip.port));
#ifdef HANDLE_RETRANSMISSION
if((hdr->pkt_type == packet_reliable_data)
&& (hdr->msg_type == MSG_TYPE_PACKET)) {
(*discarded_pkt) = handle_ack(sock_fd, is_udp_socket, hdr,
&payload[6], payload, from, tun_mac_addr);
} else
(*discarded_pkt) = 0;
#endif
} else
traceEvent(TRACE_WARNING, "Receive error [%s] or pkt too short [len=%d]\n",
strerror(errno), len);
return(len);
}
/* *********************************************** */
#if 0
static u_int32_t queue_packet(struct send_hash_entry *scan,
char *packet,
u_int16_t packet_len) {
struct packet_list *pkt = (struct packet_list*)malloc(sizeof(struct packet_list));
if(pkt == NULL) {
traceEvent(TRACE_ERROR, "Not enough memory!");
return(0);
}
if((pkt->packet = (char*)malloc(packet_len)) == NULL) {
traceEvent(TRACE_ERROR, "Not enough memory!");
return(0);
}
memcpy(pkt->packet, packet, packet_len);
pkt->packet_len = packet_len;
pkt->seq_id = scan->last_seq_id;
pkt->next = scan->unacked_packet_list;
scan->unacked_packet_list = pkt;
scan->num_unacked_pkts++;
return(pkt->seq_id);
}
#endif
/* *********************************************** */
/* Work-memory needed for compression. Allocate memory in units
* of `lzo_align_t' (instead of `char') to make sure it is properly aligned.
*/
#define HEAP_ALLOC(var,size) \
lzo_align_t __LZO_MMODEL var [ ((size) + (sizeof(lzo_align_t) - 1)) / sizeof(lzo_align_t) ]
static HEAP_ALLOC(wrkmem,LZO1X_1_MEM_COMPRESS);
/* ******************************************************* */
u_int send_data(n2n_sock_info_t * sinfo,
char *packet, size_t *packet_len,
const struct peer_addr *to, u_int8_t compress_data) {
char compressed[1600];
int rc;
lzo_uint compressed_len;
struct sockaddr_in destsock;
if(*packet_len < N2N_PKT_HDR_SIZE) {
traceEvent(TRACE_WARNING, "The packet about to be sent is too short [len=%d]\n", *packet_len);
return(-1);
}
memcpy(compressed, packet, N2N_PKT_HDR_SIZE);
peer_addr2sockaddr_in(to, &destsock);
if(compress_data) {
rc = lzo1x_1_compress((u_char*)&packet[N2N_PKT_HDR_SIZE],
*packet_len - N2N_PKT_HDR_SIZE,
(u_char*)&compressed[N2N_PKT_HDR_SIZE],
&compressed_len, wrkmem);
compressed_len += N2N_PKT_HDR_SIZE;
traceEvent(TRACE_INFO, "%u bytes compressed into %u", *packet_len, compressed_len);
/* *packet_len = compressed_len; */
if(sinfo->is_udp_socket) {
rc = sendto(sinfo->sock, compressed, compressed_len, 0,
(struct sockaddr*)&destsock, sizeof(struct sockaddr_in));
} else {
char send_len[5];
/* 4 bytes packet length */
snprintf(send_len, sizeof(send_len), "%04d", (int)compressed_len);
if((rc = send(sinfo->sock, send_len, 4, 0)) != 4)
return(-1);
if((rc = send(sinfo->sock, compressed, compressed_len, 0)) != compressed_len) {
traceEvent(TRACE_WARNING, "send error [%d][%s]",
errno, strerror(errno));
}
}
} else {
compressed_len = *packet_len;
if(sinfo->is_udp_socket)
rc = sendto(sinfo->sock, packet, compressed_len, 0,
(struct sockaddr*)&destsock, sizeof(struct sockaddr_in));
else {
char send_len[5];
/* 4 bytes packet length */
snprintf(send_len, sizeof(send_len), "%04d", (int)compressed_len);
if((rc = send(sinfo->sock, send_len, 4, 0)) != 4)
return(-1);
rc = send(sinfo->sock, compressed, compressed_len, 0);
}
if(rc == -1) {
ipstr_t ip_buf;
traceEvent(TRACE_WARNING, "sendto() failed while attempting to send data to %s:%d",
intoa(ntohl(to->addr_type.v4_addr), ip_buf, sizeof(ip_buf)),
ntohs(to->port));
}
}
if ( rc >= 0) {
traceEvent(TRACE_INFO, "### Tx N2N Msg -> network");
}
if(rc == compressed_len)
return(*packet_len); /* fake just to avoid warnings */
else
return(rc);
}
/* *********************************************** */
u_int reliable_sendto(n2n_sock_info_t * sinfo,
char *packet, size_t *packet_len,
const struct peer_addr *to, u_int8_t compress_data) {
/* char *payload = &packet[N2N_PKT_HDR_SIZE]; */
struct n2n_packet_header hdr_storage;
struct n2n_packet_header *hdr = &hdr_storage;
macstr_t src_mac_buf;
macstr_t dst_mac_buf;
/* REVISIT: efficiency of unmarshal + re-marshal just to change a couple of bits. */
unmarshall_n2n_packet_header( hdr, (u_int8_t *)packet );
/* hdr->sequence_id = (hdr->msg_type == MSG_TYPE_PACKET) ? mac2sequence((u_char*)payload, packet, *packet_len) : 0; */
hdr->sequence_id = 0;
hdr->pkt_type = packet_reliable_data;
traceEvent(TRACE_INFO, "Sent reliable packet [msg_type=%s][seq_id=%d][src_mac=%s][dst_mac=%s]",
msg_type2str(hdr->msg_type), hdr->sequence_id,
macaddr_str(&packet[6], src_mac_buf, sizeof(src_mac_buf)),
macaddr_str(packet, dst_mac_buf, sizeof(dst_mac_buf)));
marshall_n2n_packet_header( (u_int8_t *)packet, hdr );
return(send_data(sinfo, packet, packet_len, to, compress_data));
}
/* *********************************************** */
/* unreliable_sendto is passed a fully marshalled, packet. Its purpose is to set
* the unreliable flags but leave the rest of the packet untouched. */
u_int unreliable_sendto(n2n_sock_info_t * sinfo,
char *packet, size_t *packet_len,
const struct peer_addr *to, u_int8_t compress_data) {
struct n2n_packet_header hdr_storage;
struct n2n_packet_header *hdr = &hdr_storage;
macstr_t src_mac_buf;
macstr_t dst_mac_buf;
/* REVISIT: efficiency of unmarshal + re-marshal just to change a couple of bits. */
unmarshall_n2n_packet_header( hdr, (u_int8_t *)packet );
hdr->sequence_id = 0; /* Unreliable messages have 0 as sequence number */
hdr->pkt_type = packet_unreliable_data;
traceEvent(TRACE_INFO, "Sent unreliable packet [msg_type=%s][seq_id=%d][src_mac=%s][dst_mac=%s]",
msg_type2str(hdr->msg_type), hdr->sequence_id,
macaddr_str(hdr->src_mac, src_mac_buf, sizeof(src_mac_buf)),
macaddr_str(hdr->dst_mac, dst_mac_buf, sizeof(dst_mac_buf)));
marshall_n2n_packet_header( (u_int8_t *)packet, hdr );
return(send_data(sinfo, packet, packet_len, to, compress_data));
}
/* *********************************************** */
char* msg_type2str(u_short msg_type) {
switch(msg_type) {
case MSG_TYPE_REGISTER: return("MSG_TYPE_REGISTER");
case MSG_TYPE_DEREGISTER: return("MSG_TYPE_DEREGISTER");
case MSG_TYPE_PACKET: return("MSG_TYPE_PACKET");
case MSG_TYPE_REGISTER_ACK: return("MSG_TYPE_REGISTER_ACK");
case MSG_TYPE_ACK_RESPONSE: return("MSG_TYPE_ACK_RESPONSE");
}
return("???");
}
/* *********************************************** */
void hexdump(char *buf, u_int len) {
u_int i;
for(i=0; i<len; i++) {
if((i > 0) && ((i % 16) == 0)) printf("\n");
printf("%02X ", buf[i] & 0xFF);
}
printf("\n");
}
/* *********************************************** */
void print_n2n_version() {
printf("Welcome to n2n v.%s for %s\n"
"Built on %s\n"
"Copyright 2007-08 - http://www.ntop.org\n\n",
version, osName, buildDate);
}
/** Find the peer entry in list with mac_addr equal to mac.
*
* Does not modify the list.
*
* @return NULL if not found; otherwise pointer to peer entry.
*/
struct peer_info * find_peer_by_mac( struct peer_info * list, const char * mac )
{
while(list != NULL)
{
if( 0 == memcmp(mac, list->mac_addr, 6) )
{
return list;
}
list = list->next;
}
return NULL;
}
/** Return the number of elements in the list.
*
*/
size_t peer_list_size( const struct peer_info * list )
{
size_t retval=0;
while ( list )
{
++retval;
list = list->next;
}
return retval;
}
/** Add new to the head of list. If list is NULL; create it.
*
* The item new is added to the head of the list. New is modified during
* insertion. list takes ownership of new.
*/
void peer_list_add( struct peer_info * * list,
struct peer_info * new )
{
new->next = *list;
new->last_seen = time(NULL);
*list = new;
}
size_t purge_expired_registrations( struct peer_info ** peer_list ) {
static time_t last_purge = 0;
time_t now = time(NULL);
size_t num_reg = 0;
if((now - last_purge) < PURGE_REGISTRATION_FREQUENCY) return 0;
traceEvent(TRACE_INFO, "Purging old registrations");
num_reg = purge_peer_list( peer_list, now-REGISTRATION_TIMEOUT );
last_purge = now;
traceEvent(TRACE_INFO, "Remove %ld registrations", num_reg);
return num_reg;
}
/** Purge old items from the peer_list and return the number of items that were removed. */
size_t purge_peer_list( struct peer_info ** peer_list,
time_t purge_before )
{
struct peer_info *scan;
struct peer_info *prev;
size_t retval=0;
scan = *peer_list;
prev = NULL;
while(scan != NULL)
{
if(scan->last_seen < purge_before)
{
struct peer_info *next = scan->next;
if(prev == NULL)
{
*peer_list = next;
}
else
{
prev->next = next;
}
++retval;
free(scan);
scan = next;
}
else
{
prev = scan;
scan = scan->next;
}
}
return retval;
}
static u_int8_t hex2byte( const char * s )
{
char tmp[3];
tmp[0]=s[0];
tmp[1]=s[1];
tmp[2]=0; /* NULL term */
return((u_int8_t)strtol( s, NULL, 16 ));
}
extern int str2mac( u_int8_t * outmac /* 6 bytes */, const char * s )
{
size_t i;
/* break it down as one case for the first "HH", the 5 x through loop for
* each ":HH" where HH is a two hex nibbles in ASCII. */
*outmac=hex2byte(s);
++outmac;
s+=2; /* don't skip colon yet - helps generalise loop. */
for (i=1; i<6; ++i )
{
s+=1;
*outmac=hex2byte(s);
++outmac;
s+=2;
}
return 0; /* ok */
}

290
n2n.h Normal file
View file

@ -0,0 +1,290 @@
/*
* (C) 2007-08 - Luca Deri <deri@ntop.org>
*
* 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 <http://www.gnu.org/licenses/>
*
* Code contributions courtesy of:
* Richard Andrews <bbmaj7@yahoo.com.au>
* Babak Farrokhi <babak@farrokhi.net> [FreeBSD port]
*
*/
#ifndef _N2N_H_
#define _N2N_H_
/*
tunctl -t tun0
tunctl -t tun1
ifconfig tun0 1.2.3.4 up
ifconfig tun1 1.2.3.5 up
./edge -d tun0 -l 2000 -r 127.0.0.1:3000 -c hello
./edge -d tun1 -l 3000 -r 127.0.0.1:2000 -c hello
tunctl -u UID -t tunX
*/
#if defined(__APPLE__) && defined(__MACH__)
#define _DARWIN_
#endif
#ifdef WIN32
#include "win32/n2n_win32.h"
#endif
#include <time.h>
#include <ctype.h>
#include <stdlib.h>
#ifndef WIN32
#include <netdb.h>
#endif
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#ifndef WIN32
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/param.h>
#include <pthread.h>
#ifdef __linux__
#include <linux/if.h>
#include <linux/if_tun.h>
#endif
#ifdef __FreeBSD__
#include <netinet/in_systm.h>
#endif
#include <syslog.h>
#include <sys/wait.h>
#include <net/ethernet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <unistd.h>
#define closesocket(a) close(a)
#endif
#include <string.h>
#ifdef WIN32
#include "win32/getopt.h"
#else
#define _GNU_SOURCE
#include <getopt.h>
#endif
#include <stdarg.h>
#ifdef WIN32
#include "win32/wintap.h"
#endif
#include "twofish.h"
#ifndef WIN32
typedef struct tuntap_dev {
int fd;
u_int8_t mac_addr[6];
u_int32_t ip_addr, device_mask;
u_int mtu;
} tuntap_dev;
#define SOCKET int
#endif /* #ifndef WIN32 */
#define QUICKLZ 1
#define N2N_VERSION 1
#define MSG_TYPE_REGISTER 1 /* FIX invece di usare il sender del pacchetto scriverlo nel pacchetto stesso */
#define MSG_TYPE_DEREGISTER 2
#define MSG_TYPE_PACKET 3
#define MSG_TYPE_REGISTER_ACK 4
#define MSG_TYPE_ACK_RESPONSE 5
#define COMMUNITY_LEN 16
#define MIN_COMPRESSED_PKT_LEN 32
/* Maximum enum value is 255 due to marshalling into 1 byte */
enum packet_type {
packet_unreliable_data = 0, /* no ACK needed */
packet_reliable_data, /* needs ACK */
packet_ping,
packet_pong
};
/* All information is always in network byte-order */
struct peer_addr {
u_int8_t family;
u_int16_t port;
union {
u_int8_t v6_addr[16];
u_int32_t v4_addr;
} addr_type;
};
struct n2n_packet_header {
u_int8_t version, msg_type, ttl, sent_by_supernode;
char community_name[COMMUNITY_LEN], src_mac[6], dst_mac[6];
struct peer_addr public_ip, private_ip;
enum packet_type pkt_type;
u_int32_t sequence_id;
u_int32_t crc; // FIX - It needs to be handled for detcting forged packets
};
int marshall_n2n_packet_header( u_int8_t * buf, const struct n2n_packet_header * hdr );
int unmarshall_n2n_packet_header( struct n2n_packet_header * hdr, const u_int8_t * buf );
#define N2N_PKT_HDR_SIZE (sizeof(struct n2n_packet_header))
/** Common type used to hold stringified IP addresses. */
typedef char ipstr_t[32];
/** Common type used to hold stringified MAC addresses. */
typedef char macstr_t[32];
struct n2n_sock_info
{
int sock;
char is_udp_socket /*= 1*/;
};
typedef struct n2n_sock_info n2n_sock_info_t;
struct peer_info {
char community_name[16], mac_addr[6];
struct peer_addr public_ip, private_ip;
time_t last_seen;
struct peer_info *next;
/* socket */
n2n_sock_info_t sinfo;
};
struct n2n_edge; /* defined in edge.c */
typedef struct n2n_edge n2n_edge_t;
/* ************************************** */
#if defined(DEBUG)
#define SOCKET_TIMEOUT_INTERVAL_SECS 5
#define REGISTER_FREQUENCY 20 /* sec */
#else /* #if defined(DEBUG) */
#define SOCKET_TIMEOUT_INTERVAL_SECS 10
#define REGISTER_FREQUENCY 60 /* sec */
#endif /* #if defined(DEBUG) */
#define TRACE_ERROR 0, __FILE__, __LINE__
#define TRACE_WARNING 1, __FILE__, __LINE__
#define TRACE_NORMAL 2, __FILE__, __LINE__
#define TRACE_INFO 3, __FILE__, __LINE__
/* ************************************** */
#define SUPERNODE_IP "127.0.0.1"
#define SUPERNODE_PORT 1234
/* ************************************** */
#ifndef max
#define max(a, b) ((a < b) ? b : a)
#endif
#ifndef min
#define min(a, b) ((a > b) ? b : a)
#endif
/* ************************************** */
/* Variables */
// extern TWOFISH *tf;
extern int traceLevel;
extern char broadcast_addr[6];
extern char multicast_addr[6];
/* Functions */
extern void sockaddr_in2peer_addr(struct sockaddr_in *in, struct peer_addr *out);
extern void peer_addr2sockaddr_in(const struct peer_addr *in, struct sockaddr_in *out);
// extern int init_n2n(u_int8_t *encrypt_pwd, u_int32_t encrypt_pwd_len );
// extern void term_n2n();
extern void send_ack(n2n_sock_info_t * sinfo,
u_int16_t last_rcvd_seq_id,
struct n2n_packet_header *header,
struct peer_addr *remote_peer,
char *src_mac);
extern void traceEvent(int eventTraceLevel, char* file, int line, char * format, ...);
extern int tuntap_open(tuntap_dev *device, char *dev, char *device_ip, char *device_mask, const char * device_mac );
extern int tuntap_read(struct tuntap_dev *tuntap, unsigned char *buf, int len);
extern int tuntap_write(struct tuntap_dev *tuntap, unsigned char *buf, int len);
extern void tuntap_close(struct tuntap_dev *tuntap);
extern SOCKET open_socket(int local_port, int udp_sock, int server_mode);
extern int connect_socket(int sock_fd, struct peer_addr* dest);
extern void send_packet(n2n_sock_info_t * sinfo,
char *packet, size_t *packet_len,
const struct peer_addr *remote_peer,
u_int8_t compress_data);
extern char* intoa(u_int32_t addr, char* buf, u_short buf_len);
extern char* macaddr_str(const char *mac, char *buf, int buf_len);
extern int str2mac( u_int8_t * outmac /* 6 bytes */, const char * s );
extern void fill_standard_header_fields(n2n_sock_info_t * eee,
struct n2n_packet_header *hdr,
char *src_mac);
extern u_int receive_data(n2n_sock_info_t * sinfo,
char *packet, size_t packet_len,
struct peer_addr *from, u_int8_t *discarded_pkt,
char *tun_mac_addr, u_int8_t decompress_data,
struct n2n_packet_header *hdr);
extern u_int reliable_sendto(n2n_sock_info_t * sinfo,
char *packet, size_t *packet_len,
const struct peer_addr *from, u_int8_t compress_data);
extern u_int unreliable_sendto(n2n_sock_info_t * sinfo,
char *packet, size_t *packet_len,
const struct peer_addr *from, u_int8_t compress_data);
extern u_int send_data(n2n_sock_info_t * sinfo,
char *packet, size_t *packet_len,
const struct peer_addr *to, u_int8_t compress_data);
extern u_int8_t is_multi_broadcast(char *dest_mac);
extern char* msg_type2str(u_short msg_type);
extern void hexdump(char *buf, u_int len);
void print_n2n_version();
/* Operations on peer_info lists. */
struct peer_info * find_peer_by_mac( struct peer_info * list,
const char * mac );
void peer_list_add( struct peer_info * * list,
struct peer_info * new );
size_t peer_list_size( const struct peer_info * list );
size_t purge_peer_list( struct peer_info ** peer_list,
time_t purge_before );
size_t purge_expired_registrations( struct peer_info ** peer_list );
/* version.c */
extern char *version, *osName, *buildDate;
#endif /* _N2N_H_ */

47
n2n.spec Normal file
View file

@ -0,0 +1,47 @@
Summary: N2N peer-to-peer virtual private network system.
Name: n2n
Version: 1.2
Release: 1
License: GPLv3
Vendor: ntop.org
Group: None
URL: http://www.ntop.org/n2n
Source0: %{name}-%{version}.tar.gz
BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root
%description
N2N is a peer-to-peer virtual private network system. N2N uses the universal
TUNTAP interface to create TAP network interfaces to an encrypted virtual
LAN. Members of a community share a common encryption key which allows echange
of data. The supernode is used for peer discovery and initial packet relay
before direct peer-to-peer exchange is established.
Once direct packet exchange is established, the supernode is not required.
%prep
%setup -q
echo -e "\n *** Building ${RPM_PACKAGE_NAME}-${RPM_PACKAGE_VERSION}-${RPM_PACKAGE_RELEASE} ***\n"
%build
make
%install
make PREFIX=${RPM_BUILD_ROOT}/usr install
%clean
rm -rf $RPM_BUILD_ROOT
%files
%defattr(-,root,root,-)
/usr/bin/supernode
/usr/sbin/edge
%doc /usr/share/man/man1/supernode.1.gz
%doc /usr/share/man/man8/edge.8.gz
%changelog
* Sat May 3 2008 Richard Andrews <andrews@ntop.org> -
- Initial build.

55
openwrt/kamikaze/Makefile Normal file
View file

@ -0,0 +1,55 @@
#
# Copyright (C) 2008 OpenWrt.org
#
# This is free software, licensed under the GNU General Public License v2.
include $(TOPDIR)/rules.mk
PKG_BRANCH:=trunk
PKG_SOURCE_URL:=https://svn.ntop.org/svn/ntop/trunk/n2n
PKG_REV:=$(shell LC_ALL=C svn info ${PKG_SOURCE_URL} | sed -ne's/^Last Changed Rev: //p')
PKG_NAME:=n2n
PKG_VERSION:=svn$(PKG_REV)
PKG_RELEASE:=1
PKG_SOURCE_SUBDIR:=$(PKG_NAME)-$(PKG_VERSION)
PKG_SOURCE:=$(PKG_SOURCE_SUBDIR).tar.gz
PKG_SOURCE_PROTO:=svn
PKG_SOURCE_VERSION:=$(PKG_REV)
PKG_BUILD_DEPENDS:=
PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(PKG_VERSION)
PKG_INSTALL_DIR:=$(PKG_BUILD_DIR)
include $(INCLUDE_DIR)/package.mk
define Package/n2n
SECTION:=net
CATEGORY:=Network
TITLE:=VPN tunneling daemon
URL:=http://www.ntop.org/n2n/
SUBMENU:=VPN
DEPENDS:=libpthread
endef
define Build/Configure
endef
define Build/Compile
$(MAKE) CC="$(TARGET_CC)" -C $(PKG_BUILD_DIR)
endef
define Package/n2n/install
$(INSTALL_DIR) $(1)/usr/sbin
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/edge $(1)/usr/sbin/
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/supernode $(1)/usr/sbin/
endef
$(eval $(call BuildPackage,n2n))

30
scripts/mk_SRPM.sh Executable file
View file

@ -0,0 +1,30 @@
#!/bin/sh
# This script makes a SRPM - a source RPM file which can be built into the
# appropriate distro specific RPM for any platform.
#
# To build the binary package:
# rpm -i n2n-<ver>.src.rpm
# rpmbuild -bb n2n.spec
#
# Look for the "Wrote:" line to see where the final RPM is.
#
# To run this script cd to the n2n directory and run it as follows
# scripts/mk_SRPMS.sh
#
set -e
set -x
BASE=`pwd`
TARFILE=`${BASE}/scripts/mk_tar.sh`
test -f ${TARFILE}
echo "Building SRPM"
# -ts means build source RPM from tarfile
rpmbuild -ts ${TARFILE}
echo "Done"

46
scripts/mk_deb.sh Executable file
View file

@ -0,0 +1,46 @@
#!/bin/bash
# This script makes a SRPM - a source RPM file which can be built into the
# appropriate distro specific RPM for any platform.
#
# To build the binary package:
# rpm -i n2n-<ver>.src.rpm
# rpmbuild -bb n2n.spec
#
# Look for the "Wrote:" line to see where the final RPM is.
#
# To run this script cd to the n2n directory and run it as follows
# scripts/mk_SRPMS.sh
#
set -e
set -x
BASE=`pwd`
TARFILE=`${BASE}/scripts/mk_tar.sh`
TEMPDIR="build_deb"
test -f ${TARFILE}
echo "Building .deb"
if [ -d ${TEMPDIR} ]; then
echo "Removing ${TEMPDIR} directory"
rm -rf ${TEMPDIR} >&2
fi
mkdir ${TEMPDIR}
pushd ${TEMPDIR}
tar xzf ${TARFILE} #At original location
cd n2n*
dpkg-buildpackage -rfakeroot
popd
echo "Done"

105
scripts/mk_tar.sh Executable file
View file

@ -0,0 +1,105 @@
#!/bin/bash
# This script makes a SRPM - a source RPM file which can be built into the
# appropriate distro specific RPM for any platform.
#
# To build the binary package:
# rpm -i n2n-<ver>.src.rpm
# rpmbuild -bb n2n.spec
#
# Look for the "Wrote:" line to see where the final RPM is.
#
# To run this script cd to the n2n directory and run it as follows
# scripts/mk_SRPMS.sh
#
set -e
function exit_fail()
{
echo "$1"
exit 1
}
PACKAGE="n2n"
PKG_VERSION="1.2"
PKG_AND_VERSION="${PACKAGE}-${PKG_VERSION}"
TEMPDIR="tmp"
SOURCE_MANIFEST="
README
edge.c
lzoconf.h
lzodefs.h
Makefile
minilzo.c
minilzo.h
n2n.c
n2n.h
n2n.spec
supernode.c
tuntap_linux.c
tuntap_freebsd.c
tuntap_osx.c
twofish.c
twofish.h
edge.8
supernode.1
debian/changelog
debian/compat
debian/control
debian/copyright
debian/files
debian/n2n.dirs
debian/n2n.docs
debian/n2n.install
debian/n2n.manpages
debian/README.Debian
debian/rules
"
BASE=`pwd`
for F in ${SOURCE_MANIFEST}; do
test -e $F || exit_fail "Wrong directory. Please execute from n2n directory."; >&2
done
echo "Found critical files. Proceeding." >&2
if [ -d ${TEMPDIR} ]; then
echo "Removing ${TEMPDIR} directory"
rm -rf ${TEMPDIR} >&2
fi
mkdir ${TEMPDIR} >&2
pushd ${TEMPDIR} >&2
echo "Creating staging directory ${PWD}/${PKG_AND_VERSION}" >&2
if [ -d ${PKG_AND_VERSION} ] ; then
echo "Removing ${PKG_AND_VERSION} directory"
rm -rf ${PKG_AND_VERSION} >&2
fi
mkdir ${PKG_AND_VERSION}
pushd ${BASE} >&2
echo "Copying in files" >&2
for F in ${SOURCE_MANIFEST}; do
cp --parents -a $F ${TEMPDIR}/${PKG_AND_VERSION}/
done
popd >&2
TARFILE="${PKG_AND_VERSION}.tar.gz"
echo "Creating ${TARFILE}" >&2
tar czf ${BASE}/${TARFILE} ${PKG_AND_VERSION}
popd >&2
rm -rf ${TEMPDIR} >&2
echo ${BASE}/${TARFILE}

32
supernode.1 Normal file
View file

@ -0,0 +1,32 @@
.TH supernode 1 "May 3, 2008" "revision 3472" "USER COMMANDS"
.SH NAME
supernode \- n2n supernode daemon
.SH SYNOPSIS
.B supernode \-l <port> [\-v]
.SH DESCRIPTION
N2N is a peer-to-peer VPN system. Supernode is a node introduction registry,
broadcast conduit and packet relay node for the n2n system. On startup supernode
begins listening on the specified UDP port for node registrations, and other
packets to route. The supernode can service any number of communities and routes
packets only between members of the same community. The supernode does not hold
the community encryption key and so cannot snoop or inject packets into the
community.
.PP
All logging goes to stdout.
.SH OPTIONS
.TP
\-l
listen on the given UDP port
\-v
use verbose logging
.SH EXAMPLES
.TP
.B supernode -l 7654 -v
Start supernode listening on UDP port 7654 with verbose output.
.PP
.SH EXIT STATUS
edge is a daemon and any exit is an error
.SH AUTHOR
Luca Deri ( deri (at) ntop.org ), Richard Andrews ( andrews (at) ntop.org ), Don Bindner
.SH SEE ALSO
ifconfig(1) edge(1)

525
supernode.c Normal file
View file

@ -0,0 +1,525 @@
/*
* (C) 2007-08 - Luca Deri <deri@ntop.org>
*
* 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 <http://www.gnu.org/licenses/>
*
* Code contributions courtesy of:
* Richard Andrews <bbmaj7@yahoo.com.au>
*
*/
#include "n2n.h"
struct tx_stats
{
size_t pkts;
size_t errors;
};
/* *********************************************** */
static void help() {
print_n2n_version();
printf("supernode -l <listening port> [-v] [-h]\n");
exit(0);
}
/* *********************************************** */
static struct peer_info *known_peers = NULL;
static struct tx_stats supernode_stats = {0,0};
/* *********************************************** */
/** Turn a REGISTER request around and send a REGISTER_ACK packet back to the
* sender.
*
* This needs to be done for all incoming REGISTER packets to keep firewalls
* open
*/
static void send_register_ack( n2n_sock_info_t * sinfo,
const struct peer_addr *destination_peer,
const struct n2n_packet_header * reqhdr )
{
struct n2n_packet_header hdr;
u_int8_t pkt[N2N_PKT_HDR_SIZE];
size_t len = sizeof(hdr);
fill_standard_header_fields(sinfo, &hdr, NULL /* zero src MAC */ );
hdr.sent_by_supernode = 1;
hdr.msg_type = MSG_TYPE_REGISTER_ACK;
memcpy( hdr.community_name, reqhdr->community_name, COMMUNITY_LEN);
memcpy( hdr.dst_mac, reqhdr->src_mac, 6); /* turn it around */
/* leave IP sockets unfilled. */
marshall_n2n_packet_header( pkt, &hdr );
send_packet(sinfo, (char *)pkt, &len, destination_peer, 1);
}
static void register_peer(struct n2n_packet_header *hdr,
struct peer_addr *sender,
n2n_sock_info_t * sinfo) {
struct peer_info *scan = known_peers;
ipstr_t buf, buf1;
macstr_t mac_buf;
send_register_ack( sinfo, sender, hdr ); /* keep firewalls open */
while(scan != NULL) {
if((strcmp(scan->community_name, hdr->community_name) == 0)
&& (memcmp(&scan->mac_addr, hdr->src_mac, 6) == 0)) {
scan->last_seen = time(NULL);
if ( ( 0 != memcmp(&scan->public_ip, sender, sizeof(struct peer_addr)) ) ||
( 0 != memcmp(&scan->private_ip, &hdr->private_ip, sizeof(struct peer_addr)) ) )
{
/* Something is actually different. */
memcpy(&scan->public_ip, sender, sizeof(struct peer_addr));
memcpy(&scan->private_ip, &hdr->private_ip, sizeof(struct peer_addr));
/* Overwrite existing peer */
traceEvent(TRACE_NORMAL, "Re-registered node [public_ip=(%d)%s:%d][private_ip=%s:%d][mac=%s][community=%s]",
scan->public_ip.family,
intoa(ntohl(scan->public_ip.addr_type.v4_addr), buf, sizeof(buf)),
ntohs(scan->public_ip.port),
intoa(ntohl(scan->private_ip.addr_type.v4_addr), buf1, sizeof(buf1)),
ntohs(scan->private_ip.port),
macaddr_str(scan->mac_addr, mac_buf, sizeof(mac_buf)),
scan->community_name);
}
return; /* Found the registration entry so stop. */
}
scan = scan->next;
}
/* FIX mettere un limite alla lista dei peer */
scan = (struct peer_info*)calloc(1, sizeof(struct peer_info));
memcpy(scan->community_name, hdr->community_name, COMMUNITY_LEN);
memcpy(&scan->public_ip, sender, sizeof(struct peer_addr));
memcpy(&scan->private_ip, &hdr->private_ip, sizeof(struct peer_addr));
memcpy(&scan->mac_addr, hdr->src_mac, 6);
scan->last_seen = time(NULL); // FIX aggiungere un timeout
scan->next = known_peers;
scan->sinfo = *sinfo;
known_peers = scan;
traceEvent(TRACE_NORMAL, "Registered new node [public_ip=(%d)%s:%d][private_ip=%s:%d][mac=%s][community=%s]",
scan->public_ip.family,
intoa(ntohl(scan->public_ip.addr_type.v4_addr), buf, sizeof(buf)),
ntohs(scan->public_ip.port),
intoa(ntohl(scan->private_ip.addr_type.v4_addr), buf1, sizeof(buf1)),
ntohs(scan->private_ip.port),
macaddr_str(scan->mac_addr, mac_buf, sizeof(mac_buf)),
scan->community_name);
}
/* *********************************************** */
static void deregister_peer(struct n2n_packet_header *hdr,
struct peer_addr *sender) {
struct peer_info *scan = known_peers, *prev = NULL;
ipstr_t buf, buf1;
while(scan != NULL) {
if((strcmp(scan->community_name, hdr->community_name) == 0)
&& (memcmp(&scan->mac_addr, hdr->src_mac, 6) == 0)) {
/* Overwrite existing peer */
if(prev == NULL)
known_peers = scan->next;
else
prev->next = scan->next;
traceEvent(TRACE_INFO, "Degistered node [public_ip=%s:%d][private_ip=%s:%d]",
intoa(ntohl(scan->public_ip.addr_type.v4_addr), buf, sizeof(buf)),
ntohs(scan->public_ip.port),
intoa(ntohl(scan->private_ip.addr_type.v4_addr), buf1, sizeof(buf1)),
ntohs(scan->private_ip.port));
free(scan);
return;
}
scan = scan->next;
}
traceEvent(TRACE_WARNING, "Unable to delete specified peer [%s:%d]",
intoa(ntohl(sender->addr_type.v4_addr), buf, sizeof(buf)),
ntohs(sender->port));
}
/* *********************************************** */
/* *********************************************** */
static const struct option long_options[] = {
{ "community", required_argument, NULL, 'c' },
{ "listening-port", required_argument, NULL, 'l' },
{ "help" , no_argument, NULL, 'h' },
{ "verbose", no_argument, NULL, 'v' },
{ NULL, 0, NULL, 0 }
};
/* *********************************************** */
/** Forward a L2 packet to every edge registered for the community of the
* originator.
*
* @return number of copies of the packet sent
*/
static size_t broadcast_packet(char *packet, u_int packet_len,
struct peer_addr *sender,
n2n_sock_info_t * sinfo,
struct n2n_packet_header *hdr )
{
size_t numsent=0;
struct peer_info *scan;
scan = known_peers;
while(scan != NULL) {
if((strcmp(scan->community_name, hdr->community_name) == 0)
&& (memcmp(sender, &scan->public_ip, sizeof(struct peer_addr)) /* No L3 self-send */) )
{
int data_sent_len;
size_t len = packet_len;
data_sent_len = send_data( &(scan->sinfo), packet, &len, &scan->public_ip, 0);
if(data_sent_len != len)
{
++(supernode_stats.errors);
traceEvent(TRACE_WARNING, "sendto() [sent=%d][attempted_to_send=%d] [%s]\n",
data_sent_len, len, strerror(errno));
}
else
{
ipstr_t buf;
ipstr_t buf1;
++numsent;
++(supernode_stats.pkts);
traceEvent(TRACE_INFO, "Sent multicast message to remote node [%s:%d][mac=%s]",
intoa(ntohl(scan->public_ip.addr_type.v4_addr), buf, sizeof(buf)),
ntohs(scan->public_ip.port),
macaddr_str(scan->mac_addr, buf1, sizeof(buf1)));
}
}
scan = scan->next;
} /* while */
return numsent;
}
/** Forward a L2 packet. This may involve a broadcast operation.
*
* Rules are as follows:
*
* 1. If the dest MAC is a multicast address, broadcast to all edges in the
* community.
*
* 2. If the dest MAC is known forward to the destination edge only.
* Else broadcast to all edges in the community.
*
* @return number of copies of the packet sent
*/
static size_t forward_packet(char *packet, u_int packet_len,
struct peer_addr *sender,
n2n_sock_info_t * sinfo,
struct n2n_packet_header *hdr )
{
size_t numsent=0;
u_int8_t is_dst_broad_multi_cast;
struct peer_info *scan;
ipstr_t buf;
ipstr_t buf1;
hdr->ttl++; /* FIX discard packets with a high TTL */
is_dst_broad_multi_cast = is_multi_broadcast(hdr->dst_mac);
/* Put the original packet sender (public) address */
memcpy(&hdr->public_ip, sender, sizeof(struct peer_addr));
hdr->sent_by_supernode = 1;
marshall_n2n_packet_header( (u_int8_t *)packet, hdr );
if ( is_dst_broad_multi_cast )
{
traceEvent(TRACE_INFO, "Broadcasting. Multicast address [mac=%s]",
macaddr_str(hdr->dst_mac, buf, sizeof(buf)));
numsent = broadcast_packet( packet, packet_len, sender, sinfo, hdr );
}
else
{
scan = find_peer_by_mac( known_peers, hdr->dst_mac );
if ( scan )
{
int data_sent_len;
size_t len = packet_len;
data_sent_len = send_data( &(scan->sinfo), packet, &len, &scan->public_ip, 0);
if(data_sent_len != len)
{
++(supernode_stats.errors);
traceEvent(TRACE_WARNING, "sendto() [sent=%d][attempted_to_send=%d] [%s]\n",
data_sent_len, len, strerror(errno));
}
else {
++(supernode_stats.pkts);
traceEvent(TRACE_INFO, "Sent message to remote node [%s:%d][mac=%s]",
intoa(ntohl(scan->public_ip.addr_type.v4_addr), buf, sizeof(buf)),
ntohs(scan->public_ip.port),
macaddr_str(scan->mac_addr, buf1, sizeof(buf1)));
}
numsent = 1;
}
else
{
traceEvent(TRACE_INFO, "Broadcasting because unknown dest [mac=%s]",
macaddr_str(hdr->dst_mac, buf, sizeof(buf)));
numsent = broadcast_packet( packet, packet_len, sender, sinfo, hdr );
}
}
return numsent;
}
static void handle_packet(char *packet, u_int packet_len,
struct peer_addr *sender,
n2n_sock_info_t * sinfo) {
ipstr_t buf;
traceEvent(TRACE_INFO, "Received message from node [%s:%d]",
intoa(ntohl(sender->addr_type.v4_addr), buf, sizeof(buf)),
ntohs(sender->port));
if(packet_len < N2N_PKT_HDR_SIZE)
traceEvent(TRACE_WARNING, "Received packet too short [len=%d]\n", packet_len);
else {
struct n2n_packet_header hdr_storage;
struct n2n_packet_header *hdr = &hdr_storage;
unmarshall_n2n_packet_header( hdr, (u_int8_t *)packet );
if(hdr->version != N2N_VERSION) {
traceEvent(TRACE_WARNING,
"Received packet with unknown protocol version (%d): discarded\n",
hdr->version);
return;
}
if(hdr->msg_type == MSG_TYPE_REGISTER)
{
register_peer(hdr, sender, sinfo);
}
else if(hdr->msg_type == MSG_TYPE_DEREGISTER) {
deregister_peer(hdr, sender);
} else if(hdr->msg_type == MSG_TYPE_PACKET) {
forward_packet( packet, packet_len, sender, sinfo, hdr );
} else {
traceEvent(TRACE_WARNING, "Unable to handle packet type %d: ignored\n",
hdr->msg_type);
}
}
}
/* *********************************************** */
static
#ifdef WIN32
DWORD tcpReadThread(LPVOID lpArg)
#else
void* tcpReadThread(void *lpArg)
#endif
{
n2n_sock_info_t sinfo;
char c[1600];
int new_line = 0;
sinfo.sock=(int)lpArg;
sinfo.is_udp_socket=0; /* TCP in this case */
traceEvent(TRACE_NORMAL, "Handling sock_fd %d", sinfo.sock);
while(1) {
int rc;
if((rc = recv(sinfo.sock, c, 2, 0)) > 0) {
if((c[0] == '\r') && (c[1] == '\n')) {
if(!new_line)
new_line = 1;
else
break; /* Double \r\n\r\n, the http header is over */
} else
printf("%c%c [%d][%d] ", c[0], c[1], c[0], c[1]); fflush(stdout);
} else {
traceEvent(TRACE_NORMAL, "recv() error [rc=%d][%s]", rc, strerror(errno));
break;
}
}
/* Beginning of n2n protocol over TCP */
c[5] = 0;
while(1) {
int rc;
// FIX: add select
if((rc = recv(sinfo.sock, c, 4, 0)) == 4) {
int len = atoi(c);
socklen_t from_len = sizeof(struct sockaddr_in );
struct sockaddr_in from;
/* Check packet length */
if((len <= 0) || (len >= 1600)) break;
rc = recvfrom(sinfo.sock, c, len, 0, (struct sockaddr*)&from, &from_len);
if((rc <= 0) || (rc != len))
break;
else {
struct peer_addr _from;
sockaddr_in2peer_addr(&from, &_from);
handle_packet(c, len, &_from, &sinfo);
}
} else
break;
}
closesocket(sinfo.sock);
#ifdef WIN32
return(0);
#else
return(NULL);
#endif
}
/* *********************************************** */
static void startTcpReadThread(int sock_fd) {
#ifdef WIN32
HANDLE hThread;
DWORD dwThreadId;
hThread = CreateThread(NULL, /* no security attributes */
0, /* use default stack size */
(LPTHREAD_START_ROUTINE)tcpReadThread, /* thread function */
(void*)sock_fd, /* argument to thread function */
0, /* use default creation flags */
&dwThreadId); /* returns the thread identifier */
#else
int rc;
pthread_t threadId;
rc = pthread_create(&threadId, NULL, tcpReadThread, (void*)sock_fd);
#endif
}
/* *********************************************** */
int main(int argc, char* argv[]) {
int opt, local_port = 0;
n2n_sock_info_t udp_sinfo;
n2n_sock_info_t tcp_sinfo;
optarg = NULL;
while((opt = getopt_long(argc, argv, "l:vh", long_options, NULL)) != EOF) {
switch (opt) {
case 'l': /* local-port */
local_port = atoi(optarg);
break;
case 'h': /* help */
help();
break;
case 'v': /* verbose */
traceLevel = 3;
break;
}
}
if(!(local_port))
help();
udp_sinfo.is_udp_socket=1;
udp_sinfo.sock = open_socket(local_port, 1, 0);
if(udp_sinfo.sock < 0) return(-1);
tcp_sinfo.is_udp_socket=0;
tcp_sinfo.sock = open_socket(local_port, 0, 1);
if(tcp_sinfo.sock < 0) return(-1);
traceEvent(TRACE_NORMAL, "Supernode ready: listening on port %d [TCP/UDP]", local_port);
while(1) {
int rc, max_sock;
fd_set socket_mask;
struct timeval wait_time;
FD_ZERO(&socket_mask);
max_sock = max(udp_sinfo.sock, tcp_sinfo.sock);
FD_SET(udp_sinfo.sock, &socket_mask);
FD_SET(tcp_sinfo.sock, &socket_mask);
wait_time.tv_sec = 10; wait_time.tv_usec = 0;
rc = select(max_sock+1, &socket_mask, NULL, NULL, &wait_time);
if(rc > 0) {
if(FD_ISSET(udp_sinfo.sock, &socket_mask)) {
char packet[2048];
size_t len;
struct peer_addr sender;
u_int8_t discarded_pkt;
struct n2n_packet_header hdr;
len = receive_data( &udp_sinfo, packet, sizeof(packet), &sender, &discarded_pkt, NULL, 0, &hdr);
if(len <= 0)
traceEvent(TRACE_WARNING, "recvfrom()=%d [%s]\n", len, strerror(errno));
else {
handle_packet(packet, len, &sender, &udp_sinfo);
}
} else if(FD_ISSET(tcp_sinfo.sock, &socket_mask)) {
struct sockaddr from;
int from_len = sizeof(from);
int new_sock = accept(tcp_sinfo.sock, (struct sockaddr*)&from,
(socklen_t*)&from_len);
if(new_sock < 0) {
traceEvent(TRACE_WARNING, "TCP connection accept() failed [%s]\n", strerror(errno));
} else {
startTcpReadThread(new_sock);
}
}
}
purge_expired_registrations( &known_peers );
} /* while */
closesocket(udp_sinfo.sock);
closesocket(tcp_sinfo.sock);
return(0);
}

124
tuntap_freebsd.c Normal file
View file

@ -0,0 +1,124 @@
/*
* (C) 2007-08 - Luca Deri <deri@ntop.org>
*
* 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 see <http://www.gnu.org/licenses/>
*/
#include "n2n.h"
#ifdef __FreeBSD__
void tun_close(tuntap_dev *device);
/* ********************************** */
#define N2N_FREEBSD_TAPDEVICE_SIZE 32
int tuntap_open(tuntap_dev *device /* ignored */,
char *dev,
char *device_ip,
char *device_mask,
const char * device_mac ) {
int i;
char tap_device[N2N_FREEBSD_TAPDEVICE_SIZE];
for (i = 0; i < 255; i++) {
snprintf(tap_device, sizeof(tap_device), "/dev/tap%d", i);
device->fd = open(tap_device, O_RDWR);
if(device->fd > 0) {
traceEvent(TRACE_NORMAL, "Succesfully open %s", tap_device);
break;
}
}
if(device->fd < 0) {
traceEvent(TRACE_ERROR, "Unable to open tap device");
return(-1);
} else {
char buf[256];
FILE *fd;
device->ip_addr = inet_addr(device_ip);
if ( device_mac )
{
/* FIXME - This is not tested. Might be wrong syntax for OS X */
/* Set the hw address before bringing the if up. */
snprintf(buf, sizeof(buf), "ifconfig tap%d ether %s",
i, device_mac);
system(buf);
}
snprintf(buf, sizeof(buf), "ifconfig tap%d %s netmask %s mtu 1400 up",
i, device_ip, device_mask);
system(buf);
traceEvent(TRACE_NORMAL, "Interface tap%d up and running (%s/%s)",
i, device_ip, device_mask);
/* Read MAC address */
snprintf(buf, sizeof(buf), "ifconfig tap%d |grep ether|cut -c 8-24", i);
/* traceEvent(TRACE_INFO, "%s", buf); */
fd = popen(buf, "r");
if(fd < 0) {
tun_close(device);
return(-1);
} else {
int a, b, c, d, e, f;
buf[0] = 0;
fgets(buf, sizeof(buf), fd);
pclose(fd);
if(buf[0] == '\0') {
traceEvent(TRACE_ERROR, "Unable to read tap%d interface MAC address");
exit(0);
}
traceEvent(TRACE_NORMAL, "Interface tap%d mac %s", i, buf);
if(sscanf(buf, "%02x:%02x:%02x:%02x:%02x:%02x", &a, &b, &c, &d, &e, &f) == 6) {
device->mac_addr[0] = a, device->mac_addr[1] = b;
device->mac_addr[2] = c, device->mac_addr[3] = d;
device->mac_addr[4] = e, device->mac_addr[5] = f;
}
}
}
/* read_mac(dev, device->mac_addr); */
return(device->fd);
}
/* ********************************** */
int tuntap_read(struct tuntap_dev *tuntap, unsigned char *buf, int len) {
return(read(tuntap->fd, buf, len));
}
/* ********************************** */
int tuntap_write(struct tuntap_dev *tuntap, unsigned char *buf, int len) {
return(write(tuntap->fd, buf, len));
}
/* ********************************** */
void tuntap_close(struct tuntap_dev *tuntap) {
close(tuntap->fd);
}
#endif

122
tuntap_linux.c Normal file
View file

@ -0,0 +1,122 @@
/*
* (C) 2007-08 - Luca Deri <deri@ntop.org>
*
* 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 <http://www.gnu.org/licenses/>
*/
#include "n2n.h"
#ifdef __linux__
static void read_mac(char *ifname, char *mac_addr) {
int _sock, res;
struct ifreq ifr;
macstr_t mac_addr_buf;
memset (&ifr,0,sizeof(struct ifreq));
/* Dummy socket, just to make ioctls with */
_sock=socket(PF_INET, SOCK_DGRAM, 0);
strcpy(ifr.ifr_name, ifname);
res = ioctl(_sock,SIOCGIFHWADDR,&ifr);
if (res<0) {
perror ("Get hw addr");
} else
memcpy(mac_addr, ifr.ifr_ifru.ifru_hwaddr.sa_data, 6);
traceEvent(TRACE_NORMAL, "Interface %s has MAC %s",
ifname,
macaddr_str(mac_addr, mac_addr_buf, sizeof(mac_addr_buf)));
close(_sock);
}
/* ********************************** */
/** @brief Open and configure the TAP device for packet read/write.
*
* This routine creates the interface via the tuntap driver then uses ifconfig
* to configure address/mask and MTU.
*
* @param device - [inout] a device info holder object
* @param dev - user-defined name for the new iface,
* if NULL system will assign a name
* @param device_ip - address of iface
* @param device_mask - netmask for device_ip
*
* @return - negative value on error
* - non-negative file-descriptor on success
*/
int tuntap_open(tuntap_dev *device,
char *dev, /* user-definable interface name, eg. edge0 */
char *device_ip,
char *device_mask,
const char * device_mac ) {
char *tuntap_device = "/dev/net/tun";
#define N2N_LINUX_SYSTEMCMD_SIZE 128
char buf[N2N_LINUX_SYSTEMCMD_SIZE];
struct ifreq ifr;
int rc;
device->fd = open(tuntap_device, O_RDWR);
if(device->fd < 0) {
printf("ERROR: ioctl() [%s][%d]\n", strerror(errno), rc);
return -1;
}
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = IFF_TAP|IFF_NO_PI; /* Want a TAP device for layer 2 frames. */
strncpy(ifr.ifr_name, dev, IFNAMSIZ);
rc = ioctl(device->fd, TUNSETIFF, (void *)&ifr);
if(rc < 0) {
traceEvent(TRACE_ERROR, "ioctl() [%s][%d]\n", strerror(errno), rc);
close(device->fd);
return -1;
}
/* REVISIT: BbMja7: MTU should be related to MTU of the interface the tuntap
* is built on. The value 1400 assumes an eth iface with MTU 1500, but would
* fail for ppp at mtu=576.
*/
if ( device_mac )
{
/* Set the hw address before bringing the if up. */
snprintf(buf, sizeof(buf), "/sbin/ifconfig %s hw ether %s",
ifr.ifr_name, device_mac );
system(buf);
traceEvent(TRACE_INFO, "Setting MAC: %s", buf);
}
snprintf(buf, sizeof(buf), "/sbin/ifconfig %s %s netmask %s mtu 1400 up",
ifr.ifr_name, device_ip, device_mask);
system(buf);
traceEvent(TRACE_INFO, "Bringing up: %s", buf);
device->ip_addr = inet_addr(device_ip);
read_mac(dev, (char*)device->mac_addr);
return(device->fd);
}
int tuntap_read(struct tuntap_dev *tuntap, unsigned char *buf, int len) {
return(read(tuntap->fd, buf, len));
}
int tuntap_write(struct tuntap_dev *tuntap, unsigned char *buf, int len) {
return(write(tuntap->fd, buf, len));
}
void tuntap_close(struct tuntap_dev *tuntap) {
close(tuntap->fd);
}
#endif /* #ifdef __linux__ */

124
tuntap_osx.c Normal file
View file

@ -0,0 +1,124 @@
/*
* (C) 2007-08 - Luca Deri <deri@ntop.org>
*
* 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 see <http://www.gnu.org/licenses/>
*/
#include "n2n.h"
#ifdef _DARWIN_
void tun_close(tuntap_dev *device);
/* ********************************** */
#define N2N_OSX_TAPDEVICE_SIZE 32
int tuntap_open(tuntap_dev *device /* ignored */,
char *dev,
char *device_ip,
char *device_mask,
const char * device_mac ) {
int i;
char tap_device[N2N_OSX_TAPDEVICE_SIZE];
for (i = 0; i < 255; i++) {
snprintf(tap_device, sizeof(tap_device), "/dev/tap%d", i);
device->fd = open(tap_device, O_RDWR);
if(device->fd > 0) {
traceEvent(TRACE_NORMAL, "Succesfully open %s", tap_device);
break;
}
}
if(device->fd < 0) {
traceEvent(TRACE_ERROR, "Unable to open tap device");
return(-1);
} else {
char buf[256];
FILE *fd;
device->ip_addr = inet_addr(device_ip);
if ( device_mac )
{
/* FIXME - This is not tested. Might be wrong syntax for OS X */
/* Set the hw address before bringing the if up. */
snprintf(buf, sizeof(buf), "ifconfig tap%d ether %s",
i, device_mac);
system(buf);
}
snprintf(buf, sizeof(buf), "ifconfig tap%d %s netmask %s mtu 1400 up",
i, device_ip, device_mask);
system(buf);
traceEvent(TRACE_NORMAL, "Interface tap%d up and running (%s/%s)",
i, device_ip, device_mask);
/* Read MAC address */
snprintf(buf, sizeof(buf), "ifconfig tap%d |grep ether|cut -c 8-24", i);
/* traceEvent(TRACE_INFO, "%s", buf); */
fd = popen(buf, "r");
if(fd < 0) {
tun_close(device);
return(-1);
} else {
int a, b, c, d, e, f;
buf[0] = 0;
fgets(buf, sizeof(buf), fd);
pclose(fd);
if(buf[0] == '\0') {
traceEvent(TRACE_ERROR, "Unable to read tap%d interface MAC address");
exit(0);
}
traceEvent(TRACE_NORMAL, "Interface tap%d mac %s", i, buf);
if(sscanf(buf, "%02x:%02x:%02x:%02x:%02x:%02x", &a, &b, &c, &d, &e, &f) == 6) {
device->mac_addr[0] = a, device->mac_addr[1] = b;
device->mac_addr[2] = c, device->mac_addr[3] = d;
device->mac_addr[4] = e, device->mac_addr[5] = f;
}
}
}
/* read_mac(dev, device->mac_addr); */
return(device->fd);
}
/* ********************************** */
int tuntap_read(struct tuntap_dev *tuntap, unsigned char *buf, int len) {
return(read(tuntap->fd, buf, len));
}
/* ********************************** */
int tuntap_write(struct tuntap_dev *tuntap, unsigned char *buf, int len) {
return(write(tuntap->fd, buf, len));
}
/* ********************************** */
void tuntap_close(struct tuntap_dev *tuntap) {
close(tuntap->fd);
}
#endif

1031
twofish.c Normal file

File diff suppressed because it is too large Load diff

281
twofish.h Normal file
View file

@ -0,0 +1,281 @@
/* $Id: twofish.h,v 2.0 2002/08/11 22:32:25 fknobbe Exp $
*
*
* Copyright (C) 1997-2000 The Cryptix Foundation Limited.
* Copyright (C) 2000 Farm9.
* Copyright (C) 2001 Frank Knobbe.
* All rights reserved.
*
* For Cryptix code:
* Use, modification, copying and distribution of this software is subject
* the terms and conditions of the Cryptix General Licence. You should have
* received a copy of the Cryptix General Licence along with this library;
* if not, you can download a copy from http://www.cryptix.org/ .
*
* For Farm9:
* --- jojo@farm9.com, August 2000, converted from Java to C++, added CBC mode and
* ciphertext stealing technique, added AsciiTwofish class for easy encryption
* decryption of text strings
*
* Frank Knobbe <frank@knobbe.us>:
* --- April 2001, converted from C++ to C, prefixed global variables
* with TwoFish, substituted some defines, changed functions to make use of
* variables supplied in a struct, modified and added routines for modular calls.
* Cleaned up the code so that defines are used instead of fixed 16's and 32's.
* Created two general purpose crypt routines for one block and multiple block
* encryption using Joh's CBC code.
* Added crypt routines that use a header (with a magic and data length).
* (Basically a major rewrite).
*
* Note: Routines labeled _TwoFish are private and should not be used
* (or with extreme caution).
*
*/
#ifndef __TWOFISH_LIBRARY_HEADER__
#define __TWOFISH_LIBRARY_HEADER__
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE !FALSE
#endif
#ifndef bool
#define bool int
#endif
#ifdef WIN32
#include "win32/n2n_win32.h"
#endif
/* Constants */
#define TwoFish_DEFAULT_PW "SnortHas2FishEncryptionRoutines!" /* default password (not more than 32 chars) */
#define TwoFish_DEFAULT_PW_LEN 32
#define TwoFish_MAGIC "TwoFish" /* to indentify a successful decryption */
enum
{ TwoFish_KEY_SIZE = 256, /* Valid values: 64, 128, 192, 256 */
/* User 256, other key sizes have not been tested. */
/* (But should work. I substitutes as much as */
/* I could with this define.) */
TwoFish_ROUNDS = 16,
TwoFish_BLOCK_SIZE = 16, /* bytes in a data-block */
TwoFish_KEY_LENGTH = TwoFish_KEY_SIZE/8, /* 32= 256-bit key */
TwoFish_TOTAL_SUBKEYS = 4+4+2*TwoFish_ROUNDS,
TwoFish_MAGIC_LEN = TwoFish_BLOCK_SIZE-8,
TwoFish_SK_BUMP = 0x01010101,
TwoFish_SK_ROTL = 9,
TwoFish_P_00 = 1,
TwoFish_P_01 = 0,
TwoFish_P_02 = 0,
TwoFish_P_03 = TwoFish_P_01 ^ 1,
TwoFish_P_04 = 1,
TwoFish_P_10 = 0,
TwoFish_P_11 = 0,
TwoFish_P_12 = 1,
TwoFish_P_13 = TwoFish_P_11 ^ 1,
TwoFish_P_14 = 0,
TwoFish_P_20 = 1,
TwoFish_P_21 = 1,
TwoFish_P_22 = 0,
TwoFish_P_23 = TwoFish_P_21 ^ 1,
TwoFish_P_24 = 0,
TwoFish_P_30 = 0,
TwoFish_P_31 = 1,
TwoFish_P_32 = 1,
TwoFish_P_33 = TwoFish_P_31 ^ 1,
TwoFish_P_34 = 1,
TwoFish_GF256_FDBK = 0x169,
TwoFish_GF256_FDBK_2 = 0x169 / 2,
TwoFish_GF256_FDBK_4 = 0x169 / 4,
TwoFish_RS_GF_FDBK = 0x14D, /* field generator */
TwoFish_MDS_GF_FDBK = 0x169 /* primitive polynomial for GF(256) */
};
/* Global data structure for callers */
typedef struct
{
u_int32_t sBox[4 * 256]; /* Key dependent S-box */
u_int32_t subKeys[TwoFish_TOTAL_SUBKEYS]; /* Subkeys */
u_int8_t key[TwoFish_KEY_LENGTH]; /* Encryption Key */
u_int8_t *output; /* Pointer to output buffer */
u_int8_t qBlockPlain[TwoFish_BLOCK_SIZE]; /* Used by CBC */
u_int8_t qBlockCrypt[TwoFish_BLOCK_SIZE];
u_int8_t prevCipher[TwoFish_BLOCK_SIZE];
struct /* Header for crypt functions. Has to be at least one block long. */
{ u_int32_t salt; /* Random salt in first block (will salt the rest through CBC) */
u_int8_t length[4]; /* The amount of data following the header */
u_int8_t magic[TwoFish_MAGIC_LEN]; /* Magic to identify successful decryption */
} header;
bool qBlockDefined;
bool dontflush;
} TWOFISH;
#ifndef __TWOFISH_LIBRARY_SOURCE__
extern bool TwoFish_srand; /* if set to TRUE (default), first call of TwoFishInit will seed rand(); */
/* call of TwoFishInit */
#endif
/**** Public Functions ****/
/* TwoFish Initialization
*
* This routine generates a global data structure for use with TwoFish,
* initializes important values (such as subkeys, sBoxes), generates subkeys
* and precomputes the MDS matrix if not already done.
*
* Input: User supplied password (will be appended by default password of 'SnortHas2FishEncryptionRoutines!')
*
* Output: Pointer to TWOFISH structure. This data structure contains key dependent data.
* This pointer is used with all other crypt functions.
*/
TWOFISH *TwoFishInit(const u_int8_t *userkey, u_int32_t keysize );
/* TwoFish Destroy
*
* Nothing else but a free...
*
* Input: Pointer to the TwoFish structure.
*
*/
void TwoFishDestroy(TWOFISH *tfdata);
/* TwoFish Alloc
*
* Allocates enough memory for the output buffer as required.
*
* Input: Length of the plaintext.
* Boolean flag for BinHex Output.
* Pointer to the TwoFish structure.
*
* Output: Returns a pointer to the memory allocated.
*/
void *TwoFishAlloc(u_int32_t len,bool binhex,bool decrypt,TWOFISH *tfdata);
/* TwoFish Free
*
* Free's the allocated buffer.
*
* Input: Pointer to the TwoFish structure
*
* Output: (none)
*/
void TwoFishFree(TWOFISH *tfdata);
/* TwoFish Set Output
*
* If you want to allocate the output buffer yourself,
* then you can set it with this function.
*
* Input: Pointer to your output buffer
* Pointer to the TwoFish structure
*
* Output: (none)
*/
void TwoFishSetOutput(u_int8_t *outp,TWOFISH *tfdata);
/* TwoFish Raw Encryption
*
* Does not use header, but does use CBC (if more than one block has to be encrypted).
*
* Input: Pointer to the buffer of the plaintext to be encrypted.
* Pointer to the buffer receiving the ciphertext.
* The length of the plaintext buffer.
* The TwoFish structure.
*
* Output: The amount of bytes encrypted if successful, otherwise 0.
*/
u_int32_t TwoFishEncryptRaw(u_int8_t *in,u_int8_t *out,u_int32_t len,TWOFISH *tfdata);
/* TwoFish Raw Decryption
*
* Does not use header, but does use CBC (if more than one block has to be decrypted).
*
* Input: Pointer to the buffer of the ciphertext to be decrypted.
* Pointer to the buffer receiving the plaintext.
* The length of the ciphertext buffer (at least one cipher block).
* The TwoFish structure.
*
* Output: The amount of bytes decrypted if successful, otherwise 0.
*/
u_int32_t TwoFishDecryptRaw(u_int8_t *in,u_int8_t *out,u_int32_t len,TWOFISH *tfdata);
/* TwoFish Encryption
*
* Uses header and CBC. If the output area has not been intialized with TwoFishAlloc,
* this routine will alloc the memory. In addition, it will include a small 'header'
* containing the magic and some salt. That way the decrypt routine can check if the
* packet got decrypted successfully, and return 0 instead of garbage.
*
* Input: Pointer to the buffer of the plaintext to be encrypted.
* Pointer to the pointer to the buffer receiving the ciphertext.
* The pointer either points to user allocated output buffer space, or to NULL, in which case
* this routine will set the pointer to the buffer allocated through the struct.
* The length of the plaintext buffer.
* Can be -1 if the input is a null terminated string, in which case we'll count for you.
* Boolean flag for BinHex Output (if used, output will be twice as large as input).
* Note: BinHex conversion overwrites (converts) input buffer!
* The TwoFish structure.
*
* Output: The amount of bytes encrypted if successful, otherwise 0.
*/
u_int32_t TwoFishEncrypt(u_int8_t *in,u_int8_t **out,signed long len,bool binhex,TWOFISH *tfdata);
/* TwoFish Decryption
*
* Uses header and CBC. If the output area has not been intialized with TwoFishAlloc,
* this routine will alloc the memory. In addition, it will check the small 'header'
* containing the magic. If magic does not match we return 0. Otherwise we return the
* amount of bytes decrypted (should be the same as the length in the header).
*
* Input: Pointer to the buffer of the ciphertext to be decrypted.
* Pointer to the pointer to the buffer receiving the plaintext.
* The pointer either points to user allocated output buffer space, or to NULL, in which case
* this routine will set the pointer to the buffer allocated through the struct.
* The length of the ciphertext buffer.
* Can be -1 if the input is a null terminated binhex string, in which case we'll count for you.
* Boolean flag for BinHex Input (if used, plaintext will be half as large as input).
* Note: BinHex conversion overwrites (converts) input buffer!
* The TwoFish structure.
*
* Output: The amount of bytes decrypted if successful, otherwise 0.
*/
u_int32_t TwoFishDecrypt(u_int8_t *in,u_int8_t **out,signed long len,bool binhex,TWOFISH *tfdata);
/**** Private Functions ****/
u_int8_t TwoFish__b(u_int32_t x,int n);
void _TwoFish_BinHex(u_int8_t *buf,u_int32_t len,bool bintohex);
u_int32_t _TwoFish_CryptRawCBC(u_int8_t *in,u_int8_t *out,u_int32_t len,bool decrypt,TWOFISH *tfdata);
u_int32_t _TwoFish_CryptRaw16(u_int8_t *in,u_int8_t *out,u_int32_t len,bool decrypt,TWOFISH *tfdata);
u_int32_t _TwoFish_CryptRaw(u_int8_t *in,u_int8_t *out,u_int32_t len,bool decrypt,TWOFISH *tfdata);
void _TwoFish_PrecomputeMDSmatrix(void);
void _TwoFish_MakeSubKeys(TWOFISH *tfdata);
void _TwoFish_qBlockPush(u_int8_t *p,u_int8_t *c,TWOFISH *tfdata);
void _TwoFish_qBlockPop(u_int8_t *p,u_int8_t *c,TWOFISH *tfdata);
void _TwoFish_ResetCBC(TWOFISH *tfdata);
void _TwoFish_FlushOutput(u_int8_t *b,u_int32_t len,TWOFISH *tfdata);
void _TwoFish_BlockCrypt(u_int8_t *in,u_int8_t *out,u_int32_t size,int decrypt,TWOFISH *tfdata);
void _TwoFish_BlockCrypt16(u_int8_t *in,u_int8_t *out,bool decrypt,TWOFISH *tfdata);
u_int32_t _TwoFish_RS_MDS_Encode(u_int32_t k0,u_int32_t k1);
u_int32_t _TwoFish_F32(u_int32_t k64Cnt,u_int32_t x,u_int32_t *k32);
u_int32_t _TwoFish_Fe320(u_int32_t *lsBox,u_int32_t x);
u_int32_t _TwoFish_Fe323(u_int32_t *lsBox,u_int32_t x);
u_int32_t _TwoFish_Fe32(u_int32_t *lsBox,u_int32_t x,u_int32_t R);
#endif