Merge pull request #3 from ntop/master

sync n2n
This commit is contained in:
switch 2018-06-19 18:29:41 +08:00 committed by GitHub
commit d89c60d8b6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
181 changed files with 20695 additions and 315 deletions

View File

@ -28,10 +28,6 @@ endif(NOT DEFINED CMAKE_BUILD_TYPE)
#set(CMAKE_BUILD_TYPE Debug) #set(CMAKE_BUILD_TYPE Debug)
#set(CMAKE_BUILD_TYPE Release) #set(CMAKE_BUILD_TYPE Release)
#Ultrasparc64 users experiencing SIGBUS should try the following gcc options
#(thanks to Robert Gibbon)
#PLATOPTS_SPARC64=-mcpu=ultrasparc -pipe -fomit-frame-pointer -ffast-math -finline-functions -fweb -frename-registers -mapp-regs
# None # None
set(CMAKE_C_FLAGS "-Wall -Wshadow -Wpointer-arith -Wmissing-declarations -Wnested-externs") set(CMAKE_C_FLAGS "-Wall -Wshadow -Wpointer-arith -Wmissing-declarations -Wnested-externs")
set(CMAKE_CXX_FLAGS "-Wall -Wshadow -Wpointer-arith -Wmissing-declarations -Wnested-externs") set(CMAKE_CXX_FLAGS "-Wall -Wshadow -Wpointer-arith -Wmissing-declarations -Wnested-externs")
@ -51,6 +47,7 @@ set(CMAKE_CXX_FLAGS_RELEASE "-O2 -DNDEBUG")
add_library(n2n n2n.c add_library(n2n n2n.c
n2n_keyfile.c n2n_keyfile.c
edge_utils.c
wire.c wire.c
minilzo.c minilzo.c
twofish.c twofish.c
@ -73,9 +70,6 @@ if(N2N_OPTION_AES)
target_link_libraries(n2n crypto) target_link_libraries(n2n crypto)
endif(N2N_OPTION_AES) endif(N2N_OPTION_AES)
# For Solaris (or OpenSolaris?)
#target_link_libraries(n2n socket nsl)
add_executable(edge edge.c) add_executable(edge edge.c)
target_link_libraries(edge n2n) target_link_libraries(edge n2n)

View File

@ -64,7 +64,7 @@ APPS+=example_edge_embed
DOCS=edge.8.gz supernode.1.gz n2n_v2.7.gz DOCS=edge.8.gz supernode.1.gz n2n_v2.7.gz
all: $(APPS) $(DOCS) all: $(APPS) $(DOCS) benchmark
edge: edge.c $(N2N_LIB) n2n_wire.h n2n.h Makefile edge: edge.c $(N2N_LIB) n2n_wire.h n2n.h Makefile
$(CC) $(CFLAGS) edge.c $(N2N_LIB) $(LIBS_EDGE) -o edge $(CC) $(CFLAGS) edge.c $(N2N_LIB) $(LIBS_EDGE) -o edge

15
android/Hin2n/.gitignore vendored Normal file
View File

@ -0,0 +1,15 @@
.idea
*.iml
*.ipr
*.iws
/.idea/workspace.xml
/.idea/libraries
.gradle
/local.properties
reports
/captures
jacoco.exec
.DS_Store
/build
.externalNativeBuild
/app/Hin2n.jks

674
android/Hin2n/LICENSE 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:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<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>.

67
android/Hin2n/README.md Normal file
View File

@ -0,0 +1,67 @@
# n2n_vLTS
[README](README.md) | [中文文档](README_zh.md)
N2N is a VPN project that supports p2p. It was originally developed and open sourced by `Luca Deri` <deri@ntop.org>, `Richard Andrews` <andrews@ntop.org> of ntop.org, and `Meyerd` <https://github.com/meyerd> continues to do optimization work. Our goal is to continuously optimize n2n based on several masters and provide `mobile version` support.
## Hin2n
The original n2n supports many platforms, including windows, linux, osx, bsd, openwrt, raspberry pie, etc., except for mobile phones(non-root). Therefore, we have developed the Hin2n project.
### What is Hin2n
- Hin2n is a mobile VPN app that supports the n2n protocol
- Hin2n does not need a rooted phone
- Hin2n only supports Android phones for now, IPhone version will be developed in the future
- Hin2n is currently in continuous development and will gradually provide more complete versions
- Hin2n only supports [n2n_v2s](#About v2s version) protocol now, other versions of n2n protocol are under development
### Hin2n latest version [CHANGELOG](Hin2n_android/CHANGELOG)
The latest version of Hin2n is available for download at [release link](https://github.com/switch-iot/n2n_vLTS/releases).
### Hin2n Development Plan
View the development plan at [`Projects`](https://github.com/switch-iot/n2n_vLTS/projects).
If you have new features and ideas, you can submit them in [`issues`](https://github.com/switch-iot/n2n_vLTS/issues), and we will arrange development plans as appropriate. Your concern is our motivation.
### Technical principle
- VPNService
> Hin2n is based on Android's native VPNService. It builds a tun virtual network card through VPNService and communicates with supernode and edges.
- tun2tap
> Android only supports tun virtual network card, only support network layer, and n2n requires tap virtual network card, which needs data link layer support. So we simulated the data link layer and ARP protocol.
- n2n protocol
> Hin2n supports the n2n protocol by using the native method of jni to reuse the code of the original n2n project as far as possible.
## N2N protocol version
There are three popular versions of the n2n project
- Version v1 developed by the great masters of ntop.org. Project addresshttps://github.com/meyerd/n2n.git(n2n_v1)
- Version v2 developed by the great masters of ntop.org. Project addresshttps://github.com/ntop/n2n.git
- Version [v2s](#About v2s version) developed by the master Meyerd. Project addresshttps://github.com/meyerd/n2n.git(n2n_v2)
### About v2s version
The v2s is the renaming of the v2 (also known as v2.1) developed by master Meyerd in the QQ group(256572040), that is, the v2 upgrade version. The v2s version is not compatible with the v2 version developed by the ntop.org masters. To avoid confusion, the QQ group friends named the project separately.
## Development and compilation
### Hin2n
- git clone https://github.com/switch-iot/n2n_vLTS.git `--recurse-submodules`
- The windows environment needs to execute `link.bat` in the project folder to replace symbolic links under Linux.
- Hin2n_android directory is the Hin2n project Android source directory
- Execute `gradlew assemble` in Hin2n_android directory to compile Hin2n
- The gradle version of the Hin2n_android project is 2.14.1. If you want to upgrade the gradle version to 4.4, copy the file under the branch `dev_android_gradle4.4` to the branch `marster`/`dev_android` to overwrite the corresponding files.
### About open source agreement
The project is open sourced under the [`GPLv3`](LICENSE) agreement, and is consistent with the original open source agreement of n2n. We also hope that everyone will support and comply with the open source agreement of this project.
## Contribute to Hin2n
Hin2n is a free and open source n2n project, and we welcome anyone to contribute to it.
- Any problems in use can be fed back through ['issues'](https://github.com/switch-iot/n2n_vLTS/issues)
- Bug fixes can submit `Pull Request` to `android_dev` branch
- If you want to add a new feature, please create an [`issues`](https://github.com/switch-iot/n2n_vLTS/issues) first to describe the new feature, as well as the implementation approach. Once a proposal is accepted, create an implementation of the new features and submit it as a pull request.
- Sorry for my poor english and improvement for this document is welcome even some typo fix.
- Welcome to pay attention to the project and give the project a `Star`
### Contributors
- [`lucktu`](https://github.com/lucktu) is the initiator of the Hin2n project and plays a crucial role in the project. We thank [`lucktu`](https://github.com/lucktu) for organizing, promoting and testing for the project.
- [`zhangbz`](https://github.com/zhangbz) is mainly responsible for the development of the Android level, and has given strong support in the most difficult time of the project. The participation of [`zhangbz`](https://github.com/zhangbz) has enabled the project to continue.
- At the same time, thank all the friends for their support
## QQ group
- Hin2n QQ group 769731491
- N2N QQ group 256572040

View File

@ -0,0 +1,67 @@
# n2n_vLTS
[README](README.md) | [中文文档](README_zh.md)
n2n是一个支持内网穿透p2p的VPN项目最初由ntop.org大神`Luca Deri` <deri@ntop.org>, `Richard Andrews` <andrews@ntop.org>开发并开源的项目,后由`meyerd`大神 <https://github.com/meyerd>继续做优化工作。我们的目的是在几位大神的基础上做持续优化并提供`手机版本`的支持。
## Hin2n
原版的n2n支持很多平台包括windowslinuxosxbsdopenwrtraspberry pie等唯独缺少对手机(非root)的支持。因此我们开发了Hin2n项目。
### Hin2n是什么
- Hin2n是支持n2n协议的手机VPN软件
- 该APP不需要root手机
- 该APP暂时只支持安卓手机后续会发开IPhone版本
- 该项目现处于持续开发阶段,仅支持基本的配置连接功能,后续会提供更完善的功能
- 该项目现只支持[n2n_v2s](#关于v2s版本)协议其他版本的n2n协议正在开发中
### Hin2n最新版本 [CHANGELOG](Hin2n_android/CHANGELOG_zh)
Hin2n最新版本可在[release地址](https://github.com/switch-iot/n2n_vLTS/releases)查看下载。
### Hin2n开发计划
详细开发计划请见[`Projects`](https://github.com/switch-iot/n2n_vLTS/projects)。
大家如果有新需求和想法,任何意见建议均可提交在[`issues`](https://github.com/switch-iot/n2n_vLTS/issues)中,我们将会酌情安排开发计划。您的关注就是我们的动力。
### 技术原理
- VPNService
> Hin2n基于安卓原生提供的VPNService通过VPNService建立tun虚拟网卡与supernode和edge通讯。
- tun2tap
> 安卓上层仅支持建立tun虚拟网卡仅是TCP/IP网络层而n2n协议依赖tap虚拟网卡需要对数据链路层的支持因此我们模拟了数据链路层并实现了ARP协议。
- n2n protocol
> Hin2n对n2n协议的支持是采用jni的方式native方法可以尽量复用原n2n项目的代码。
## n2n协议版本
n2n项目现有三个主流版本
- ntop.org大神们维护的v1版本项目地址https://github.com/meyerd/n2n.git(n2n_v1)
- ntop.org大神们维护的v2版本项目地址https://github.com/ntop/n2n.git
- meyerd大神维护的[v2s版本](#关于v2s版本)项目地址https://github.com/meyerd/n2n.git(n2n_v2)
### 关于v2s版本
v2s版本是N2N交流QQ群(256572040)中对meyerd大神维护的v2版本(又称v2.1)的命名即v2升级版该版本与ntop.org大神们维护的v2版本并不互通为避免混淆群友们对该项目另行命名。
## 项目开发/编译说明
### Hin2n
- git clone https://github.com/switch-iot/n2n_vLTS.git `--recurse-submodules`
- windows环境下需要在项目文件夹下执行`link.bat`用于替换linux下的符号链接
- Hin2n_android目录即是Hin2n项目安卓源码目录
- Hin2n_android目录下执行`gradlew assemble`编译
- Hin2n_android项目的gradle是2.14.1版本如需4.4版本的gradle请将分支`dev_android_gradle4.4`下的文件拷贝至分支`marster`/`dev_android`下,覆盖相应的文件
### 关于开源协议
该项目以[`GPLv3`](LICENSE)协议进行开源与n2n原有开源协议保持一致也希望大家支持并遵守本项目的开源协议。
## 为Hin2n做贡献
Hin2n是一个免费且开源的n2n项目我们欢迎任何人为其开发和进步贡献力量。
- 在使用过程中出现任何问题,可以通过[`issues`](https://github.com/switch-iot/n2n_vLTS/issues) 来反馈
- Bug的修复可以直接提交`Pull Request`到`android_dev`分支
- 如果是增加新的功能特性,请先创建一个[`issues`](https://github.com/switch-iot/n2n_vLTS/issues)并做简单描述以及大致的实现方法,提议被采纳后,就可以创建一个实现新特性的 Pull Request
- 欢迎对说明文档做出改善,帮助更多的人使用`Hin2n`,特别是英文文档
- 如果您觉得Hin2n对您有帮助欢迎您关注该项目并给项目点个`Star`
### 贡献者
- [`lucktu`](https://github.com/lucktu)是Hin2n项目的发起人对该项目起到至关重要的作用感谢[`lucktu`](https://github.com/lucktu)对该项目的组织、推广、测试等工作
- [`zhangbz`](https://github.com/zhangbz)主要负责Android层面的开发在项目最困难的时候给予了强有力的支持[`zhangbz`](https://github.com/zhangbz)的参与,使得该项目得以继续
- 同时也感谢广大群友对我们的支持
## 交流群
- Hin2n交流群 769731491(QQ群号)
- N2N交流群 256572040(QQ群号)

View File

@ -0,0 +1,15 @@
.idea
*.iml
*.ipr
*.iws
/.idea/workspace.xml
/.idea/libraries
.gradle
/local.properties
reports
/captures
jacoco.exec
.DS_Store
/build
.externalNativeBuild
/app/Hin2n.jks

View File

@ -0,0 +1 @@
/build

View File

@ -0,0 +1,160 @@
apply plugin: 'org.greenrobot.greendao'
apply plugin: 'com.android.application'
def getVersionCode = { ->
try {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'rev-list', '--all', '--count'
standardOutput = stdout
}
return Integer.parseInt(stdout.toString().trim())
}
catch (ignored) {
return -1;
}
}
def getVersionName = { ->
def ver = 'v0.5.2'
return ver;
try {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'describe', '--tags', '--always', '--dirty', '--match', 'hin2n_v*'
standardOutput = stdout
}
return stdout.toString().trim()
}
catch (ignored) {
return null;
}
}
def getEnvOrConsole = { env, prompt ->
def val = null
try {
val = System.getenv(env)
if (val == null || val == "") {
if (System.console() != null) {
val = System.console().readLine("\n" + prompt + ": ")
}
}
} catch (ignored) {
return null
}
return val
}
android {
compileSdkVersion 25
buildToolsVersion '27.0.3'
defaultConfig {
applicationId "wang.switchy.hin2n"
minSdkVersion 14
targetSdkVersion 25
versionCode getVersionCode()
versionName getVersionName()
multiDexEnabled true
manifestPlaceholders = [CHANNEL_VALUE: "normal", ARCH: "all"]
resConfigs "en", "zh-rCN", "zh-rTW"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags ""
}
}
}
signingConfigs {
debug {}
release {
storeFile file("Hin2n.jks")
storePassword getEnvOrConsole("HIN2N_KSTOREPWD", "Keystore password")
keyAlias "Hin2n"
keyPassword getEnvOrConsole("HIN2N_KEYPWD", "Key password")
}
}
buildTypes {
debug {
buildConfigField("boolean", "API_DEBUG", "true")
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
release {
buildConfigField("boolean", "API_DEBUG", "false")
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
applicationVariants.all { variant ->
variant.outputs.all { output ->
def outputFile = output.outputFile
def fileName = null
if (outputFile != null && outputFile.name.endsWith('.apk')) {
variant.mergedFlavor.versionName = getVersionName()
def channel = variant.mergedFlavor.manifestPlaceholders.CHANNEL_VALUE
def arch = variant.mergedFlavor.manifestPlaceholders.ARCH
fileName = "hin2n_${variant.mergedFlavor.versionName}_${channel}_${arch}_${variant.buildType.name}.apk"
outputFileName = fileName
}
}
}
flavorDimensions "channel", "arch"
productFlavors {
normal {
dimension "channel"
manifestPlaceholders += [CHANNEL_VALUE: "normal"]
}
arm {
dimension "arch"
ndk {
abiFilters "armeabi-v7a", "arm64-v8a"
manifestPlaceholders += [ARCH: "arm"]
}
}
x86 {
dimension "arch"
ndk {
abiFilters "x86", "x86_64"
manifestPlaceholders += [ARCH: "x86"]
}
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
}
greendao {
schemaVersion 1
daoPackage 'wang.switchy.hin2n.storage.db.base'
targetGenDir 'src/main/java'
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
implementation 'com.android.support:design:25.4.0'
testImplementation 'junit:junit:4.12'
implementation 'com.android.support:appcompat-v7:25.+'
implementation 'org.greenrobot:eventbus:3.1.1'
implementation 'org.greenrobot:greendao:3.2.0'
}

View File

@ -0,0 +1,17 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in D:\Users\janiszhang\AppData\Local\Android\sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

View File

@ -0,0 +1,27 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.3'
classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
mavenCentral()
google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

View File

@ -0,0 +1,19 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
org.gradle.daemon=true

View File

@ -0,0 +1,6 @@
#Wed Apr 18 23:44:31 CST 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

View File

@ -0,0 +1,160 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

View File

@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1 @@
include ':app'

1
android/Hin2n/app/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/build

View File

@ -0,0 +1,56 @@
project(Hin2n)
cmake_minimum_required(VERSION 3.4.1)
# N2n information
set(N2N_VERSION 2.1.0)
set(N2N_OSNAME ${CMAKE_SYSTEM})
INCLUDE(TestBigEndian)
TEST_BIG_ENDIAN(UIP_CONF_BYTE_ORDER)
if(${UIP_CONF_BYTE_ORDER} EQUAL 1)
set(UIP_CONF_BYTE_ORDER UIP_BIG_ENDIAN)
else(${UIP_CONF_BYTE_ORDER} EQUAL 1)
set(UIP_CONF_BYTE_ORDER UIP_LITTLE_ENDIAN)
endif(${UIP_CONF_BYTE_ORDER} EQUAL 1)
if(CMAKE_BUILD_TYPE)
if(NOT ${CMAKE_BUILD_TYPE} STREQUAL Debug)
set(CMAKE_BUILD_TYPE Release)
endif(NOT ${CMAKE_BUILD_TYPE} STREQUAL Debug)
else(CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif(CMAKE_BUILD_TYPE)
add_definitions(-DN2N_VERSION=\"${N2N_VERSION}\" -DN2N_OSNAME=\"${N2N_OSNAME}\" -DUIP_CONF_BYTE_ORDER=\"${UIP_CONF_BYTE_ORDER}\")
include_directories(src/main/cpp src/main/cpp/tun2tap src/main/cpp/uip)
add_library(edge SHARED
src/main/cpp/n2n/android/edge_jni.c
src/main/cpp/n2n/android/edge_android.c
)
target_link_libraries(edge n2n)
target_link_libraries(edge log)
add_library(n2n SHARED
src/main/cpp/n2n/n2n.c
src/main/cpp/n2n/n2n_keyfile.c
src/main/cpp/n2n/wire.c
src/main/cpp/n2n/minilzo.c
src/main/cpp/n2n/twofish.c
src/main/cpp/n2n/edge_utils.c
src/main/cpp/n2n/transform_null.c
src/main/cpp/n2n/transform_tf.c
src/main/cpp/n2n/transform_aes.c
src/main/cpp/n2n/android/tuntap_android.c
src/main/cpp/n2n/version.c
)
target_link_libraries(n2n uip)
target_link_libraries(n2n log)
add_library(uip SHARED
src/main/cpp/uip/uip.c
src/main/cpp/uip/uip_arp.c
src/main/cpp/tun2tap/tun2tap.c
)

View File

@ -0,0 +1,160 @@
apply plugin: 'org.greenrobot.greendao'
apply plugin: 'com.android.application'
def getVersionCode = { ->
try {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'rev-list', '--all', '--count'
standardOutput = stdout
}
return Integer.parseInt(stdout.toString().trim())
}
catch (ignored) {
return -1;
}
}
def getVersionName = { ->
def ver = 'v0.5.2'
return ver
try {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'describe', '--tags', '--always', '--dirty', '--match', 'hin2n_v*'
standardOutput = stdout
}
return stdout.toString().trim()
}
catch (ignored) {
return null
}
}
def getEnvOrConsole = { env, prompt ->
def val = null
try {
val = System.getenv(env)
if (val == null || val == "") {
if (System.console() != null) {
val = System.console().readLine("\n" + prompt + ": ")
}
}
} catch (ignored) {
return null
}
return val
}
android {
compileSdkVersion 25
buildToolsVersion '25.0.0'
defaultConfig {
applicationId "wang.switchy.hin2n"
minSdkVersion 14
targetSdkVersion 25
versionCode getVersionCode()
versionName getVersionName()
multiDexEnabled true
manifestPlaceholders = [CHANNEL_VALUE: "normal", ARCH: "all"]
resConfigs "en", "zh-rCN", "zh-rTW"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags ""
}
}
}
signingConfigs {
debug {}
release {
storeFile file("Hin2n.jks")
storePassword getEnvOrConsole("HIN2N_KSTOREPWD", "Keystore password")
keyAlias "Hin2n"
keyPassword getEnvOrConsole("HIN2N_KEYPWD", "Key password")
}
}
buildTypes {
debug {
buildConfigField("boolean", "API_DEBUG", "true")
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
release {
buildConfigField("boolean", "API_DEBUG", "false")
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
applicationVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
def fileName = null
if (outputFile != null && outputFile.name.endsWith('.apk')) {
variant.mergedFlavor.versionName = getVersionName()
def channel = variant.mergedFlavor.manifestPlaceholders.CHANNEL_VALUE
def arch = variant.mergedFlavor.manifestPlaceholders.ARCH
fileName = "hin2n_${variant.mergedFlavor.versionName}_${channel}_${arch}_${variant.buildType.name}.apk"
output.outputFile = new File(output.outputFile.parent, fileName)
}
}
}
flavorDimensions "channel", "arch"
productFlavors {
normal {
dimension "channel"
manifestPlaceholders += [CHANNEL_VALUE: "normal"]
}
arm {
dimension "arch"
ndk {
abiFilters "armeabi-v7a", "arm64-v8a"
manifestPlaceholders += [ARCH: "arm"]
}
}
x86 {
dimension "arch"
ndk {
abiFilters "x86", "x86_64"
manifestPlaceholders += [ARCH: "x86"]
}
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
}
greendao {
schemaVersion 1
daoPackage 'wang.switchy.hin2n.storage.db.base'
targetGenDir 'src/main/java'
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:design:25.2.0'
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:25.+'
compile 'org.greenrobot:eventbus:3.1.1'
compile 'org.greenrobot:greendao:3.2.0'
}

17
android/Hin2n/app/proguard-rules.pro vendored Normal file
View File

@ -0,0 +1,17 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in D:\Users\janiszhang\AppData\Local\Android\sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

View File

@ -0,0 +1,26 @@
package wang.switchy.hin2n;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.n2n.hin2n", appContext.getPackageName());
}
}

View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="wang.switchy.hin2n">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".Hin2nApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".activity.MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".activity.ListActivity"
android:screenOrientation="portrait"/>
<activity android:name=".activity.SettingDetailsActivity"
android:screenOrientation="portrait"/>
<service android:name=".service.N2NService"
android:permission="android.permission.BIND_VPN_SERVICE">
<intent-filter>
<action android:name="android.net.VpnService" />
</intent-filter>
</service>
</application>
</manifest>

View File

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

View File

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

View File

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

View File

@ -0,0 +1,56 @@
package wang.switchy.hin2n;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.multidex.MultiDexApplication;
import wang.switchy.hin2n.storage.db.base.DaoMaster;
import wang.switchy.hin2n.storage.db.base.DaoSession;
/**
* Created by janiszhang on 2018/4/19.
*/
public class Hin2nApplication extends MultiDexApplication {
public Context AppContext;
private DaoMaster.DevOpenHelper mHelper;
private SQLiteDatabase db;
private DaoMaster mDaoMaster;
private DaoSession mDaoSession;
public static Hin2nApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
AppContext = this;
setDatabase();
}
public static Hin2nApplication getInstance(){
return instance;
}
private void setDatabase() {
mHelper = new DaoMaster.DevOpenHelper(this, "N2N-db", null);
db = mHelper.getWritableDatabase();
mDaoMaster = new DaoMaster(db);
mDaoSession = mDaoMaster.newSession();
}
public DaoSession getDaoSession() {
return mDaoSession;
}
public SQLiteDatabase getDb() {
return db;
}
}

View File

@ -0,0 +1,59 @@
package wang.switchy.hin2n.activity;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import wang.switchy.hin2n.template.BaseTemplate;
/**
* Created by janiszhang on 2018/4/13.
*/
public abstract class BaseActivity extends AppCompatActivity {
protected Activity mContext;
protected View mContentView;
protected BaseTemplate mTemplate;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
mContext = this;
mTemplate = createTemplate();
if (mTemplate != null) {
if (getContentLayout() != 0) {
mContentView = LayoutInflater.from(mContext).inflate(getContentLayout(), null);
mTemplate.setContentView(mContentView);
}
setContentView(mTemplate.getPageView());
}
doOnCreate(savedInstanceState);
}
protected abstract BaseTemplate createTemplate();
protected abstract void doOnCreate(Bundle savedInstanceState);
protected abstract int getContentLayout();
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
}

View File

@ -0,0 +1,166 @@
package wang.switchy.hin2n.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import wang.switchy.hin2n.Hin2nApplication;
import wang.switchy.hin2n.service.N2NService;
import wang.switchy.hin2n.R;
import wang.switchy.hin2n.adapter.SettingItemAdapter;
import wang.switchy.hin2n.entity.SettingItemEntity;
import wang.switchy.hin2n.model.N2NSettingInfo;
import wang.switchy.hin2n.storage.db.base.N2NSettingModelDao;
import wang.switchy.hin2n.storage.db.base.model.N2NSettingModel;
import wang.switchy.hin2n.template.BaseTemplate;
import wang.switchy.hin2n.template.CommonTitleTemplate;
/**
* Created by janiszhang on 2018/5/4.
*/
public class ListActivity extends BaseActivity {
private ListView mSettingsListView;
private SettingItemAdapter mSettingItemAdapter;
private ArrayList<SettingItemEntity> mSettingItemEntities;
private SharedPreferences mHin2nSp;
private SharedPreferences.Editor mHin2nEdit;
private TextView mMoreInfo;
private N2NSettingModel mN2NSettingModel;
@Override
protected BaseTemplate createTemplate() {
CommonTitleTemplate titleTemplate = new CommonTitleTemplate(mContext, "Setting List");
titleTemplate.mRightImg.setVisibility(View.VISIBLE);
titleTemplate.mRightImg.setImageResource(R.mipmap.img_add);
titleTemplate.mRightImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(ListActivity.this, SettingDetailsActivity.class);
intent.putExtra("type", SettingDetailsActivity.TYPE_SETTING_ADD);
startActivity(intent);
}
});
titleTemplate.mLeftImg.setVisibility(View.VISIBLE);
titleTemplate.mLeftImg.setImageResource(R.drawable.titlebar_icon_return_selector);
titleTemplate.mLeftImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
return titleTemplate;
}
@Override
protected void doOnCreate(Bundle savedInstanceState) {
mHin2nSp = getSharedPreferences("Hin2n", MODE_PRIVATE);
mHin2nEdit = mHin2nSp.edit();
mSettingsListView = (ListView) findViewById(R.id.lv_setting_item);
mSettingItemEntities = new ArrayList<>();
mSettingItemAdapter = new SettingItemAdapter(this, mSettingItemEntities);
mSettingsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Long currentSettingId = mHin2nSp.getLong("current_setting_id", -1);
if (currentSettingId != -1) {
N2NSettingModel currentSettingItem = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao().load((long) currentSettingId);
if (currentSettingItem != null) {
currentSettingItem.setIsSelcected(false);
Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao().update(currentSettingItem);
}
}
for (int i = 0; i < mSettingItemEntities.size(); i++) {
mSettingItemEntities.get(i).setSelected(false);
}
mSettingItemAdapter.notifyDataSetChanged();
N2NSettingModelDao n2NSettingModelDao = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao();
mN2NSettingModel = n2NSettingModelDao.load(mSettingItemEntities.get(position).getSaveId());
mN2NSettingModel.setIsSelcected(true);
n2NSettingModelDao.update(mN2NSettingModel);
mHin2nEdit.putLong("current_setting_id", mN2NSettingModel.getId());
mHin2nEdit.commit();
mSettingItemEntities.get(position).setSelected(true);
mSettingItemAdapter.notifyDataSetChanged();
}
});
mSettingsListView.setAdapter(mSettingItemAdapter);
}
@Override
protected void onResume() {
super.onResume();
N2NSettingModelDao n2NSettingModelDao = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao();
List<N2NSettingModel> n2NSettingModels = n2NSettingModelDao.loadAll();
N2NSettingModel n2NSettingModel;
mSettingItemEntities.clear();
for (int i = 0; i < n2NSettingModels.size(); i++) {
n2NSettingModel = n2NSettingModels.get(i);
final SettingItemEntity settingItemEntity = new SettingItemEntity(n2NSettingModel.getName(),
n2NSettingModel.getId(), n2NSettingModel.getIsSelcected());
settingItemEntity.setOnMoreBtnClickListener(new SettingItemEntity.OnMoreBtnClickListener() {
@Override
public void onClick() {
Intent intent = new Intent(ListActivity.this, SettingDetailsActivity.class);
intent.putExtra("type", SettingDetailsActivity.TYPE_SETTING_MODIFY);
intent.putExtra("saveId", settingItemEntity.getSaveId());
startActivity(intent);
}
});
mSettingItemEntities.add(settingItemEntity);
}
mSettingItemAdapter.notifyDataSetChanged();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK) {
Intent intent = new Intent(ListActivity.this, N2NService.class);
Bundle bundle = new Bundle();
N2NSettingInfo n2NSettingInfo = new N2NSettingInfo(mN2NSettingModel);
bundle.putParcelable("n2nSettingInfo", n2NSettingInfo);
intent.putExtra("Setting", bundle);
startService(intent);
}
}
@Override
protected int getContentLayout() {
return R.layout.activity_setting_list;
}
}

View File

@ -0,0 +1,187 @@
package wang.switchy.hin2n.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.VpnService;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import wang.switchy.hin2n.Hin2nApplication;
import wang.switchy.hin2n.service.N2NService;
import wang.switchy.hin2n.R;
import wang.switchy.hin2n.event.ErrorEvent;
import wang.switchy.hin2n.event.StartEvent;
import wang.switchy.hin2n.event.StopEvent;
import wang.switchy.hin2n.model.N2NSettingInfo;
import wang.switchy.hin2n.storage.db.base.model.N2NSettingModel;
import wang.switchy.hin2n.template.BaseTemplate;
import wang.switchy.hin2n.template.CommonTitleTemplate;
public class MainActivity extends BaseActivity {
private Button mActionBtn;
static {
System.loadLibrary("uip");
System.loadLibrary("n2n");
System.loadLibrary("edge");
}
private N2NSettingModel mCurrentSettingInfo;
private RelativeLayout mCurrentSettingItem;
private TextView mCurrentSettingName;
@Override
protected BaseTemplate createTemplate() {
CommonTitleTemplate titleTemplate = new CommonTitleTemplate(this, "Hin2n");
titleTemplate.mRightImg.setImageResource(R.mipmap.img_add);
titleTemplate.mRightImg.setVisibility(View.VISIBLE);
titleTemplate.mRightImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, SettingDetailsActivity.class);
intent.putExtra("type", SettingDetailsActivity.TYPE_SETTING_ADD);
startActivity(intent);
}
});
return titleTemplate;
}
@Override
protected void doOnCreate(Bundle savedInstanceState) {
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
mCurrentSettingItem = (RelativeLayout) findViewById(R.id.rl_current_setting_item);
mCurrentSettingItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (N2NService.INSTANCE != null && N2NService.INSTANCE.getEdgeStatus().isRunning) {
Toast.makeText(mContext, "~Running~", Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(MainActivity.this, ListActivity.class));
}
}
});
mCurrentSettingName = (TextView) findViewById(R.id.tv_current_setting_name);
mActionBtn = (Button) findViewById(R.id.btn_action);
if (N2NService.INSTANCE == null) {
mActionBtn.setText("start");
} else {
if (N2NService.INSTANCE.getEdgeStatus().isRunning) {
mActionBtn.setText("stop");
} else {
mActionBtn.setText("start");
}
}
mActionBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mCurrentSettingName.getText().equals("--null--")) {
Toast.makeText(mContext, "null setting", Toast.LENGTH_SHORT).show();
return;
}
if (N2NService.INSTANCE != null && N2NService.INSTANCE.getEdgeStatus().isRunning) {
N2NService.INSTANCE.stop();
} else {
Intent vpnPrepareIntent = VpnService.prepare(MainActivity.this);
if (vpnPrepareIntent != null) {
startActivityForResult(vpnPrepareIntent, 100);
} else {
onActivityResult(100, RESULT_OK, null);
}
}
}
});
}
@Override
protected int getContentLayout() {
return R.layout.activity_main;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK) {
Intent intent = new Intent(MainActivity.this, N2NService.class);
Bundle bundle = new Bundle();
N2NSettingInfo n2NSettingInfo = new N2NSettingInfo(mCurrentSettingInfo);
bundle.putParcelable("n2nSettingInfo", n2NSettingInfo);
intent.putExtra("Setting", bundle);
startService(intent);
}
}
@Override
protected void onResume() {
super.onResume();
SharedPreferences n2nSp = getSharedPreferences("Hin2n", MODE_PRIVATE);
Long currentSettingId = n2nSp.getLong("current_setting_id", -1);
if (currentSettingId != -1) {
mCurrentSettingInfo = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao().load((long) currentSettingId);
if (mCurrentSettingInfo != null) {
mCurrentSettingName.setText(mCurrentSettingInfo.getName());
} else {
mCurrentSettingName.setText("--null--");
}
}
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().unregister(this);
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onStartEvent(StartEvent event) {
mActionBtn.setText("stop");
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onStopEvent(StopEvent event) {
mActionBtn.setText("start");
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onErrorEvent(ErrorEvent event) {
mActionBtn.setText("start");
Toast.makeText(mContext, "~_~Error~_~", Toast.LENGTH_SHORT).show();
}
}

View File

@ -0,0 +1,543 @@
package wang.switchy.hin2n.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.VpnService;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import wang.switchy.hin2n.Hin2nApplication;
import wang.switchy.hin2n.service.N2NService;
import wang.switchy.hin2n.R;
import wang.switchy.hin2n.model.EdgeCmd;
import wang.switchy.hin2n.model.N2NSettingInfo;
import wang.switchy.hin2n.storage.db.base.N2NSettingModelDao;
import wang.switchy.hin2n.storage.db.base.model.N2NSettingModel;
import wang.switchy.hin2n.template.BaseTemplate;
import wang.switchy.hin2n.template.CommonTitleTemplate;
/**
* Created by janiszhang on 2018/5/4.
*/
public class SettingDetailsActivity extends BaseActivity implements View.OnClickListener {
public static int TYPE_SETTING_ADD = 0;
public static int TYPE_SETTING_MODIFY = 1;
private int type = TYPE_SETTING_ADD;
private TextInputLayout mIpAddressTIL;
private TextInputLayout mNetMaskTIL;
private TextInputLayout mCommunityTIL;
private TextInputLayout mEncryptTIL;
private TextInputLayout mSuperNodeTIL;
private Button mSaveBtn;
private SharedPreferences mHin2nSp;
private SharedPreferences.Editor mHin2nEdit;
private TextInputLayout mSettingName;
private CheckBox mSaveAndSetCheckBox;
private TextInputLayout mSuperNodeBackup;
private TextInputLayout mMacAddr;
private TextInputLayout mMtu;
private CheckBox mResoveSupernodeIPCheckBox;
private TextInputLayout mLocalPort;
private CheckBox mAllowRoutinCheckBox;
private CheckBox mDropMuticastCheckBox;
private Spinner mTraceLevelSpinner;
private CheckBox mMoreSettingCheckBox;
private RelativeLayout mMoreSettingView;
private N2NSettingModel mN2NSettingModel;
private Button mModifyBtn;
private LinearLayout mButtons;
private Button mDeleteBtn;
private long mSaveId;
private ArrayList<String> mTraceLevelList;
@Override
protected BaseTemplate createTemplate() {
CommonTitleTemplate titleTemplate = new CommonTitleTemplate(mContext, "Add New Setting");
titleTemplate.mLeftImg.setVisibility(View.VISIBLE);
titleTemplate.mLeftImg.setImageResource(R.drawable.titlebar_icon_return_selector);
titleTemplate.mLeftImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
return titleTemplate;
}
@Override
protected void doOnCreate(Bundle savedInstanceState) {
mHin2nSp = getSharedPreferences("Hin2n", MODE_PRIVATE);
mHin2nEdit = mHin2nSp.edit();
mSettingName = (TextInputLayout) findViewById(R.id.til_setting_name);
mIpAddressTIL = (TextInputLayout) findViewById(R.id.til_ip_address);
mNetMaskTIL = (TextInputLayout) findViewById(R.id.til_net_mask);
mCommunityTIL = (TextInputLayout) findViewById(R.id.til_community);
mEncryptTIL = (TextInputLayout) findViewById(R.id.til_encrypt);
mEncryptTIL.getEditText().setTransformationMethod(PasswordTransformationMethod.getInstance());//隐藏
mSuperNodeTIL = (TextInputLayout) findViewById(R.id.til_super_node);
mMoreSettingView = (RelativeLayout) findViewById(R.id.rl_more_setting);
mMoreSettingCheckBox = (CheckBox) findViewById(R.id.more_setting_check_box);
mMoreSettingCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
mMoreSettingView.setVisibility(View.VISIBLE);
} else {
mMoreSettingView.setVisibility(View.GONE);
}
}
});
mSuperNodeBackup = (TextInputLayout) findViewById(R.id.til_super_node_2);
mMacAddr = (TextInputLayout) findViewById(R.id.til_mac_addr);
mMtu = (TextInputLayout) findViewById(R.id.til_mtu);
mResoveSupernodeIPCheckBox = (CheckBox) findViewById(R.id.resove_super_node_ip_check_box);
mLocalPort = (TextInputLayout) findViewById(R.id.til_local_port);
mAllowRoutinCheckBox = (CheckBox) findViewById(R.id.allow_routing_check_box);
mDropMuticastCheckBox = (CheckBox) findViewById(R.id.drop_muticast_check_box);
mTraceLevelSpinner = (Spinner) findViewById(R.id.spinner_trace_level);
mTraceLevelList = new ArrayList<>();
// 0ERROR, 1: WARNING, 2: NORMAL, 3: INFO, 4: DEBUG
mTraceLevelList.add("ERROR");
mTraceLevelList.add("WARNING");
mTraceLevelList.add("NORMAL");
mTraceLevelList.add("INFO");
mTraceLevelList.add("DEBUG");
final ArrayAdapter<String> traceLevelAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mTraceLevelList);
traceLevelAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mTraceLevelSpinner.setAdapter(traceLevelAdapter);
mTraceLevelSpinner.setSelection(1);
mTraceLevelSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = traceLevelAdapter.getItem(position);
int selectedItemPosition = mTraceLevelSpinner.getSelectedItemPosition();
String traceLevel = mTraceLevelList.get(selectedItemPosition);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
mSaveAndSetCheckBox = (CheckBox) findViewById(R.id.check_box);
mSaveBtn = (Button) findViewById(R.id.btn_save);
mSaveBtn.setOnClickListener(this);
mButtons = (LinearLayout) findViewById(R.id.ll_buttons);
mModifyBtn = (Button) findViewById(R.id.btn_modify);
mModifyBtn.setOnClickListener(this);
mDeleteBtn = (Button) findViewById(R.id.btn_delete);
mDeleteBtn.setOnClickListener(this);
Intent intent = getIntent();
type = intent.getIntExtra("type", 0);
if (type == TYPE_SETTING_ADD) {
mMtu.getEditText().setText("1400");
mDropMuticastCheckBox.setChecked(true);
mTraceLevelSpinner.setSelection(1);
mSaveBtn.setVisibility(View.VISIBLE);
mButtons.setVisibility(View.GONE);
} else if (type == TYPE_SETTING_MODIFY) {
mSaveId = intent.getLongExtra("saveId", 0);
mN2NSettingModel = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao().load(mSaveId);
mSettingName.getEditText().setText(mN2NSettingModel.getName());
mIpAddressTIL.getEditText().setText(mN2NSettingModel.getIp());
mNetMaskTIL.getEditText().setText(mN2NSettingModel.getNetmask());
mCommunityTIL.getEditText().setText(mN2NSettingModel.getCommunity());
mEncryptTIL.getEditText().setText(mN2NSettingModel.getPassword());
mSuperNodeTIL.getEditText().setText(mN2NSettingModel.getSuperNode());
mSuperNodeBackup.getEditText().setText(mN2NSettingModel.getSuperNodeBackup());
mMacAddr.getEditText().setText(mN2NSettingModel.getMacAddr());
mMtu.getEditText().setText(String.valueOf(mN2NSettingModel.getMtu()));
mResoveSupernodeIPCheckBox.setChecked(mN2NSettingModel.getResoveSupernodeIP());
mLocalPort.getEditText().setText(String.valueOf(mN2NSettingModel.getLocalPort()));
mAllowRoutinCheckBox.setChecked(mN2NSettingModel.getAllowRouting());
mDropMuticastCheckBox.setChecked(mN2NSettingModel.getDropMuticast());
mTraceLevelSpinner.setSelection(Integer.valueOf(mN2NSettingModel.getTraceLevel()));
if (mN2NSettingModel.getMoreSettings()) {
mMoreSettingCheckBox.setChecked(true);
mMoreSettingView.setVisibility(View.VISIBLE);
} else {
mMoreSettingCheckBox.setChecked(false);
}
mButtons.setVisibility(View.VISIBLE);
mSaveBtn.setVisibility(View.GONE);
}
}
@Override
protected int getContentLayout() {
return R.layout.activity_add_item;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == -RESULT_OK) {
Intent intent = new Intent(SettingDetailsActivity.this, N2NService.class);
Bundle bundle = new Bundle();
N2NSettingInfo n2NSettingInfo = new N2NSettingInfo(mN2NSettingModel);
bundle.putParcelable("n2nSettingInfo", n2NSettingInfo);
intent.putExtra("Setting", bundle);
startService(intent);
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_save:
if (!checkValues()) {
return;
}
if (mSaveAndSetCheckBox.isChecked()) {
Long currentSettingId = mHin2nSp.getLong("current_setting_id", -1);
if (currentSettingId != -1) {
N2NSettingModel currentSettingItem = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao().load((long) currentSettingId);
if (currentSettingItem != null) {
currentSettingItem.setIsSelcected(false);
Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao().update(currentSettingItem);
}
}
N2NSettingModelDao n2NSettingModelDao = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao();
String settingName = mSettingName.getEditText().getText().toString();
String setingNameTmp = settingName;
int i = 0;
while (n2NSettingModelDao.queryBuilder().where(N2NSettingModelDao.Properties.Name.eq(settingName)).unique() != null) {
i++;
settingName = setingNameTmp + "(" + i + ")";
}
long id;
if (mMoreSettingCheckBox.isChecked()) {
mN2NSettingModel = new N2NSettingModel(null, settingName, mIpAddressTIL.getEditText().getText().toString(),
TextUtils.isEmpty(mNetMaskTIL.getEditText().getText()) ? "255.255.255.0" : mNetMaskTIL.getEditText().getText().toString(),
mCommunityTIL.getEditText().getText().toString(), mEncryptTIL.getEditText().getText().toString(),
mSuperNodeTIL.getEditText().getText().toString(), true, mSuperNodeBackup.getEditText().getText().toString(),
TextUtils.isEmpty(mMacAddr.getEditText().getText().toString()) ? EdgeCmd.getRandomMac() : mMacAddr.getEditText().getText().toString(),
TextUtils.isEmpty(mMtu.getEditText().getText().toString()) ? 1400 : Integer.valueOf(mMtu.getEditText().getText().toString()),
mResoveSupernodeIPCheckBox.isChecked(), TextUtils.isEmpty(mLocalPort.getEditText().getText().toString()) ? 0 : Integer.valueOf(mLocalPort.getEditText().getText().toString()),
mAllowRoutinCheckBox.isChecked(), mDropMuticastCheckBox.isChecked(), mTraceLevelSpinner.getSelectedItemPosition(), true);
id = n2NSettingModelDao.insert(mN2NSettingModel);
} else {
mN2NSettingModel = new N2NSettingModel(null, settingName, mIpAddressTIL.getEditText().getText().toString(),
TextUtils.isEmpty(mNetMaskTIL.getEditText().getText()) ? "255.255.255.0" : mNetMaskTIL.getEditText().getText().toString(),
mCommunityTIL.getEditText().getText().toString(), mEncryptTIL.getEditText().getText().toString(),
mSuperNodeTIL.getEditText().getText().toString(), false, "", EdgeCmd.getRandomMac(), 1400, false, 0, false, true, 1, true);
id = n2NSettingModelDao.insert(mN2NSettingModel);
}
mHin2nEdit.putLong("current_setting_id", id);
mHin2nEdit.commit();
if (N2NService.INSTANCE != null && N2NService.INSTANCE.getEdgeStatus().isRunning) {
N2NService.INSTANCE.stop();
}
Intent vpnPrepareIntent = VpnService.prepare(SettingDetailsActivity.this);
if (vpnPrepareIntent != null) {
startActivityForResult(vpnPrepareIntent, 100);
} else {
onActivityResult(100, RESULT_OK, null);
}
} else {
N2NSettingModelDao n2NSettingModelDao = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao();
String settingName = mSettingName.getEditText().getText().toString();
String setingNameTmp = settingName;
int i = 0;
while (n2NSettingModelDao.queryBuilder().where(N2NSettingModelDao.Properties.Name.eq(settingName)).unique() != null) {
i++;
settingName = setingNameTmp + "(" + i + ")";
}
Long id;
if (mMoreSettingCheckBox.isChecked()) {
mN2NSettingModel = new N2NSettingModel(null, settingName, mIpAddressTIL.getEditText().getText().toString(),
TextUtils.isEmpty(mNetMaskTIL.getEditText().getText()) ? "255.255.255.0" : mNetMaskTIL.getEditText().getText().toString(),
mCommunityTIL.getEditText().getText().toString(), mEncryptTIL.getEditText().getText().toString(),
mSuperNodeTIL.getEditText().getText().toString(), true, mSuperNodeBackup.getEditText().getText().toString(),
TextUtils.isEmpty(mMacAddr.getEditText().getText().toString()) ? EdgeCmd.getRandomMac() : mMacAddr.getEditText().getText().toString(),
TextUtils.isEmpty(mMtu.getEditText().getText().toString()) ? 1400 : Integer.valueOf(mMtu.getEditText().getText().toString()),
mResoveSupernodeIPCheckBox.isChecked(), TextUtils.isEmpty(mLocalPort.getEditText().getText().toString()) ? 0 : Integer.valueOf(mLocalPort.getEditText().getText().toString()),
mAllowRoutinCheckBox.isChecked(), mDropMuticastCheckBox.isChecked(), mTraceLevelSpinner.getSelectedItemPosition(), false);
id = n2NSettingModelDao.insert(mN2NSettingModel);
} else {
mN2NSettingModel = new N2NSettingModel(null, settingName, mIpAddressTIL.getEditText().getText().toString(),
TextUtils.isEmpty(mNetMaskTIL.getEditText().getText()) ? "255.255.255.0" : mNetMaskTIL.getEditText().getText().toString(),
mCommunityTIL.getEditText().getText().toString(), mEncryptTIL.getEditText().getText().toString(),
mSuperNodeTIL.getEditText().getText().toString(), false, "", EdgeCmd.getRandomMac(), 1400, false, 0, false, true, 1, false);
id = n2NSettingModelDao.insert(mN2NSettingModel);
}
}
Toast.makeText(mContext, "Add Succeed", Toast.LENGTH_SHORT).show();
finish();
break;
case R.id.btn_modify:
if (!checkValues()) {
return;
}
if (mSaveAndSetCheckBox.isChecked()) {
Long currentSettingId = mHin2nSp.getLong("current_setting_id", -1);
if (currentSettingId != -1) {
N2NSettingModel currentSettingItem = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao().load((long) currentSettingId);
if (currentSettingItem != null) {
currentSettingItem.setIsSelcected(false);
Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao().update(currentSettingItem);
}
}
N2NSettingModelDao n2NSettingModelDao1 = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao();
String settingName1 = mSettingName.getEditText().getText().toString();
String setingNameTmp1 = settingName1;
int i1 = 0;
N2NSettingModel n2NSettingModelTmp = n2NSettingModelDao1.queryBuilder().where(N2NSettingModelDao.Properties.Name.eq(settingName1)).unique();
while (n2NSettingModelTmp != null) {
if (n2NSettingModelTmp.getId() == mSaveId) {
break;
}
i1++;
settingName1 = setingNameTmp1 + "(" + i1 + ")";
n2NSettingModelTmp = n2NSettingModelDao1.queryBuilder().where(N2NSettingModelDao.Properties.Name.eq(settingName1)).unique();
}
long id;
if (mMoreSettingCheckBox.isChecked()) {
mN2NSettingModel = new N2NSettingModel(mSaveId, settingName1, mIpAddressTIL.getEditText().getText().toString(),
TextUtils.isEmpty(mNetMaskTIL.getEditText().getText()) ? "255.255.255.0" : mNetMaskTIL.getEditText().getText().toString(),
mCommunityTIL.getEditText().getText().toString(), mEncryptTIL.getEditText().getText().toString(),
mSuperNodeTIL.getEditText().getText().toString(), true, mSuperNodeBackup.getEditText().getText().toString(),
TextUtils.isEmpty(mMacAddr.getEditText().getText().toString()) ? EdgeCmd.getRandomMac() : mMacAddr.getEditText().getText().toString(),
TextUtils.isEmpty(mMtu.getEditText().getText().toString()) ? 1400 : Integer.valueOf(mMtu.getEditText().getText().toString()),
mResoveSupernodeIPCheckBox.isChecked(), TextUtils.isEmpty(mLocalPort.getEditText().getText().toString()) ? 0 : Integer.valueOf(mLocalPort.getEditText().getText().toString()),
mAllowRoutinCheckBox.isChecked(), mDropMuticastCheckBox.isChecked(), mTraceLevelSpinner.getSelectedItemPosition(), true);
n2NSettingModelDao1.update(mN2NSettingModel);
} else {
mN2NSettingModel = new N2NSettingModel(mSaveId, settingName1, mIpAddressTIL.getEditText().getText().toString(),
TextUtils.isEmpty(mNetMaskTIL.getEditText().getText()) ? "255.255.255.0" : mNetMaskTIL.getEditText().getText().toString(),
mCommunityTIL.getEditText().getText().toString(), mEncryptTIL.getEditText().getText().toString(),
mSuperNodeTIL.getEditText().getText().toString(), false, "", EdgeCmd.getRandomMac(), 1400, false, 0, false, true, 1, true);
n2NSettingModelDao1.update(mN2NSettingModel);
}
mHin2nEdit.putLong("current_setting_id", mSaveId);
mHin2nEdit.commit();
if (N2NService.INSTANCE != null && N2NService.INSTANCE.getEdgeStatus().isRunning) {
N2NService.INSTANCE.stop();
}
Intent vpnPrepareIntent = VpnService.prepare(SettingDetailsActivity.this);
if (vpnPrepareIntent != null) {
startActivityForResult(vpnPrepareIntent, 100);
} else {
onActivityResult(100, RESULT_OK, null);
}
} else {
N2NSettingModelDao n2NSettingModelDao1 = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao();
String settingName1 = mSettingName.getEditText().getText().toString();
String setingNameTmp1 = settingName1;
int i1 = 0;
N2NSettingModel n2NSettingModelTmp = n2NSettingModelDao1.queryBuilder().where(N2NSettingModelDao.Properties.Name.eq(settingName1)).unique();
while (n2NSettingModelTmp != null) {
if (n2NSettingModelTmp.getId() == mSaveId) {
break;
}
i1++;
settingName1 = setingNameTmp1 + "(" + i1 + ")";
n2NSettingModelTmp = n2NSettingModelDao1.queryBuilder().where(N2NSettingModelDao.Properties.Name.eq(settingName1)).unique();
}
Long id;
if (mMoreSettingCheckBox.isChecked()) {
mN2NSettingModel = new N2NSettingModel(mSaveId, settingName1, mIpAddressTIL.getEditText().getText().toString(),
TextUtils.isEmpty(mNetMaskTIL.getEditText().getText()) ? "255.255.255.0" : mNetMaskTIL.getEditText().getText().toString(),
mCommunityTIL.getEditText().getText().toString(), mEncryptTIL.getEditText().getText().toString(),
mSuperNodeTIL.getEditText().getText().toString(), true, mSuperNodeBackup.getEditText().getText().toString(),
TextUtils.isEmpty(mMacAddr.getEditText().getText().toString()) ? EdgeCmd.getRandomMac() : mMacAddr.getEditText().getText().toString(),
TextUtils.isEmpty(mMtu.getEditText().getText().toString()) ? 1400 : Integer.valueOf(mMtu.getEditText().getText().toString()),
mResoveSupernodeIPCheckBox.isChecked(), TextUtils.isEmpty(mLocalPort.getEditText().getText().toString()) ? 0 : Integer.valueOf(mLocalPort.getEditText().getText().toString()),
mAllowRoutinCheckBox.isChecked(), mDropMuticastCheckBox.isChecked(), mTraceLevelSpinner.getSelectedItemPosition(), mN2NSettingModel.getIsSelcected());
n2NSettingModelDao1.update(mN2NSettingModel);
} else {
mN2NSettingModel = new N2NSettingModel(mSaveId, settingName1, mIpAddressTIL.getEditText().getText().toString(),
TextUtils.isEmpty(mNetMaskTIL.getEditText().getText()) ? "255.255.255.0" : mNetMaskTIL.getEditText().getText().toString(),
mCommunityTIL.getEditText().getText().toString(), mEncryptTIL.getEditText().getText().toString(),
mSuperNodeTIL.getEditText().getText().toString(), false, "", EdgeCmd.getRandomMac(), 1400, false, 0, false, true, 1, mN2NSettingModel.getIsSelcected());
n2NSettingModelDao1.update(mN2NSettingModel);
}
}
Toast.makeText(mContext, "Update Succeed", Toast.LENGTH_SHORT).show();
finish();
break;
case R.id.btn_delete:
N2NSettingModelDao n2NSettingModelDao = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao();
n2NSettingModelDao.deleteByKey(mSaveId);
Toast.makeText(mContext, "Delete Succeed", Toast.LENGTH_SHORT).show();
finish();
break;
default:
break;
}
}
private boolean checkValues() {
if (TextUtils.isEmpty(mSettingName.getEditText().getText())
|| TextUtils.isEmpty(mIpAddressTIL.getEditText().getText())
|| TextUtils.isEmpty(mCommunityTIL.getEditText().getText())
|| TextUtils.isEmpty(mSuperNodeTIL.getEditText().getText())) {
if (TextUtils.isEmpty(mSuperNodeTIL.getEditText().getText())) {
mSuperNodeTIL.setError("Required");
mSuperNodeTIL.getEditText().requestFocus();
} else {
mSuperNodeTIL.setErrorEnabled(false);
}
if (TextUtils.isEmpty(mCommunityTIL.getEditText().getText())) {
mCommunityTIL.setError("Required");
mCommunityTIL.getEditText().requestFocus();
} else {
mCommunityTIL.setErrorEnabled(false);
}
if (TextUtils.isEmpty(mIpAddressTIL.getEditText().getText())) {
mIpAddressTIL.setError("Required");
mIpAddressTIL.getEditText().requestFocus();
} else {
mIpAddressTIL.setErrorEnabled(false);
}
if (TextUtils.isEmpty(mSettingName.getEditText().getText())) {
mSettingName.setError("Required");
mSettingName.getEditText().requestFocus();
} else {
mSettingName.setErrorEnabled(false);
}
return false;
}
if (!EdgeCmd.checkIPV4(mIpAddressTIL.getEditText().getText().toString())) {
mIpAddressTIL.setError("IP Address Error!");
mIpAddressTIL.getEditText().requestFocus();
return false;
} else {
mIpAddressTIL.setErrorEnabled(false);
}
if (!EdgeCmd.checkIPV4Mask(TextUtils.isEmpty(mNetMaskTIL.getEditText().getText().toString()) ? "255.255.255.0" : mNetMaskTIL.getEditText().getText().toString())) {
mNetMaskTIL.setError("NetMask Error!");
mNetMaskTIL.getEditText().requestFocus();
return false;
} else {
mNetMaskTIL.setErrorEnabled(false);
}
if (!EdgeCmd.checkCommunity(mCommunityTIL.getEditText().getText().toString())) {
mCommunityTIL.setError("Community Error!");
mCommunityTIL.getEditText().requestFocus();
return false;
} else {
mCommunityTIL.setErrorEnabled(false);
}
if (!EdgeCmd.checkEncKey(mEncryptTIL.getEditText().getText().toString())) {
mEncryptTIL.setError("Password Error!");
mEncryptTIL.getEditText().requestFocus();
return false;
} else {
mEncryptTIL.setErrorEnabled(false);
}
if (!EdgeCmd.checkSupernode(mSuperNodeTIL.getEditText().getText().toString())) {
mSuperNodeTIL.setError("Supernode Error!");
mSuperNodeTIL.getEditText().requestFocus();
return false;
} else {
mSuperNodeTIL.setErrorEnabled(false);
}
if (mMoreSettingCheckBox.isChecked()) {
if (!TextUtils.isEmpty(mSuperNodeBackup.getEditText().getText().toString()) && !EdgeCmd.checkSupernode(mSuperNodeBackup.getEditText().getText().toString())) {
mSuperNodeBackup.setError("Supernode Back Error!");
mSuperNodeBackup.getEditText().requestFocus();
return false;
} else {
mSuperNodeBackup.setErrorEnabled(false);
}
if (!TextUtils.isEmpty(mMacAddr.getEditText().getText().toString()) && !EdgeCmd.checkMacAddr(mMacAddr.getEditText().getText().toString())) {
mMacAddr.setError("Mac Address Error!");
mMacAddr.getEditText().requestFocus();
return false;
} else {
mMacAddr.setErrorEnabled(false);
}
if (!TextUtils.isEmpty(mMtu.getEditText().getText().toString()) && !EdgeCmd.checkInt(Integer.valueOf(mMtu.getEditText().getText().toString()), 46, 1500)) {
mMtu.setError("Mtu Error!");
mMtu.getEditText().requestFocus();
return false;
} else {
mMtu.setErrorEnabled(false);
}
if (!TextUtils.isEmpty(mLocalPort.getEditText().getText().toString()) && !EdgeCmd.checkInt(Integer.valueOf(mLocalPort.getEditText().getText().toString()), 0, 65535)) {
mLocalPort.setError("Local Port Error!");
mLocalPort.getEditText().requestFocus();
return false;
} else {
mLocalPort.setErrorEnabled(false);
}
}
return true;
}
}

View File

@ -0,0 +1,89 @@
package wang.switchy.hin2n.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.List;
import wang.switchy.hin2n.R;
import wang.switchy.hin2n.entity.SettingItemEntity;
/**
* Created by janiszhang on 2018/5/6.
*/
public class SettingItemAdapter extends BaseAdapter {
private Context mContext;
private List<SettingItemEntity> mSettingItemEntities;
private final LayoutInflater mLayoutInflater;
public SettingItemAdapter(Context context, List<SettingItemEntity> settingItemEntities) {
mContext = context;
mSettingItemEntities = settingItemEntities;
mLayoutInflater = LayoutInflater.from(mContext);
}
@Override
public int getCount() {
return mSettingItemEntities.size();
}
@Override
public Object getItem(int i) {
return mSettingItemEntities.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
final SettingItemEntity settingItemEntity = mSettingItemEntities.get(position);
if (convertView == null) {
convertView = mLayoutInflater.inflate(R.layout.layout_setting_item, null);
viewHolder = new ViewHolder();
viewHolder.settingName = (TextView) convertView.findViewById(R.id.tv_setting_name);
viewHolder.imgIsSelected = (ImageView) convertView.findViewById(R.id.iv_selected);
viewHolder.moreInfo = (TextView) convertView.findViewById(R.id.tv_more);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.settingName.setText(settingItemEntity.getSettingName());
if (settingItemEntity.isSelected()) {
viewHolder.imgIsSelected.setVisibility(View.VISIBLE);
} else {
viewHolder.imgIsSelected.setVisibility(View.INVISIBLE);
}
viewHolder.moreInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
settingItemEntity.mOnMoreBtnClickListener.onClick();
}
});
return convertView;
}
class ViewHolder {
TextView settingName;
ImageView imgIsSelected;
TextView moreInfo;
}
}

View File

@ -0,0 +1,51 @@
package wang.switchy.hin2n.entity;
/**
* Created by janiszhang on 2018/5/5.
*/
public class SettingItemEntity {
private String mSettingName;
private Long mSaveId;
private boolean isSelected;
public SettingItemEntity(String settingName, Long saveId, boolean isSelected) {
mSettingName = settingName;
mSaveId = saveId;
this.isSelected = isSelected;
}
public String getSettingName() {
return mSettingName;
}
public void setSettingName(String settingName) {
mSettingName = settingName;
}
public Long getSaveId() {
return mSaveId;
}
public void setSaveId(Long saveId) {
mSaveId = saveId;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
public OnMoreBtnClickListener mOnMoreBtnClickListener;
public void setOnMoreBtnClickListener(OnMoreBtnClickListener onMoreBtnClickListener) {
mOnMoreBtnClickListener = onMoreBtnClickListener;
}
public interface OnMoreBtnClickListener {
void onClick();
}
}

View File

@ -0,0 +1,8 @@
package wang.switchy.hin2n.event;
/**
* Created by janiszhang on 2018/4/21.
*/
public class ErrorEvent {
}

View File

@ -0,0 +1,8 @@
package wang.switchy.hin2n.event;
/**
* Created by janiszhang on 2018/4/21.
*/
public class StartEvent {
}

View File

@ -0,0 +1,8 @@
package wang.switchy.hin2n.event;
/**
* Created by janiszhang on 2018/4/21.
*/
public class StopEvent {
}

View File

@ -0,0 +1,152 @@
package wang.switchy.hin2n.model;
import android.util.Log;
import java.util.Random;
import java.util.Vector;
public class EdgeCmd {
public String ipAddr;
public String ipNetmask;
public String[] supernodes;
public String community;
public String encKey;
public String encKeyFile;
public String macAddr;
public int mtu;
public boolean reResoveSupernodeIP;
public int localPort;
public boolean allowRouting;
public boolean dropMuticast;
public int traceLevel;
public int vpnFd;
public static boolean checkIPV4(String ip) {
if (ip == null || ip.length() < 7 || ip.length() > 15) {
return false;
}
String[] split = ip.split("\\.");
if (split == null || split.length != 4) {
return false;
}
try {
for (int i = 0; i < split.length; ++i) {
int n = Integer.parseInt(split[i]);
if (n < 0 || n > 255 || !String.valueOf(n).equals(split[i])) {
return false;
}
}
} catch (Exception e) {
return false;
}
return true;
}
public static boolean checkIPV4Mask(String netmask) {
int[] arr = {0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE, 0xFF};
if (netmask == null || netmask.length() < 7 || netmask.length() > 15) {
return false;
}
String[] split = netmask.split("\\.");
if (split == null || split.length != 4) {
return false;
}
try {
for (int i = 0; i < split.length; ++i) {
int n = Integer.parseInt(split[i]);
boolean flag = false;
for (int j = 0; j < arr.length; ++j) {
if (n == arr[j]) {
flag = true;
break;
}
}
if (!flag || !String.valueOf(n).equals(split[i])) {
return false;
}
}
} catch (Exception e) {
return false;
}
return true;
}
public static boolean checkSupernode(String supernode) {
if (supernode == null || supernode.isEmpty() || supernode.length() > 47) {
return false;
}
String[] split = supernode.split(":");
if (split == null || split.length != 2 || split[0].isEmpty()) {
return false;
}
int n = Integer.parseInt(split[1]);
if (n < 0 || n > 65535 || !String.valueOf(n).equals(split[1])) {
return false;
}
return true;
}
public static boolean checkCommunity(String community) {
if (community == null || community.isEmpty() || community.length() > 15) {
return false;
}
return true;
}
public static boolean checkEncKey(String encKey) {
return true;
}
public static boolean checkEncKeyFile(String encKeyFile) {
return true;
}
public static boolean checkMacAddr(String mac) {
String hex = "0123456789abcdef";
if (mac == null || mac.length() != 17) {
return false;
}
for (int i = 0; i < mac.length(); ++i) {
char c = mac.charAt(i);
if ((i + 1) % 3 == 0) {
if (c != ':') {
return false;
}
continue;
}
if (!hex.contains(String.valueOf(c))) {
return false;
}
}
return true;
}
public static boolean checkInt(int n, int min, int max) {
if (n < min || n > max) {
return false;
}
return true;
}
public static String getRandomMac() {
String mac = "", hex="0123456789abcdef";
Random rand = new Random();
for (int i = 0; i < 17; ++i)
{
if ((i + 1) % 3 == 0) {
mac += ':';
continue;
}
mac += hex.charAt(rand.nextInt(16));
}
return mac;
}
}

View File

@ -0,0 +1,9 @@
package wang.switchy.hin2n.model;
//
// Created by switchwang(https://github.com/switch-st) on 2018-04-28.
//
public class EdgeStatus {
public boolean isRunning;
}

View File

@ -0,0 +1,254 @@
package wang.switchy.hin2n.model;
import android.os.Parcel;
import android.os.Parcelable;
import wang.switchy.hin2n.storage.db.base.model.N2NSettingModel;
/**
* Created by janiszhang on 2018/5/11.
*/
public class N2NSettingInfo implements Parcelable {
Long id;
String name;
String ip;
String netmask;
String community;
String password;
String superNode;
boolean moreSettings;
String superNodeBackup;
String macAddr;
int mtu;
boolean resoveSupernodeIP;
int localPort;
boolean allowRouting;
boolean dropMuticast;
int traceLevel;
public N2NSettingInfo(N2NSettingModel n2NSettingModel) {
this.id = n2NSettingModel.getId();
this.name = n2NSettingModel.getName();
this.ip = n2NSettingModel.getIp();
this.netmask = n2NSettingModel.getNetmask();
this.community = n2NSettingModel.getCommunity();
this.password = n2NSettingModel.getPassword();
this.superNode = n2NSettingModel.getSuperNode();
this.moreSettings = n2NSettingModel.getMoreSettings();
this.superNodeBackup = n2NSettingModel.getSuperNodeBackup();
this.macAddr = n2NSettingModel.getMacAddr();
this.mtu = n2NSettingModel.getMtu();
this.resoveSupernodeIP = n2NSettingModel.getResoveSupernodeIP();
this.localPort = n2NSettingModel.getLocalPort();
this.allowRouting = n2NSettingModel.getAllowRouting();
this.dropMuticast = n2NSettingModel.getDropMuticast();
this.traceLevel = n2NSettingModel.getTraceLevel();
}
protected N2NSettingInfo(Parcel in) {
name = in.readString();
ip = in.readString();
netmask = in.readString();
community = in.readString();
password = in.readString();
superNode = in.readString();
moreSettings = in.readByte() != 0;
superNodeBackup = in.readString();
macAddr = in.readString();
mtu = in.readInt();
resoveSupernodeIP = in.readByte() != 0;
localPort = in.readInt();
allowRouting = in.readByte() != 0;
dropMuticast = in.readByte() != 0;
traceLevel = in.readInt();
}
public static final Creator<N2NSettingInfo> CREATOR = new Creator<N2NSettingInfo>() {
@Override
public N2NSettingInfo createFromParcel(Parcel in) {
return new N2NSettingInfo(in);
}
@Override
public N2NSettingInfo[] newArray(int size) {
return new N2NSettingInfo[size];
}
};
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getNetmask() {
return netmask;
}
public void setNetmask(String netmask) {
this.netmask = netmask;
}
public String getCommunity() {
return community;
}
public void setCommunity(String community) {
this.community = community;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSuperNode() {
return superNode;
}
public void setSuperNode(String superNode) {
this.superNode = superNode;
}
public boolean isMoreSettings() {
return moreSettings;
}
public void setMoreSettings(boolean moreSettings) {
this.moreSettings = moreSettings;
}
public String getSuperNodeBackup() {
return superNodeBackup;
}
public void setSuperNodeBackup(String superNodeBackup) {
this.superNodeBackup = superNodeBackup;
}
public String getMacAddr() {
return macAddr;
}
public void setMacAddr(String macAddr) {
this.macAddr = macAddr;
}
public int getMtu() {
return mtu;
}
public void setMtu(int mtu) {
this.mtu = mtu;
}
public boolean isResoveSupernodeIP() {
return resoveSupernodeIP;
}
public void setResoveSupernodeIP(boolean resoveSupernodeIP) {
this.resoveSupernodeIP = resoveSupernodeIP;
}
public int getLocalPort() {
return localPort;
}
public void setLocalPort(int localPort) {
this.localPort = localPort;
}
public boolean isAllowRouting() {
return allowRouting;
}
public void setAllowRouting(boolean allowRouting) {
this.allowRouting = allowRouting;
}
public boolean isDropMuticast() {
return dropMuticast;
}
public void setDropMuticast(boolean dropMuticast) {
this.dropMuticast = dropMuticast;
}
public int getTraceLevel() {
return traceLevel;
}
public void setTraceLevel(int traceLevel) {
this.traceLevel = traceLevel;
}
@Override
public String toString() {
return "N2NSettingInfo{" +
"id=" + id +
", name='" + name + '\'' +
", ip='" + ip + '\'' +
", netmask='" + netmask + '\'' +
", community='" + community + '\'' +
", password='" + password + '\'' +
", superNode='" + superNode + '\'' +
", moreSettings=" + moreSettings +
", superNodeBackup='" + superNodeBackup + '\'' +
", macAddr='" + macAddr + '\'' +
", mtu=" + mtu +
", resoveSupernodeIP=" + resoveSupernodeIP +
", localPort=" + localPort +
", allowRouting=" + allowRouting +
", dropMuticast=" + dropMuticast +
", traceLevel=" + traceLevel +
'}';
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeString(ip);
parcel.writeString(netmask);
parcel.writeString(community);
parcel.writeString(password);
parcel.writeString(superNode);
parcel.writeByte((byte) (moreSettings ? 1 : 0));
parcel.writeString(superNodeBackup);
parcel.writeString(macAddr);
parcel.writeInt(mtu);
parcel.writeByte((byte) (resoveSupernodeIP ? 1 : 0));
parcel.writeInt(localPort);
parcel.writeByte((byte) (allowRouting ? 1 : 0));
parcel.writeByte((byte) (dropMuticast ? 1 : 0));
parcel.writeInt(traceLevel);
}
}

View File

@ -0,0 +1,187 @@
package wang.switchy.hin2n.service;
import android.content.Intent;
import android.net.VpnService;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.widget.Toast;
import org.greenrobot.eventbus.EventBus;
import java.io.IOException;
import java.net.InetAddress;
import wang.switchy.hin2n.event.ErrorEvent;
import wang.switchy.hin2n.event.StartEvent;
import wang.switchy.hin2n.event.StopEvent;
import wang.switchy.hin2n.model.EdgeCmd;
import wang.switchy.hin2n.model.EdgeStatus;
import wang.switchy.hin2n.model.N2NSettingInfo;
import static wang.switchy.hin2n.model.EdgeCmd.getRandomMac;
/**
* Created by janiszhang on 2018/4/15.
*/
public class N2NService extends VpnService {
public static N2NService INSTANCE;
private ParcelFileDescriptor mParcelFileDescriptor = null;
private EdgeCmd cmd;
private boolean mStartResult;
@Override
public void onCreate() {
super.onCreate();
INSTANCE = this;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle setting = intent.getBundleExtra("Setting");
N2NSettingInfo n2nSettingInfo = setting.getParcelable("n2nSettingInfo");
Builder b = new Builder();
b.setMtu(n2nSettingInfo.getMtu());
String ipAddress = n2nSettingInfo.getIp();
b.addAddress(ipAddress, getIpAddrPrefixLength(n2nSettingInfo.getNetmask()));
String route = getRoute(ipAddress, getIpAddrPrefixLength(n2nSettingInfo.getNetmask()));
b.addRoute(route, getIpAddrPrefixLength(n2nSettingInfo.getNetmask()));
try {
mParcelFileDescriptor = b.setSession("N2N").establish();
} catch (IllegalArgumentException e) {
e.printStackTrace();
Toast.makeText(INSTANCE, "Parameter is not accepted by the operating system.", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
} catch (IllegalStateException e) {
e.printStackTrace();
Toast.makeText(INSTANCE, "Parameter cannot be applied by the operating system.", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
if (mParcelFileDescriptor == null) {
Toast.makeText(INSTANCE, "~error~", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
cmd = new EdgeCmd();
cmd.ipAddr = n2nSettingInfo.getIp();
cmd.ipNetmask = n2nSettingInfo.getNetmask();
cmd.supernodes = new String[2];
cmd.supernodes[0] = n2nSettingInfo.getSuperNode();
cmd.supernodes[1] = n2nSettingInfo.getSuperNodeBackup();
cmd.community = n2nSettingInfo.getCommunity();
cmd.encKey = n2nSettingInfo.getPassword();
cmd.encKeyFile = null;
cmd.macAddr = n2nSettingInfo.getMacAddr();
cmd.mtu = n2nSettingInfo.getMtu();
cmd.reResoveSupernodeIP = n2nSettingInfo.isResoveSupernodeIP();
cmd.localPort = n2nSettingInfo.getLocalPort();
cmd.allowRouting = n2nSettingInfo.isAllowRouting();
cmd.dropMuticast = n2nSettingInfo.isDropMuticast();
cmd.traceLevel = n2nSettingInfo.getTraceLevel();
cmd.vpnFd = mParcelFileDescriptor.detachFd();
try {
mStartResult = startEdge(cmd);
if (!mStartResult) {
EventBus.getDefault().post(new ErrorEvent());
}
} catch (Exception e) {
e.printStackTrace();
}
return super.onStartCommand(intent, flags, startId);
}
public void stop() {
stopEdge();
try {
if (mParcelFileDescriptor != null) {
mParcelFileDescriptor.close();
mParcelFileDescriptor = null;
}
} catch (IOException e) {
e.printStackTrace();
}
EventBus.getDefault().post(new StopEvent());
}
@Override
public void onRevoke() {
super.onRevoke();
stop();
}
@Override
public void onDestroy() {
super.onDestroy();
}
public native boolean startEdge(EdgeCmd cmd);
public native void stopEdge();
public native EdgeStatus getEdgeStatus();
public void reportEdgeStatus(EdgeStatus status) {
if (status != null) {
if (status.isRunning) {
EventBus.getDefault().post(new StartEvent());
} else {
EventBus.getDefault().post(new StopEvent());
}
}
}
private int getIpAddrPrefixLength(String netmask) {
try {
byte[] byteAddr = InetAddress.getByName(netmask).getAddress();
int prefixLength = 0;
for (int i = 0; i < byteAddr.length; i++) {
for (int j = 0; j < 8; j++) {
if ((byteAddr[i] << j & 0xFF) != 0) {
prefixLength++;
} else {
return prefixLength;
}
}
}
return prefixLength;
} catch (Exception e) {
return -1;
}
}
private String getRoute(String ipAddr, int prefixLength) {
byte[] arr = {(byte) 0x00, (byte) 0x80, (byte) 0xC0, (byte) 0xE0, (byte) 0xF0, (byte) 0xF8, (byte) 0xFC, (byte) 0xFE, (byte) 0xFF};
if (prefixLength > 32 || prefixLength < 0) {
return "";
}
try {
byte[] byteAddr = InetAddress.getByName(ipAddr).getAddress();
int idx = 0;
while (prefixLength >= 8) {
idx++;
prefixLength -= 8;
}
if (idx < byteAddr.length) {
byteAddr[idx++] &= arr[prefixLength];
}
for (; idx < byteAddr.length; idx++) {
byteAddr[idx] = (byte) 0x00;
}
return InetAddress.getByAddress(byteAddr).getHostAddress();
} catch (Exception e) {
return "";
}
}
}

View File

@ -0,0 +1,96 @@
package wang.switchy.hin2n.storage.db.base;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;
import org.greenrobot.greendao.AbstractDaoMaster;
import org.greenrobot.greendao.database.StandardDatabase;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseOpenHelper;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* Master of DAO (schema version 1): knows all DAOs.
*/
public class DaoMaster extends AbstractDaoMaster {
public static final int SCHEMA_VERSION = 1;
/** Creates underlying database table using DAOs. */
public static void createAllTables(Database db, boolean ifNotExists) {
N2NSettingModelDao.createTable(db, ifNotExists);
}
/** Drops underlying database table using DAOs. */
public static void dropAllTables(Database db, boolean ifExists) {
N2NSettingModelDao.dropTable(db, ifExists);
}
/**
* WARNING: Drops all table on Upgrade! Use only during development.
* Convenience method using a {@link DevOpenHelper}.
*/
public static DaoSession newDevSession(Context context, String name) {
Database db = new DevOpenHelper(context, name).getWritableDb();
DaoMaster daoMaster = new DaoMaster(db);
return daoMaster.newSession();
}
public DaoMaster(SQLiteDatabase db) {
this(new StandardDatabase(db));
}
public DaoMaster(Database db) {
super(db, SCHEMA_VERSION);
registerDaoClass(N2NSettingModelDao.class);
}
public DaoSession newSession() {
return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
}
public DaoSession newSession(IdentityScopeType type) {
return new DaoSession(db, type, daoConfigMap);
}
/**
* Calls {@link #createAllTables(Database, boolean)} in {@link #onCreate(Database)} -
*/
public static abstract class OpenHelper extends DatabaseOpenHelper {
public OpenHelper(Context context, String name) {
super(context, name, SCHEMA_VERSION);
}
public OpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory, SCHEMA_VERSION);
}
@Override
public void onCreate(Database db) {
Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION);
createAllTables(db, false);
}
}
/** WARNING: Drops all table on Upgrade! Use only during development. */
public static class DevOpenHelper extends OpenHelper {
public DevOpenHelper(Context context, String name) {
super(context, name);
}
public DevOpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
dropAllTables(db, true);
onCreate(db);
}
}
}

View File

@ -0,0 +1,48 @@
package wang.switchy.hin2n.storage.db.base;
import java.util.Map;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.AbstractDaoSession;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
import org.greenrobot.greendao.internal.DaoConfig;
import wang.switchy.hin2n.storage.db.base.model.N2NSettingModel;
import wang.switchy.hin2n.storage.db.base.N2NSettingModelDao;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* {@inheritDoc}
*
* @see org.greenrobot.greendao.AbstractDaoSession
*/
public class DaoSession extends AbstractDaoSession {
private final DaoConfig n2NSettingModelDaoConfig;
private final N2NSettingModelDao n2NSettingModelDao;
public DaoSession(Database db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
daoConfigMap) {
super(db);
n2NSettingModelDaoConfig = daoConfigMap.get(N2NSettingModelDao.class).clone();
n2NSettingModelDaoConfig.initIdentityScope(type);
n2NSettingModelDao = new N2NSettingModelDao(n2NSettingModelDaoConfig, this);
registerDao(N2NSettingModel.class, n2NSettingModelDao);
}
public void clear() {
n2NSettingModelDaoConfig.clearIdentityScope();
}
public N2NSettingModelDao getN2NSettingModelDao() {
return n2NSettingModelDao;
}
}

View File

@ -0,0 +1,275 @@
package wang.switchy.hin2n.storage.db.base;
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.internal.DaoConfig;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseStatement;
import wang.switchy.hin2n.storage.db.base.model.N2NSettingModel;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "N2NSettingList".
*/
public class N2NSettingModelDao extends AbstractDao<N2NSettingModel, Long> {
public static final String TABLENAME = "N2NSettingList";
/**
* Properties of entity N2NSettingModel.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property Name = new Property(1, String.class, "name", false, "NAME");
public final static Property Ip = new Property(2, String.class, "ip", false, "IP");
public final static Property Netmask = new Property(3, String.class, "netmask", false, "NETMASK");
public final static Property Community = new Property(4, String.class, "community", false, "COMMUNITY");
public final static Property Password = new Property(5, String.class, "password", false, "PASSWORD");
public final static Property SuperNode = new Property(6, String.class, "superNode", false, "SUPER_NODE");
public final static Property MoreSettings = new Property(7, boolean.class, "moreSettings", false, "MORE_SETTINGS");
public final static Property SuperNodeBackup = new Property(8, String.class, "superNodeBackup", false, "SUPER_NODE_BACKUP");
public final static Property MacAddr = new Property(9, String.class, "macAddr", false, "MAC_ADDR");
public final static Property Mtu = new Property(10, int.class, "mtu", false, "MTU");
public final static Property ResoveSupernodeIP = new Property(11, boolean.class, "resoveSupernodeIP", false, "RESOVE_SUPERNODE_IP");
public final static Property LocalPort = new Property(12, int.class, "localPort", false, "LOCAL_PORT");
public final static Property AllowRouting = new Property(13, boolean.class, "allowRouting", false, "ALLOW_ROUTING");
public final static Property DropMuticast = new Property(14, boolean.class, "dropMuticast", false, "DROP_MUTICAST");
public final static Property TraceLevel = new Property(15, int.class, "traceLevel", false, "TRACE_LEVEL");
public final static Property IsSelcected = new Property(16, boolean.class, "isSelcected", false, "IS_SELCECTED");
}
public N2NSettingModelDao(DaoConfig config) {
super(config);
}
public N2NSettingModelDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}
/** Creates the underlying database table. */
public static void createTable(Database db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"N2NSettingList\" (" + //
"\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id
"\"NAME\" TEXT," + // 1: name
"\"IP\" TEXT," + // 2: ip
"\"NETMASK\" TEXT," + // 3: netmask
"\"COMMUNITY\" TEXT," + // 4: community
"\"PASSWORD\" TEXT," + // 5: password
"\"SUPER_NODE\" TEXT," + // 6: superNode
"\"MORE_SETTINGS\" INTEGER NOT NULL ," + // 7: moreSettings
"\"SUPER_NODE_BACKUP\" TEXT," + // 8: superNodeBackup
"\"MAC_ADDR\" TEXT," + // 9: macAddr
"\"MTU\" INTEGER NOT NULL ," + // 10: mtu
"\"RESOVE_SUPERNODE_IP\" INTEGER NOT NULL ," + // 11: resoveSupernodeIP
"\"LOCAL_PORT\" INTEGER NOT NULL ," + // 12: localPort
"\"ALLOW_ROUTING\" INTEGER NOT NULL ," + // 13: allowRouting
"\"DROP_MUTICAST\" INTEGER NOT NULL ," + // 14: dropMuticast
"\"TRACE_LEVEL\" INTEGER NOT NULL ," + // 15: traceLevel
"\"IS_SELCECTED\" INTEGER NOT NULL );"); // 16: isSelcected
}
/** Drops the underlying database table. */
public static void dropTable(Database db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"N2NSettingList\"";
db.execSQL(sql);
}
@Override
protected final void bindValues(DatabaseStatement stmt, N2NSettingModel entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String name = entity.getName();
if (name != null) {
stmt.bindString(2, name);
}
String ip = entity.getIp();
if (ip != null) {
stmt.bindString(3, ip);
}
String netmask = entity.getNetmask();
if (netmask != null) {
stmt.bindString(4, netmask);
}
String community = entity.getCommunity();
if (community != null) {
stmt.bindString(5, community);
}
String password = entity.getPassword();
if (password != null) {
stmt.bindString(6, password);
}
String superNode = entity.getSuperNode();
if (superNode != null) {
stmt.bindString(7, superNode);
}
stmt.bindLong(8, entity.getMoreSettings() ? 1L: 0L);
String superNodeBackup = entity.getSuperNodeBackup();
if (superNodeBackup != null) {
stmt.bindString(9, superNodeBackup);
}
String macAddr = entity.getMacAddr();
if (macAddr != null) {
stmt.bindString(10, macAddr);
}
stmt.bindLong(11, entity.getMtu());
stmt.bindLong(12, entity.getResoveSupernodeIP() ? 1L: 0L);
stmt.bindLong(13, entity.getLocalPort());
stmt.bindLong(14, entity.getAllowRouting() ? 1L: 0L);
stmt.bindLong(15, entity.getDropMuticast() ? 1L: 0L);
stmt.bindLong(16, entity.getTraceLevel());
stmt.bindLong(17, entity.getIsSelcected() ? 1L: 0L);
}
@Override
protected final void bindValues(SQLiteStatement stmt, N2NSettingModel entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String name = entity.getName();
if (name != null) {
stmt.bindString(2, name);
}
String ip = entity.getIp();
if (ip != null) {
stmt.bindString(3, ip);
}
String netmask = entity.getNetmask();
if (netmask != null) {
stmt.bindString(4, netmask);
}
String community = entity.getCommunity();
if (community != null) {
stmt.bindString(5, community);
}
String password = entity.getPassword();
if (password != null) {
stmt.bindString(6, password);
}
String superNode = entity.getSuperNode();
if (superNode != null) {
stmt.bindString(7, superNode);
}
stmt.bindLong(8, entity.getMoreSettings() ? 1L: 0L);
String superNodeBackup = entity.getSuperNodeBackup();
if (superNodeBackup != null) {
stmt.bindString(9, superNodeBackup);
}
String macAddr = entity.getMacAddr();
if (macAddr != null) {
stmt.bindString(10, macAddr);
}
stmt.bindLong(11, entity.getMtu());
stmt.bindLong(12, entity.getResoveSupernodeIP() ? 1L: 0L);
stmt.bindLong(13, entity.getLocalPort());
stmt.bindLong(14, entity.getAllowRouting() ? 1L: 0L);
stmt.bindLong(15, entity.getDropMuticast() ? 1L: 0L);
stmt.bindLong(16, entity.getTraceLevel());
stmt.bindLong(17, entity.getIsSelcected() ? 1L: 0L);
}
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
@Override
public N2NSettingModel readEntity(Cursor cursor, int offset) {
N2NSettingModel entity = new N2NSettingModel( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // name
cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // ip
cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // netmask
cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4), // community
cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5), // password
cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6), // superNode
cursor.getShort(offset + 7) != 0, // moreSettings
cursor.isNull(offset + 8) ? null : cursor.getString(offset + 8), // superNodeBackup
cursor.isNull(offset + 9) ? null : cursor.getString(offset + 9), // macAddr
cursor.getInt(offset + 10), // mtu
cursor.getShort(offset + 11) != 0, // resoveSupernodeIP
cursor.getInt(offset + 12), // localPort
cursor.getShort(offset + 13) != 0, // allowRouting
cursor.getShort(offset + 14) != 0, // dropMuticast
cursor.getInt(offset + 15), // traceLevel
cursor.getShort(offset + 16) != 0 // isSelcected
);
return entity;
}
@Override
public void readEntity(Cursor cursor, N2NSettingModel entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setName(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
entity.setIp(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
entity.setNetmask(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
entity.setCommunity(cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4));
entity.setPassword(cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5));
entity.setSuperNode(cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6));
entity.setMoreSettings(cursor.getShort(offset + 7) != 0);
entity.setSuperNodeBackup(cursor.isNull(offset + 8) ? null : cursor.getString(offset + 8));
entity.setMacAddr(cursor.isNull(offset + 9) ? null : cursor.getString(offset + 9));
entity.setMtu(cursor.getInt(offset + 10));
entity.setResoveSupernodeIP(cursor.getShort(offset + 11) != 0);
entity.setLocalPort(cursor.getInt(offset + 12));
entity.setAllowRouting(cursor.getShort(offset + 13) != 0);
entity.setDropMuticast(cursor.getShort(offset + 14) != 0);
entity.setTraceLevel(cursor.getInt(offset + 15));
entity.setIsSelcected(cursor.getShort(offset + 16) != 0);
}
@Override
protected final Long updateKeyAfterInsert(N2NSettingModel entity, long rowId) {
entity.setId(rowId);
return rowId;
}
@Override
public Long getKey(N2NSettingModel entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
@Override
public boolean hasKey(N2NSettingModel entity) {
return entity.getId() != null;
}
@Override
protected final boolean isEntityUpdateable() {
return true;
}
}

View File

@ -0,0 +1,222 @@
package wang.switchy.hin2n.storage.db.base.model;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
/**
* Created by janiszhang on 2018/5/4.
*/
@Entity(
nameInDb = "N2NSettingList"
)
public class N2NSettingModel /*implements Parcelable*/ {
@Id(autoincrement = true)
Long id;
String name;
String ip;
String netmask;
String community;
String password;
String superNode;
boolean moreSettings;
String superNodeBackup;
String macAddr;
int mtu;
boolean resoveSupernodeIP;
int localPort;
boolean allowRouting;
boolean dropMuticast;
int traceLevel;
boolean isSelcected;
@Generated(hash = 1390425120)
public N2NSettingModel(Long id, String name, String ip, String netmask,
String community, String password, String superNode,
boolean moreSettings, String superNodeBackup, String macAddr, int mtu,
boolean resoveSupernodeIP, int localPort, boolean allowRouting,
boolean dropMuticast, int traceLevel, boolean isSelcected) {
this.id = id;
this.name = name;
this.ip = ip;
this.netmask = netmask;
this.community = community;
this.password = password;
this.superNode = superNode;
this.moreSettings = moreSettings;
this.superNodeBackup = superNodeBackup;
this.macAddr = macAddr;
this.mtu = mtu;
this.resoveSupernodeIP = resoveSupernodeIP;
this.localPort = localPort;
this.allowRouting = allowRouting;
this.dropMuticast = dropMuticast;
this.traceLevel = traceLevel;
this.isSelcected = isSelcected;
}
@Generated(hash = 998225630)
public N2NSettingModel() {
}
public String getSuperNode() {
return this.superNode;
}
public void setSuperNode(String superNode) {
this.superNode = superNode;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCommunity() {
return this.community;
}
public void setCommunity(String community) {
this.community = community;
}
public String getNetmask() {
return this.netmask;
}
public void setNetmask(String netmask) {
this.netmask = netmask;
}
public String getIp() {
return this.ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public boolean getIsSelcected() {
return this.isSelcected;
}
public void setIsSelcected(boolean isSelcected) {
this.isSelcected = isSelcected;
}
public int getTraceLevel() {
return this.traceLevel;
}
public void setTraceLevel(int traceLevel) {
this.traceLevel = traceLevel;
}
public boolean getDropMuticast() {
return this.dropMuticast;
}
public void setDropMuticast(boolean dropMuticast) {
this.dropMuticast = dropMuticast;
}
public boolean getAllowRouting() {
return this.allowRouting;
}
public void setAllowRouting(boolean allowRouting) {
this.allowRouting = allowRouting;
}
public int getLocalPort() {
return this.localPort;
}
public void setLocalPort(int localPort) {
this.localPort = localPort;
}
public boolean getResoveSupernodeIP() {
return this.resoveSupernodeIP;
}
public void setResoveSupernodeIP(boolean resoveSupernodeIP) {
this.resoveSupernodeIP = resoveSupernodeIP;
}
public int getMtu() {
return this.mtu;
}
public void setMtu(int mtu) {
this.mtu = mtu;
}
public String getMacAddr() {
return this.macAddr;
}
public void setMacAddr(String macAddr) {
this.macAddr = macAddr;
}
public String getSuperNodeBackup() {
return this.superNodeBackup;
}
public void setSuperNodeBackup(String superNodeBackup) {
this.superNodeBackup = superNodeBackup;
}
public boolean getMoreSettings() {
return this.moreSettings;
}
public void setMoreSettings(boolean moreSettings) {
this.moreSettings = moreSettings;
}
@Override
public String toString() {
return "N2NSettingModel{" +
"id=" + id +
", name='" + name + '\'' +
", ip='" + ip + '\'' +
", netmask='" + netmask + '\'' +
", community='" + community + '\'' +
", password='" + password + '\'' +
", superNode='" + superNode + '\'' +
", moreSettings=" + moreSettings +
", superNodeBackup='" + superNodeBackup + '\'' +
", macAddr='" + macAddr + '\'' +
", mtu=" + mtu +
", resoveSupernodeIP=" + resoveSupernodeIP +
", localPort=" + localPort +
", allowRouting=" + allowRouting +
", dropMuticast=" + dropMuticast +
", traceLevel=" + traceLevel +
", isSelcected=" + isSelcected +
'}';
}
}

View File

@ -0,0 +1,21 @@
package wang.switchy.hin2n.template;
import android.content.Context;
import android.view.View;
/**
* Created by janiszhang on 2018/4/13.
*/
public abstract class BaseTemplate {
protected Context mContext;
public BaseTemplate(Context context) {
this.mContext = context;
}
public abstract void setContentView(View contentView);
public abstract View getPageView();
}

View File

@ -0,0 +1,60 @@
package wang.switchy.hin2n.template;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import wang.switchy.hin2n.R;
/**
* Created by janiszhang on 2018/4/13.
*/
public class CommonTitleTemplate extends BaseTemplate {
private Context mContext;
private LinearLayout mPageView;
private RelativeLayout mTitleLayout;
private FrameLayout mContainerLayout;
public final ImageView mLeftImg;
public final ImageView mRightImg;
public CommonTitleTemplate(Context context, String title) {
super(context);
this.mContext = context;
mPageView = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.main_template_view, null);
mTitleLayout = (RelativeLayout) mPageView.findViewById(R.id.rl_title);
mContainerLayout = (FrameLayout) mPageView.findViewById(R.id.fl_container);
TextView titleText = (TextView) mPageView.findViewById(R.id.tv_title);
mLeftImg = (ImageView) mPageView.findViewById(R.id.iv_left_img);
mRightImg = (ImageView) mPageView.findViewById(R.id.iv_right_img);
titleText.setText(title);
}
@Override
public void setContentView(View contentView) {
RelativeLayout.LayoutParams contentViewLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
mContainerLayout.addView(contentView, contentViewLayoutParams);
}
@Override
public View getPageView() {
return mPageView;
}
}

View File

@ -0,0 +1,26 @@
package wang.switchy.hin2n.template;
import android.content.Context;
import android.view.View;
/**
* Created by janiszhang on 2018/4/13.
*/
public class EmptyTemplate extends BaseTemplate {
private View mContentView;
public EmptyTemplate(Context context) {
super(context);
}
@Override
public void setContentView(View contentView) {
this.mContentView = contentView;
}
@Override
public View getPageView() {
return mContentView;
}
}

View File

@ -0,0 +1,53 @@
package wang.switchy.hin2n.template;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import wang.switchy.hin2n.R;
/**
* Created by janiszhang on 2018/4/13.
*/
public class MainTitleTemplate extends BaseTemplate {
private Context mContext;
private LinearLayout mPageView;
private RelativeLayout mTitleLayout;
private FrameLayout mContainerLayout;
public MainTitleTemplate(Context context, String title) {
super(context);
this.mContext = context;
mPageView = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.main_template_view, null);
mTitleLayout = (RelativeLayout) mPageView.findViewById(R.id.rl_title);
mContainerLayout = (FrameLayout) mPageView.findViewById(R.id.fl_container);
TextView titleText = (TextView) mPageView.findViewById(R.id.tv_title);
titleText.setText(title);
}
@Override
public void setContentView(View contentView) {
RelativeLayout.LayoutParams contentViewLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
mContainerLayout.addView(contentView, contentViewLayoutParams);
}
@Override
public View getPageView() {
return mPageView;
}
}

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<layer-list>
<item><shape android:shape="oval">
<solid android:color="#33FFFFFF" />
</shape></item>
<item android:drawable="@mipmap/title_back_normal"/>
</layer-list></item>
<item android:drawable="@mipmap/title_back_normal" android:state_pressed="false"/>
</selector>

View File

@ -0,0 +1,328 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<android.support.design.widget.TextInputLayout
android:id="@+id/til_setting_name"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_setting_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/til_ip_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/til_setting_name">
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_ip_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="IP address"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/til_net_mask"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/til_ip_address">
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_net_mask"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Netmask"
android:text="255.255.255.0"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/til_community"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/til_net_mask">
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_community"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Community"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/til_encrypt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/til_community">
<!--app:passwordToggleEnabled="true"-->
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_encrypt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"/>
<!--android:inputType="textPassword"-->
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/til_super_node"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/til_encrypt">
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_super_node"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Supernode"
android:text="n2n.switchy.wang:10086"/>
</android.support.design.widget.TextInputLayout>
<RelativeLayout
android:id="@+id/rl_more_setting_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/til_super_node">
<CheckBox
android:id="@+id/more_setting_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/more_setting_check_box"
android:text="more setting"/>
</RelativeLayout>
<RelativeLayout
android:id="@+id/rl_more_setting"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/rl_more_setting_check_box"
android:visibility="gone">
<android.support.design.widget.TextInputLayout
android:id="@+id/til_super_node_2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_super_node_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Supernode Backup"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/til_mac_addr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/til_super_node_2">
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_mac_addr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Mac Address"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/til_mtu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/til_mac_addr">
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_mtu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="mtu"/>
</android.support.design.widget.TextInputLayout>
<!--boolean-->
<RelativeLayout
android:id="@+id/rl_resove_super_node_ip_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/til_mtu">
<CheckBox
android:id="@+id/resove_super_node_ip_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/resove_super_node_ip_check_box"
android:text="Resove Supernode IP"/>
</RelativeLayout>
<android.support.design.widget.TextInputLayout
android:layout_below="@id/rl_resove_super_node_ip_check_box"
android:id="@+id/til_local_port"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_local_port"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="localPort"/>
</android.support.design.widget.TextInputLayout>
<!--boolean-->
<RelativeLayout
android:id="@+id/rl_allow_routing"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/til_local_port">
<CheckBox
android:id="@+id/allow_routing_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/allow_routing_check_box"
android:text="Allow Routing"/>
</RelativeLayout>
<!--boolean-->
<RelativeLayout
android:id="@+id/rl_drop_muticast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/rl_allow_routing">
<CheckBox
android:id="@+id/drop_muticast_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/drop_muticast_check_box"
android:text="Drop Muticast"/>
</RelativeLayout>
<RelativeLayout
android:layout_below="@id/rl_drop_muticast"
android:id="@+id/rl_trace_level"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_trace_level"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Trace Level : "/>
<Spinner
android:layout_toRightOf="@id/tv_trace_level"
android:id="@+id/spinner_trace_level"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
</RelativeLayout>
<RelativeLayout
android:id="@+id/rl_buttons"
android:layout_below="@id/rl_more_setting"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:visibility="gone"
android:id="@+id/btn_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="save"/>
<LinearLayout
android:id="@+id/ll_buttons"
android:weightSum="1"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_weight="0.5"
android:id="@+id/btn_modify"
android:text="modify"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:layout_weight="0.5"
android:id="@+id/btn_delete"
android:text="delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="@+id/rl_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/rl_buttons"
android:visibility="gone">
<CheckBox
android:id="@+id/check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/check_box"
android:text="with immediate effect"/>
</RelativeLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>

View File

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_centerVertical="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:id="@+id/rl_current_setting"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp">
<TextView
android:layout_centerVertical="true"
android:id="@+id/tv_current_setting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18dp"
android:text="Current Setting : "/>
<RelativeLayout
android:layout_toRightOf="@id/tv_current_setting"
android:id="@+id/rl_current_setting_item"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:id="@+id/tv_current_setting_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18dp"
android:text="--null--"/>
<ImageView
android:layout_alignParentRight="true"
android:layout_width="20dp"
android:layout_height="20dp"
android:src="@mipmap/img_more"/>
</RelativeLayout>
</RelativeLayout>
<Button
android:layout_marginTop="30dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:id="@+id/btn_action"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/rl_current_setting"
android:text="Start"/>
</RelativeLayout>
</RelativeLayout>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/lv_setting_item"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>

View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
>
<ImageView
android:layout_marginLeft="20dp"
android:layout_centerVertical="true"
android:id="@+id/iv_selected"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
android:src="@mipmap/img_icon_selected"/>
<TextView
android:layout_toRightOf="@id/iv_selected"
android:layout_marginLeft="10dp"
android:layout_centerVertical="true"
android:id="@+id/tv_setting_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:text="SettingName"/>
<TextView
android:layout_centerVertical="true"
android:layout_marginRight="20dp"
android:layout_alignParentRight="true"
android:id="@+id/tv_more"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:text="Edit"
android:padding="10dp"
/>
</RelativeLayout>
</RelativeLayout>

View File

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="@+id/rl_title"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@color/colorPrimary">
<ImageView
android:id="@+id/iv_left_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"/>
<TextView
android:id="@+id/tv_title"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hin2n"
android:textSize="20dp"
android:textColor="@android:color/white"/>
<ImageView
android:id="@+id/iv_right_img"
android:layout_alignParentRight="true"
android:layout_width="30dp"
android:layout_height="30dp"
android:visibility="visible"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"/>
</RelativeLayout>
<FrameLayout
android:id="@+id/fl_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 552 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 557 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 343 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 496 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 629 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 910 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 179 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

View File

@ -0,0 +1,6 @@
<resources>
<!-- Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
<dimen name="activity_horizontal_margin">64dp</dimen>
</resources>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>

View File

@ -0,0 +1,5 @@
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>

View File

@ -0,0 +1,3 @@
<resources>
<string name="app_name">Hin2n</string>
</resources>

View File

@ -0,0 +1,11 @@
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>

View File

@ -0,0 +1,17 @@
package wang.switchy.hin2n;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}

View File

@ -0,0 +1,25 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.2'
classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

View File

@ -0,0 +1,19 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
org.gradle.daemon=true

Binary file not shown.

View File

@ -0,0 +1,6 @@
#Tue Apr 17 00:25:58 CST 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip

160
android/Hin2n/gradlew vendored Executable file
View File

@ -0,0 +1,160 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

90
android/Hin2n/gradlew.bat vendored Normal file
View File

@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1 @@
include ':app'

367
android/edge_android.c Normal file
View File

@ -0,0 +1,367 @@
/**
* (C) 2007-18 - ntop.org and contributors
*
* 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 __ANDROID_NDK__
#include "edge_android.h"
#include <tun2tap/tun2tap.h>
#define N2N_NETMASK_STR_SIZE 16 /* dotted decimal 12 numbers + 3 dots */
#define N2N_MACNAMSIZ 18 /* AA:BB:CC:DD:EE:FF + NULL*/
#define N2N_IF_MODE_SIZE 16 /* static | dhcp */
/* *************************************************** */
#if defined(DUMMY_ID_00001) /* Disabled waiting for config option to enable it */
static char gratuitous_arp[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, /* Dest mac */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Src mac */
0x08, 0x06, /* ARP */
0x00, 0x01, /* Ethernet */
0x08, 0x00, /* IP */
0x06, /* Hw Size */
0x04, /* Protocol Size */
0x00, 0x01, /* ARP Request */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Src mac */
0x00, 0x00, 0x00, 0x00, /* Src IP */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Target mac */
0x00, 0x00, 0x00, 0x00 /* Target IP */
};
/* ************************************** */
/** Build a gratuitous ARP packet for a /24 layer 3 (IP) network. */
static int build_gratuitous_arp(char *buffer, uint16_t buffer_len) {
if(buffer_len < sizeof(gratuitous_arp)) return(-1);
memcpy(buffer, gratuitous_arp, sizeof(gratuitous_arp));
memcpy(&buffer[6], device.mac_addr, 6);
memcpy(&buffer[22], device.mac_addr, 6);
memcpy(&buffer[28], &device.ip_addr, 4);
/* REVISIT: BbMaj7 - use a real netmask here. This is valid only by accident
* for /24 IPv4 networks. */
buffer[31] = 0xFF; /* Use a faked broadcast address */
memcpy(&buffer[38], &device.ip_addr, 4);
return(sizeof(gratuitous_arp));
}
/* ************************************** */
/** Called from update_supernode_reg to periodically send gratuitous ARP
* broadcasts. */
static void send_grat_arps(n2n_edge_t * eee,) {
char buffer[48];
size_t len;
traceEvent(TRACE_NORMAL, "Sending gratuitous ARP...");
len = build_gratuitous_arp(buffer, sizeof(buffer));
send_packet2net(eee, buffer, len);
send_packet2net(eee, buffer, len); /* Two is better than one :-) */
}
#endif /* #if defined(DUMMY_ID_00001) */
/* ***************************************************** */
/** Find the address and IP mode for the tuntap device.
*
* s is one of these forms:
*
* <host> := <hostname> | A.B.C.D
*
* <host> | static:<host> | dhcp:<host>
*
* If the mode is present (colon required) then fill ip_mode with that value
* otherwise do not change ip_mode. Fill ip_mode with everything after the
* colon if it is present; or s if colon is not present.
*
* ip_add and ip_mode are NULL terminated if modified.
*
* return 0 on success and -1 on error
*/
static int scan_address(char * ip_addr, size_t addr_size,
char * ip_mode, size_t mode_size,
const char * s) {
int retval = -1;
char * p;
if((NULL == s) || (NULL == ip_addr))
{
return -1;
}
memset(ip_addr, 0, addr_size);
p = strpbrk(s, ":");
if(p)
{
/* colon is present */
if(ip_mode)
{
size_t end=0;
memset(ip_mode, 0, mode_size);
end = MIN(p-s, (ssize_t)(mode_size-1)); /* ensure NULL term */
strncpy(ip_mode, s, end);
strncpy(ip_addr, p+1, addr_size-1); /* ensure NULL term */
retval = 0;
}
}
else
{
/* colon is not present */
strncpy(ip_addr, s, addr_size);
}
return retval;
}
/* *************************************************** */
int start_edge(const n2n_edge_cmd_t* cmd)
{
int keep_on_running = 0;
int local_port = 0 /* any port */;
char tuntap_dev_name[N2N_IFNAMSIZ] = "tun0";
char ip_mode[N2N_IF_MODE_SIZE]="static";
char ip_addr[N2N_NETMASK_STR_SIZE] = "";
char netmask[N2N_NETMASK_STR_SIZE]="255.255.255.0";
char device_mac[N2N_MACNAMSIZ]="";
char * encrypt_key=NULL;
n2n_edge_t eee;
int i;
keep_on_running = 0;
pthread_mutex_lock(&status.mutex);
status.is_running = keep_on_running;
pthread_mutex_unlock(&status.mutex);
report_edge_status();
if (!cmd) {
traceEvent( TRACE_ERROR, "Empty cmd struct" );
return 1;
}
traceLevel = cmd->trace_vlevel;
traceLevel = traceLevel < 0 ? 0 : traceLevel; /* TRACE_ERROR */
traceLevel = traceLevel > 4 ? 4 : traceLevel; /* TRACE_DEBUG */
if (-1 == edge_init(&eee) )
{
traceEvent( TRACE_ERROR, "Failed in edge_init" );
return 1;
}
memset(&(eee.supernode), 0, sizeof(eee.supernode));
eee.supernode.family = AF_INET;
if (cmd->vpn_fd < 0) {
traceEvent(TRACE_ERROR, "VPN socket is invalid.");
return 1;
}
eee.device.fd = cmd->vpn_fd;
if (cmd->enc_key_file)
{
strncpy(eee.keyschedule, cmd->enc_key_file, N2N_PATHNAME_MAXLEN-1);
eee.keyschedule[N2N_PATHNAME_MAXLEN-1]=0; /* strncpy does not add NULL if the source has no NULL. */
traceEvent(TRACE_DEBUG, "keyfile = '%s'\n", eee.keyschedule);
}
else if (cmd->enc_key)
{
encrypt_key = strdup(cmd->enc_key);
traceEvent(TRACE_DEBUG, "encrypt_key = '%s'\n", encrypt_key);
}
if (cmd->ip_addr[0] != '\0')
{
scan_address(ip_addr, N2N_NETMASK_STR_SIZE,
ip_mode, N2N_IF_MODE_SIZE,
cmd->ip_addr);
}
else
{
traceEvent(TRACE_ERROR, "Ip address is not set.");
free(encrypt_key);
return 1;
}
if (cmd->community[0] != '\0')
{
strncpy((char *)eee.community_name, cmd->community, N2N_COMMUNITY_SIZE);
}
else
{
traceEvent(TRACE_ERROR, "Community is not set.");
free(encrypt_key);
return 1;
}
eee.drop_multicast = cmd->drop_multicast == 0 ? 0 : 1;
if (cmd->mac_addr[0] != '\0')
{
strncpy(device_mac, cmd->mac_addr, N2N_MACNAMSIZ);
}
else
{
strncpy(device_mac, random_device_mac(), N2N_MACNAMSIZ);
traceEvent(TRACE_DEBUG, "random device mac: %s\n", device_mac);
}
eee.allow_routing = cmd->allow_routing == 0 ? 0 : 1;
for (i = 0; i < N2N_EDGE_NUM_SUPERNODES && i < EDGE_CMD_SUPERNODES_NUM; ++i)
{
if (cmd->supernodes[i][0] != '\0')
{
strncpy(eee.sn_ip_array[eee.sn_num], cmd->supernodes[i], N2N_EDGE_SN_HOST_SIZE);
traceEvent(TRACE_DEBUG, "Adding supernode[%u] = %s\n", (unsigned int)eee.sn_num, (eee.sn_ip_array[eee.sn_num]));
++eee.sn_num;
}
}
eee.re_resolve_supernode_ip = cmd->re_resolve_supernode_ip == 0 ? 0 : 1;
if (cmd->ip_netmask[0] != '\0')
{
strncpy(netmask, cmd->ip_netmask, N2N_NETMASK_STR_SIZE);
}
for (i=0; i< N2N_EDGE_NUM_SUPERNODES; ++i )
{
traceEvent(TRACE_NORMAL, "supernode %u => %s\n", i, (eee.sn_ip_array[i]));
}
supernode2addr(&(eee.supernode), eee.sn_ip_array[eee.sn_idx]);
if (encrypt_key == NULL && strlen(eee.keyschedule) == 0)
{
traceEvent(TRACE_WARNING, "Encryption is disabled in edge.");
eee.null_transop = 1;
}
if (0 == strcmp("dhcp", ip_mode))
{
traceEvent(TRACE_NORMAL, "Dynamic IP address assignment enabled.");
eee.dyn_ip_mode = 1;
}
else
{
traceEvent(TRACE_NORMAL, "ip_mode='%s'", ip_mode);
}
if(tuntap_open(&(eee.device), tuntap_dev_name, ip_mode, ip_addr, netmask, device_mac, cmd->mtu) < 0)
{
traceEvent(TRACE_ERROR, "Failed in tuntap_open");
free(encrypt_key);
return 1;
}
if(local_port > 0)
{
traceEvent(TRACE_NORMAL, "Binding to local port %d", (signed int)local_port);
}
if (encrypt_key)
{
if(edge_init_twofish(&eee, (uint8_t *)(encrypt_key), strlen(encrypt_key)) < 0)
{
traceEvent(TRACE_ERROR, "twofish setup failed.\n");
free(encrypt_key);
return 1;
}
free(encrypt_key);
encrypt_key = NULL;
}
else if (strlen(eee.keyschedule) > 0)
{
if (edge_init_keyschedule(&eee) != 0)
{
traceEvent(TRACE_ERROR, "keyschedule setup failed.\n");
free(encrypt_key);
return 1;
}
}
/* else run in NULL mode */
eee.udp_sock = open_socket(local_port, 1 /*bind ANY*/ );
if(eee.udp_sock < 0)
{
traceEvent(TRACE_ERROR, "Failed to bind main UDP port %u", (signed int)local_port);
return 1;
}
eee.udp_mgmt_sock = open_socket(N2N_EDGE_MGMT_PORT, 0 /* bind LOOPBACK*/ );
if(eee.udp_mgmt_sock < 0)
{
traceEvent( TRACE_ERROR, "Failed to bind management UDP port %u", (unsigned int)N2N_EDGE_MGMT_PORT );
return 1;
}
/* set host addr, netmask, mac addr for UIP and init arp*/
{
int match, i;
u8_t ip[4];
uip_ipaddr_t ipaddr;
struct uip_eth_addr eaddr;
match = sscanf(ip_addr, "%d.%d.%d.%d", ip, ip + 1, ip + 2, ip + 3);
if (match != 4) {
traceEvent(TRACE_ERROR, "scan ip failed, ip: %s", ip_addr);
return 1;
}
uip_ipaddr(ipaddr, ip[0], ip[1], ip[2], ip[3]);
uip_sethostaddr(ipaddr);
match = sscanf(netmask, "%d.%d.%d.%d", ip, ip + 1, ip + 2, ip + 3);
if (match != 4) {
traceEvent(TRACE_ERROR, "scan netmask error, ip: %s", netmask);
return 1;
}
uip_ipaddr(ipaddr, ip[0], ip[1], ip[2], ip[3]);
uip_setnetmask(ipaddr);
for (i = 0; i < 6; ++i) {
eaddr.addr[i] = eee.device.mac_addr[i];
}
uip_setethaddr(eaddr);
uip_arp_init();
}
keep_on_running = 1;
pthread_mutex_lock(&status.mutex);
status.is_running = keep_on_running;
pthread_mutex_unlock(&status.mutex);
report_edge_status();
traceEvent(TRACE_NORMAL, "edge started");
update_supernode_reg(&eee, time(NULL));
return run_edge_loop(&eee, &keep_on_running);
}
int stop_edge(void)
{
// quick stop
int fd = open_socket(0, 0 /* bind LOOPBACK*/ );
if (fd < 0) {
return 1;
}
struct sockaddr_in peer_addr;
peer_addr.sin_family = PF_INET;
peer_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
peer_addr.sin_port = htons(N2N_EDGE_MGMT_PORT);
sendto(fd, "stop", 4, 0, (struct sockaddr *)&peer_addr, sizeof(struct sockaddr_in));
pthread_mutex_lock(&status.mutex);
status.is_running = 0;
pthread_mutex_unlock(&status.mutex);
report_edge_status();
return 0;
}
#endif /* #ifdef __ANDROID_NDK__ */
/* ************************************** */

64
android/edge_android.h Normal file
View File

@ -0,0 +1,64 @@
//
// Created by switchwang(https://github.com/switch-st) on 2018-04-13.
//
#ifndef _EDGE_ANDROID_H_
#define _EDGE_ANDROID_H_
#ifdef __ANDROID_NDK__
#include "../n2n.h"
#include <pthread.h>
#define EDGE_CMD_IPSTR_SIZE 16
#define EDGE_CMD_SUPERNODES_NUM 2
#define EDGE_CMD_SN_HOST_SIZE 48
#define EDGE_CMD_MACNAMSIZ 18
typedef struct n2n_edge_cmd_st
{
char ip_addr[EDGE_CMD_IPSTR_SIZE];
char ip_netmask[EDGE_CMD_IPSTR_SIZE];
char supernodes[EDGE_CMD_SUPERNODES_NUM][EDGE_CMD_SN_HOST_SIZE];
char community[N2N_COMMUNITY_SIZE];
char* enc_key;
char* enc_key_file;
char mac_addr[EDGE_CMD_MACNAMSIZ];
unsigned int mtu;
int re_resolve_supernode_ip;
unsigned int local_port;
int allow_routing;
int drop_multicast;
int trace_vlevel;
int vpn_fd;
} n2n_edge_cmd_t;
typedef struct n2n_edge_status_st
{
pthread_mutex_t mutex;
uint8_t is_running;
} n2n_edge_status;
#define INIT_EDGE_CMD(cmd) do {\
memset(&(cmd), 0, sizeof((cmd))); \
(cmd).enc_key = NULL; \
(cmd).enc_key_file = NULL; \
(cmd).mtu = 1400; \
(cmd).re_resolve_supernode_ip = 0;\
(cmd).local_port = 0; \
(cmd).allow_routing = 0; \
(cmd).drop_multicast = 1; \
(cmd).trace_vlevel = 2; \
(cmd).vpn_fd = -1; \
} while (0);
n2n_edge_status status;
int start_edge(const n2n_edge_cmd_t* cmd);
int stop_edge(void);
void report_edge_status(void);
#endif /* __ANDROID_NDK__ */
#endif //_EDGE_ANDROID_H_

405
android/edge_jni.c Normal file
View File

@ -0,0 +1,405 @@
//
// Created by switchwang(https://github.com/switch-st) on 2018-04-15.
//
#include <jni.h>
#include <pthread.h>
#include "edge_android.h"
static int GetEdgeCmd(JNIEnv *env, jobject jcmd, n2n_edge_cmd_t* cmd);
static void* EdgeRoutine(void* cmd);
static n2n_edge_cmd_t cmd;
static pthread_t tid = -1;
static JavaVM* jvm = NULL;
static jobject jobj_service = NULL;
static jclass jcls_status = NULL;
JNIEXPORT jboolean JNICALL Java_wang_switchy_hin2n_service_N2NService_startEdge(
JNIEnv *env,
jobject this,
jobject jcmd) {
#ifndef NDEBUG
__android_log_write(LOG_DEBUG, "edge_jni", "in start");
#endif /* #ifndef NDEBUG */
if (GetEdgeCmd(env, jcmd, &cmd) != 0) {
goto ERROR;
}
int val = fcntl(cmd.vpn_fd, F_GETFL);
if (val == -1) {
goto ERROR;
}
if ((val & O_NONBLOCK) == O_NONBLOCK) {
val &= ~O_NONBLOCK;
val = fcntl(cmd.vpn_fd, F_SETFL, val);
if (val == -1) {
goto ERROR;
}
}
if (tid != -1) {
stop_edge();
pthread_kill(tid, SIGINT);
pthread_join(tid, NULL);
tid = -1;
if (jcls_status) {
(*env)->DeleteGlobalRef(env, jcls_status);
jcls_status = NULL;
}
if (jobj_service) {
(*env)->DeleteGlobalRef(env, jobj_service);
jobj_service = NULL;
}
jvm = NULL;
pthread_mutex_destroy(&status.mutex);
}
if ((*env)->GetJavaVM(env, &jvm) != JNI_OK) {
goto ERROR;
}
jobj_service = (*env)->NewGlobalRef(env, this);
jclass cls = (*env)->FindClass(env, "wang/switchy/hin2n/model/EdgeStatus");
if (!cls) {
goto ERROR;
}
jcls_status = (*env)->NewGlobalRef(env, cls);
pthread_mutex_init(&status.mutex, NULL);
int ret = pthread_create(&tid, NULL, EdgeRoutine, &cmd);
if (ret != 0) {
tid = -1;
goto ERROR;
}
return JNI_TRUE;
ERROR:
if (jcls_status) {
(*env)->DeleteGlobalRef(env, jcls_status);
jcls_status = NULL;
}
if (jobj_service) {
(*env)->DeleteGlobalRef(env, jobj_service);
jobj_service = NULL;
}
jvm = NULL;
pthread_mutex_destroy(&status.mutex);
free(cmd.enc_key);
free(cmd.enc_key_file);
cmd.enc_key = NULL;
cmd.enc_key_file = NULL;
return JNI_FALSE;
}
JNIEXPORT void JNICALL Java_wang_switchy_hin2n_service_N2NService_stopEdge(
JNIEnv *env,
jobject this) {
#ifndef NDEBUG
__android_log_write(LOG_DEBUG, "edge_jni", "in stop");
#endif /* #ifndef NDEBUG */
stop_edge();
pthread_join(tid, NULL);
tid = -1;
if (jcls_status) {
(*env)->DeleteGlobalRef(env, jcls_status);
jcls_status = NULL;
}
if (jobj_service) {
(*env)->DeleteGlobalRef(env, jobj_service);
jobj_service = NULL;
}
jvm = NULL;
pthread_mutex_destroy(&status.mutex);
}
JNIEXPORT jobject JNICALL Java_wang_switchy_hin2n_service_N2NService_getEdgeStatus(
JNIEnv *env,
jobject this) {
jboolean is_running = JNI_FALSE;
if (tid != -1) {
is_running = pthread_kill(tid, 0) ? JNI_FALSE : JNI_TRUE;
pthread_mutex_lock(&status.mutex);
is_running = is_running && status.is_running;
pthread_mutex_unlock(&status.mutex);
}
jclass cls = (*env)->FindClass(env, "wang/switchy/hin2n/model/EdgeStatus");
jobject jStatus = (*env)->NewObject(env, cls, (*env)->GetMethodID(env, cls, "<init>", "()V"));
if (!jStatus) {
return NULL;
}
(*env)->SetBooleanField(env, jStatus, (*env)->GetFieldID(env, cls, "isRunning", "Z"), is_running);
return jStatus;
}
/////////////////////////////////////////////////////////////////////////
#ifndef JNI_CHECKNULL
#define JNI_CHECKNULL(p) do { if (!(p)) return 1;}while(0)
#endif /* JNI_CHECKNULL */
int GetEdgeCmd(JNIEnv *env, jobject jcmd, n2n_edge_cmd_t* cmd)
{
jclass cls;
int i, j;
INIT_EDGE_CMD(*cmd);
cls = (*env)->GetObjectClass(env, jcmd);
JNI_CHECKNULL(cls);
// ipAddr
{
jstring jsIpAddr = (*env)->GetObjectField(env, jcmd, (*env)->GetFieldID(env, cls, "ipAddr", "Ljava/lang/String;"));
JNI_CHECKNULL(jsIpAddr);
const char* ipAddr = (*env)->GetStringUTFChars(env, jsIpAddr, NULL);
if (!ipAddr || strlen(ipAddr) == 0) {
(*env)->ReleaseStringUTFChars(env, jsIpAddr, ipAddr);
return 1;
}
strncpy(cmd->ip_addr, ipAddr, EDGE_CMD_IPSTR_SIZE);
(*env)->ReleaseStringUTFChars(env, jsIpAddr, ipAddr);
#ifndef NDEBUG
__android_log_print(LOG_DEBUG, "edge_jni", "ipAddr = %s", cmd->ip_addr);
#endif /* #ifndef NDEBUG */
}
// ipNetmask
{
jstring jsIpNetmask = (*env)->GetObjectField(env, jcmd, (*env)->GetFieldID(env, cls, "ipNetmask", "Ljava/lang/String;"));
JNI_CHECKNULL(jsIpNetmask);
const char* ipNetmask = (*env)->GetStringUTFChars(env, jsIpNetmask, NULL);
if (!ipNetmask || strlen(ipNetmask) == 0) {
(*env)->ReleaseStringUTFChars(env, jsIpNetmask, ipNetmask);
return 1;
}
strncpy(cmd->ip_netmask, ipNetmask, EDGE_CMD_IPSTR_SIZE);
(*env)->ReleaseStringUTFChars(env, jsIpNetmask, ipNetmask);
#ifndef NDEBUG
__android_log_print(LOG_DEBUG, "edge_jni", "ipNetmask = %s", cmd->ip_netmask);
#endif /* #ifndef NDEBUG */
}
// supernodes
{
jarray jaSupernodes = (*env)->GetObjectField(env, jcmd, (*env)->GetFieldID(env, cls, "supernodes", "[Ljava/lang/String;"));
JNI_CHECKNULL(jaSupernodes);
int len = (*env)->GetArrayLength(env, jaSupernodes);
if (len <= 0) {
return 1;
}
for (i = 0, j = 0; i < len && i < EDGE_CMD_SUPERNODES_NUM; ++i) {
const jobject jsNode = (*env)->GetObjectArrayElement(env, jaSupernodes, i);
if (!jsNode) {
continue;
}
const char* node = (*env)->GetStringUTFChars(env, jsNode, NULL);
if (!node || strlen(node) == 0) {
(*env)->ReleaseStringUTFChars(env, jsNode, node);
continue;
}
strncpy(cmd->supernodes[j], node, EDGE_CMD_SN_HOST_SIZE);
(*env)->ReleaseStringUTFChars(env, jsNode, node);
#ifndef NDEBUG
__android_log_print(LOG_DEBUG, "edge_jni", "supernodes = %s", cmd->supernodes[j]);
#endif /* #ifndef NDEBUG */
j++;
}
#ifndef NDEBUG
__android_log_print(LOG_DEBUG, "edge_jni", "j = %d", j);
#endif /* #ifndef NDEBUG */
if (j == 0) {
return 1;
}
}
// community
{
jstring jsCommunity = (*env)->GetObjectField(env, jcmd, (*env)->GetFieldID(env, cls, "community", "Ljava/lang/String;"));
JNI_CHECKNULL(jsCommunity);
const char* community = (*env)->GetStringUTFChars(env, jsCommunity, NULL);
if (!community || strlen(community) == 0) {
(*env)->ReleaseStringUTFChars(env, jsCommunity, community);
return 1;
}
strncpy(cmd->community, community, N2N_COMMUNITY_SIZE);
(*env)->ReleaseStringUTFChars(env, jsCommunity, community);
#ifndef NDEBUG
__android_log_print(LOG_DEBUG, "edge_jni", "community = %s", cmd->community);
#endif /* #ifndef NDEBUG */
}
// encKey
{
jstring jsEncKey = (*env)->GetObjectField(env, jcmd, (*env)->GetFieldID(env, cls, "encKey", "Ljava/lang/String;"));
if (jsEncKey) {
const char* encKey = (*env)->GetStringUTFChars(env, jsEncKey, NULL);
if (encKey && strlen(encKey) != 0) {
cmd->enc_key = strdup(encKey);
}
(*env)->ReleaseStringUTFChars(env, jsEncKey, encKey);
#ifndef NDEBUG
__android_log_print(LOG_DEBUG, "edge_jni", "encKey = %s", cmd->enc_key);
#endif /* #ifndef NDEBUG */
}
}
// encKeyFile
{
jstring jsEncKeyFile = (*env)->GetObjectField(env, jcmd, (*env)->GetFieldID(env, cls, "encKeyFile", "Ljava/lang/String;"));
if (jsEncKeyFile) {
const char* encKeyFile = (*env)->GetStringUTFChars(env, jsEncKeyFile, NULL);
if (encKeyFile && strlen(encKeyFile) != 0) {
cmd->enc_key_file = strdup(encKeyFile);
}
(*env)->ReleaseStringUTFChars(env, jsEncKeyFile, encKeyFile);
#ifndef NDEBUG
__android_log_print(LOG_DEBUG, "edge_jni", "encKeyFile = %s", cmd->enc_key_file);
#endif /* #ifndef NDEBUG */
}
}
// macAddr
{
jstring jsMacAddr = (*env)->GetObjectField(env, jcmd, (*env)->GetFieldID(env, cls, "macAddr", "Ljava/lang/String;"));
JNI_CHECKNULL(jsMacAddr);
const char* macAddr = (*env)->GetStringUTFChars(env, jsMacAddr, NULL);
if (macAddr && strlen(macAddr) != 0) {
strncpy(cmd->mac_addr, macAddr, EDGE_CMD_MACNAMSIZ);
}
(*env)->ReleaseStringUTFChars(env, jsMacAddr, macAddr);
#ifndef NDEBUG
__android_log_print(LOG_DEBUG, "edge_jni", "macAddr = %s", cmd->mac_addr);
#endif /* #ifndef NDEBUG */
}
// mtu
{
jint jiMtu = (*env)->GetIntField(env, jcmd, (*env)->GetFieldID(env, cls, "mtu", "I"));
if (jiMtu <= 0) {
return 1;
}
cmd->mtu = jiMtu;
#ifndef NDEBUG
__android_log_print(LOG_DEBUG, "edge_jni", "mtu = %d", cmd->mtu);
#endif /* #ifndef NDEBUG */
}
// reResoveSupernodeIP
{
jboolean jbReResoveSupernodeIP= (*env)->GetBooleanField(env, jcmd, (*env)->GetFieldID(env, cls, "reResoveSupernodeIP", "Z"));
cmd->re_resolve_supernode_ip = jbReResoveSupernodeIP ? 1 : 0;
#ifndef NDEBUG
__android_log_print(LOG_DEBUG, "edge_jni", "reResoveSupernodeIP = %d", cmd->re_resolve_supernode_ip);
#endif /* #ifndef NDEBUG */
}
// localPort
{
jint jiLocalPort = (*env)->GetIntField(env, jcmd, (*env)->GetFieldID(env, cls, "localPort", "I"));
if (jiLocalPort < 0) {
return 1;
}
cmd->local_port = jiLocalPort;
#ifndef NDEBUG
__android_log_print(LOG_DEBUG, "edge_jni", "localPort = %d", cmd->local_port);
#endif /* #ifndef NDEBUG */
}
// allowRouting
{
jboolean jbAllowRouting= (*env)->GetBooleanField(env, jcmd, (*env)->GetFieldID(env, cls, "allowRouting", "Z"));
cmd->allow_routing = jbAllowRouting ? 1 : 0;
#ifndef NDEBUG
__android_log_print(LOG_DEBUG, "edge_jni", "allowRouting = %d", cmd->allow_routing);
#endif /* #ifndef NDEBUG */
}
// dropMuticast
{
jboolean jbDropMuticast= (*env)->GetBooleanField(env, jcmd, (*env)->GetFieldID(env, cls, "dropMuticast", "Z"));
cmd->drop_multicast = jbDropMuticast ? 1 : 0;
#ifndef NDEBUG
__android_log_print(LOG_DEBUG, "edge_jni", "dropMuticast = %d", cmd->drop_multicast);
#endif /* #ifndef NDEBUG */
}
// traceLevel
{
jint jiTraceLevel = (*env)->GetIntField(env, jcmd, (*env)->GetFieldID(env, cls, "traceLevel", "I"));
cmd->trace_vlevel = jiTraceLevel;
#ifndef NDEBUG
__android_log_print(LOG_DEBUG, "edge_jni", "traceLevel = %d", cmd->trace_vlevel);
#endif /* #ifndef NDEBUG */
}
// vpnFd
{
jint jiVpnFd = (*env)->GetIntField(env, jcmd, (*env)->GetFieldID(env, cls, "vpnFd", "I"));
if (jiVpnFd < 0) {
return 1;
}
cmd->vpn_fd = jiVpnFd;
#ifndef NDEBUG
__android_log_print(LOG_DEBUG, "edge_jni", "vpnFd = %d", cmd->vpn_fd);
#endif /* #ifndef NDEBUG */
}
return 0;
}
void* EdgeRoutine(void* cmd)
{
int flag = 0;
if (jvm) {
JNIEnv* env = NULL;
if ((*jvm)->AttachCurrentThread(jvm, &env, NULL) == JNI_OK) {
flag = 1;
}
}
n2n_edge_cmd_t* c = cmd;
int ret = start_edge(c);
free(c->enc_key);
free(c->enc_key_file);
c->enc_key = NULL;
c->enc_key_file = NULL;
if (flag && jvm) {
(*jvm)->DetachCurrentThread(jvm);
}
return (void*)ret;
}
void report_edge_status(void)
{
if (!jvm || !jobj_service || !jcls_status || tid == -1) {
return;
}
jboolean is_running = JNI_FALSE;
pthread_mutex_lock(&status.mutex);
is_running = status.is_running;
pthread_mutex_unlock(&status.mutex);
JNIEnv* env = NULL;
if ((*jvm)->GetEnv(jvm, &env, JNI_VERSION_1_1) != JNI_OK || !env) {
return;
}
jmethodID mid = (*env)->GetMethodID(env, jcls_status, "<init>", "()V");
if (!mid) {
return;
}
jobject jStatus = (*env)->NewObject(env, jcls_status, mid);
if (!jStatus) {
return;
}
jfieldID fid = (*env)->GetFieldID(env, jcls_status, "isRunning", "Z");
if (!fid) {
return;
}
(*env)->SetBooleanField(env, jStatus, fid, is_running);
jclass cls = (*env)->GetObjectClass(env, jobj_service);
if (!cls) {
return;
}
mid = (*env)->GetMethodID(env, cls, "reportEdgeStatus", "(Lwang/switchy/hin2n/model/EdgeStatus;)V");
if (!mid) {
return;
}
(*env)->CallVoidMethod(env, jobj_service, mid, jStatus);
(*env)->DeleteLocalRef(env, jStatus);
}

View File

@ -0,0 +1,9 @@
//
// Created by switchwang(https://github.com/switch-st) on 2018-04-20.
//
#include "tun2tap.h"
u8_t* uip_buf = NULL;
u8_t uip_arp_buf[UIP_LLH_LEN + UIP_ARP_LEN];
u16_t uip_arp_len = 0;

53
android/tun2tap/tun2tap.h Normal file
View File

@ -0,0 +1,53 @@
//
// Created by switchwang(https://github.com/switch-st) on 2018-04-14.
//
#ifndef _TUN2TAP_H_
#define _TUN2TAP_H_
#ifdef HTONS
#undef HTONS
#endif
#include "uip-conf.h"
#include <uip/uip.h>
#include <uip/uip_arp.h>
#define UIP_ARP_LEN 28
struct arp_hdr {
struct uip_eth_hdr ethhdr;
u16_t hwtype;
u16_t protocol;
u8_t hwlen;
u8_t protolen;
u16_t opcode;
struct uip_eth_addr shwaddr;
u16_t sipaddr[2];
struct uip_eth_addr dhwaddr;
u16_t dipaddr[2];
};
struct ethip_hdr {
struct uip_eth_hdr ethhdr;
/* IP header. */
u8_t vhl,
tos,
len[2],
ipid[2],
ipoffset[2],
ttl,
proto;
u16_t ipchksum;
u16_t srcipaddr[2],
destipaddr[2];
};
#define BUF ((struct arp_hdr *)&uip_buf[0])
#define IPBUF ((struct ethip_hdr *)&uip_buf[0])
extern u8_t* uip_buf;
extern u8_t uip_arp_buf[UIP_LLH_LEN + UIP_ARP_LEN];
extern u16_t uip_arp_len;
#endif //_TUN2TAP_H_

View File

@ -0,0 +1,13 @@
//
// Created by switchwang(https://github.com/switch-st) on 2018-04-14.
//
#ifndef _TUN2TAP_DEFINE_H_
#define _TUN2TAP_DEFINE_H_
#define uip_tcp_appstate_t void*
#define UIP_APPCALL()
extern u8_t* uip_buf;
#endif //_TUN2TAP_DEFINE_H_

163
android/tun2tap/uip-conf.h Normal file
View File

@ -0,0 +1,163 @@
/**
* \addtogroup uipopt
* @{
*/
/**
* \name Project-specific configuration options
* @{
*
* uIP has a number of configuration options that can be overridden
* for each project. These are kept in a project-specific uip-conf.h
* file and all configuration names have the prefix UIP_CONF.
*/
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* 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 above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE 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 INSTITUTE 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.
*
* This file is part of the uIP TCP/IP stack
*
* $Id: uip-conf.h,v 1.6 2006/06/12 08:00:31 adam Exp $
*/
/**
* \file
* An example uIP configuration file
* \author
* Adam Dunkels <adam@sics.se>
*/
#ifndef __UIP_CONF_H__
#define __UIP_CONF_H__
#include <inttypes.h>
/**
* 8 bit datatype
*
* This typedef defines the 8-bit type used throughout uIP.
*
* \hideinitializer
*/
typedef uint8_t u8_t;
/**
* 16 bit datatype
*
* This typedef defines the 16-bit type used throughout uIP.
*
* \hideinitializer
*/
typedef uint16_t u16_t;
/**
* Statistics datatype
*
* This typedef defines the dataype used for keeping statistics in
* uIP.
*
* \hideinitializer
*/
typedef unsigned short uip_stats_t;
/**
* Maximum number of TCP connections.
*
* \hideinitializer
*/
#define UIP_CONF_MAX_CONNECTIONS 40
/**
* Maximum number of listening TCP ports.
*
* \hideinitializer
*/
#define UIP_CONF_MAX_LISTENPORTS 40
/**
* uIP buffer size.
*
* \hideinitializer
*/
/*#define UIP_CONF_BUFFER_SIZE 420*/
#define UIP_CONF_BUFFER_SIZE 2048
/**
* Manually define the uip_buf.
*
* \hideinitializer
*/
#define UIP_CONF_EXTERNAL_BUFFER
/**
* CPU byte order.
* Defined in CMakeList.txt
*
* \hideinitializer
*/
#ifndef UIP_CONF_BYTE_ORDER
#define UIP_CONF_BYTE_ORDER UIP_LITTLE_ENDIAN
#endif
/**
* Logging on or off
*
* \hideinitializer
*/
/*#define UIP_CONF_LOGGING 1*/
#define UIP_CONF_LOGGING 0
/**
* UDP support on or off
*
* \hideinitializer
*/
#define UIP_CONF_UDP 0
/**
* UDP checksums on or off
*
* \hideinitializer
*/
#define UIP_CONF_UDP_CHECKSUMS 1
/**
* uIP statistics on or off
*
* \hideinitializer
*/
#define UIP_CONF_STATISTICS 1
/* Here we include the header file for the application(s) we use in
our project. */
#include "tun2tap_appdef.h"
#endif /* __UIP_CONF_H__ */
/** @} */
/** @} */

107
android/tuntap_android.c Normal file
View File

@ -0,0 +1,107 @@
/*
* (C) 2007-09 - 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 __ANDROID_NDK__
#include <tun2tap/tun2tap.h>
/* ********************************** */
/** @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
* @param mtu - MTU 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 */
const char *address_mode, /* static or dhcp */
char *device_ip,
char *device_mask,
const char * device_mac,
int mtu) {
int i, n_matched;
unsigned int mac[6];
n_matched = sscanf(device_mac, "%x:%x:%x:%x:%x:%x", mac, mac + 1, mac + 2, mac + 3, mac + 4, mac + 5);
if (n_matched != 6) {
return -1;
}
memset(device->mac_addr, 0, sizeof(device->mac_addr));
for (i = 0; i < 6; i++)
device->mac_addr[i] = mac[i];
device->ip_addr = inet_addr(device_ip);
device->device_mask = inet_addr(device_mask);
device->mtu = mtu;
strncpy(device->dev_name, dev, MIN(IFNAMSIZ, N2N_IFNAMSIZ));
return device->fd;
}
int tuntap_read(struct tuntap_dev *tuntap, unsigned char *buf, int len) {
int rlen = read(tuntap->fd, buf + UIP_LLH_LEN, len - UIP_LLH_LEN);
if ((rlen <= 0) || (rlen > N2N_PKT_BUF_SIZE - UIP_LLH_LEN))
{
return rlen;
}
uip_buf = buf;
uip_len = rlen;
uip_arp_out();
if (IPBUF->ethhdr.type == htons(UIP_ETHTYPE_ARP))
{
traceEvent(TRACE_DEBUG, "ARP request packets are sent instead of packets");
}
return uip_len;
}
int tuntap_write(struct tuntap_dev *tuntap, unsigned char *buf, int len) {
uip_buf = buf;
uip_len = len;
if (IPBUF->ethhdr.type == htons(UIP_ETHTYPE_IP)) {
return write(tuntap->fd, buf + UIP_LLH_LEN, len - UIP_LLH_LEN);
} else if (IPBUF->ethhdr.type == htons(UIP_ETHTYPE_ARP)) {
uip_arp_arpin();
if (uip_len > 0) {
uip_arp_len = uip_len;
memcpy(uip_arp_buf, uip_buf, uip_arp_len);
traceEvent(TRACE_DEBUG, "ARP reply packet prepare to send");
}
return uip_len;
}
errno = EINVAL;
return -1;
}
void tuntap_close(struct tuntap_dev *tuntap) {
close(tuntap->fd);
}
void tuntap_get_address(struct tuntap_dev *tuntap) {
}
#endif /* #ifdef __ANDROID_NDK__ */

13
android/uip/README Normal file
View File

@ -0,0 +1,13 @@
uIP is a very small implementation of the TCP/IP stack that is written
by Adam Dunkels <adam@sics.se>. More information can be obtained
at the uIP homepage at http://www.sics.se/~adam/uip/.
This is version $Name: uip-1-0 $.
The directory structure look as follows:
apps/ - Example applications
doc/ - Documentation
lib/ - Library code used by some applications
uip/ - uIP TCP/IP stack code
unix/ - uIP as a user space process under FreeBSD or Linux

2
android/uip/apps/README Normal file
View File

@ -0,0 +1,2 @@
This directory contains a few example applications. They are not all
heavily tested, however.

View File

@ -0,0 +1 @@
APP_SOURCES += dhcpc.c timer.c

View File

@ -0,0 +1,356 @@
/*
* Copyright (c) 2005, Swedish Institute of Computer Science
* 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 above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE 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 INSTITUTE 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.
*
* This file is part of the uIP TCP/IP stack
*
* @(#)$Id: dhcpc.c,v 1.2 2006/06/11 21:46:37 adam Exp $
*/
#include <stdio.h>
#include <string.h>
#include "uip.h"
#include "dhcpc.h"
#include "timer.h"
#include "pt.h"
#define STATE_INITIAL 0
#define STATE_SENDING 1
#define STATE_OFFER_RECEIVED 2
#define STATE_CONFIG_RECEIVED 3
static struct dhcpc_state s;
struct dhcp_msg {
u8_t op, htype, hlen, hops;
u8_t xid[4];
u16_t secs, flags;
u8_t ciaddr[4];
u8_t yiaddr[4];
u8_t siaddr[4];
u8_t giaddr[4];
u8_t chaddr[16];
#ifndef UIP_CONF_DHCP_LIGHT
u8_t sname[64];
u8_t file[128];
#endif
u8_t options[312];
};
#define BOOTP_BROADCAST 0x8000
#define DHCP_REQUEST 1
#define DHCP_REPLY 2
#define DHCP_HTYPE_ETHERNET 1
#define DHCP_HLEN_ETHERNET 6
#define DHCP_MSG_LEN 236
#define DHCPC_SERVER_PORT 67
#define DHCPC_CLIENT_PORT 68
#define DHCPDISCOVER 1
#define DHCPOFFER 2
#define DHCPREQUEST 3
#define DHCPDECLINE 4
#define DHCPACK 5
#define DHCPNAK 6
#define DHCPRELEASE 7
#define DHCP_OPTION_SUBNET_MASK 1
#define DHCP_OPTION_ROUTER 3
#define DHCP_OPTION_DNS_SERVER 6
#define DHCP_OPTION_REQ_IPADDR 50
#define DHCP_OPTION_LEASE_TIME 51
#define DHCP_OPTION_MSG_TYPE 53
#define DHCP_OPTION_SERVER_ID 54
#define DHCP_OPTION_REQ_LIST 55
#define DHCP_OPTION_END 255
static const u8_t xid[4] = {0xad, 0xde, 0x12, 0x23};
static const u8_t magic_cookie[4] = {99, 130, 83, 99};
/*---------------------------------------------------------------------------*/
static u8_t *
add_msg_type(u8_t *optptr, u8_t type)
{
*optptr++ = DHCP_OPTION_MSG_TYPE;
*optptr++ = 1;
*optptr++ = type;
return optptr;
}
/*---------------------------------------------------------------------------*/
static u8_t *
add_server_id(u8_t *optptr)
{
*optptr++ = DHCP_OPTION_SERVER_ID;
*optptr++ = 4;
memcpy(optptr, s.serverid, 4);
return optptr + 4;
}
/*---------------------------------------------------------------------------*/
static u8_t *
add_req_ipaddr(u8_t *optptr)
{
*optptr++ = DHCP_OPTION_REQ_IPADDR;
*optptr++ = 4;
memcpy(optptr, s.ipaddr, 4);
return optptr + 4;
}
/*---------------------------------------------------------------------------*/
static u8_t *
add_req_options(u8_t *optptr)
{
*optptr++ = DHCP_OPTION_REQ_LIST;
*optptr++ = 3;
*optptr++ = DHCP_OPTION_SUBNET_MASK;
*optptr++ = DHCP_OPTION_ROUTER;
*optptr++ = DHCP_OPTION_DNS_SERVER;
return optptr;
}
/*---------------------------------------------------------------------------*/
static u8_t *
add_end(u8_t *optptr)
{
*optptr++ = DHCP_OPTION_END;
return optptr;
}
/*---------------------------------------------------------------------------*/
static void
create_msg(register struct dhcp_msg *m)
{
m->op = DHCP_REQUEST;
m->htype = DHCP_HTYPE_ETHERNET;
m->hlen = s.mac_len;
m->hops = 0;
memcpy(m->xid, xid, sizeof(m->xid));
m->secs = 0;
m->flags = HTONS(BOOTP_BROADCAST); /* Broadcast bit. */
/* uip_ipaddr_copy(m->ciaddr, uip_hostaddr);*/
memcpy(m->ciaddr, uip_hostaddr, sizeof(m->ciaddr));
memset(m->yiaddr, 0, sizeof(m->yiaddr));
memset(m->siaddr, 0, sizeof(m->siaddr));
memset(m->giaddr, 0, sizeof(m->giaddr));
memcpy(m->chaddr, s.mac_addr, s.mac_len);
memset(&m->chaddr[s.mac_len], 0, sizeof(m->chaddr) - s.mac_len);
#ifndef UIP_CONF_DHCP_LIGHT
memset(m->sname, 0, sizeof(m->sname));
memset(m->file, 0, sizeof(m->file));
#endif
memcpy(m->options, magic_cookie, sizeof(magic_cookie));
}
/*---------------------------------------------------------------------------*/
static void
send_discover(void)
{
u8_t *end;
struct dhcp_msg *m = (struct dhcp_msg *)uip_appdata;
create_msg(m);
end = add_msg_type(&m->options[4], DHCPDISCOVER);
end = add_req_options(end);
end = add_end(end);
uip_send(uip_appdata, end - (u8_t *)uip_appdata);
}
/*---------------------------------------------------------------------------*/
static void
send_request(void)
{
u8_t *end;
struct dhcp_msg *m = (struct dhcp_msg *)uip_appdata;
create_msg(m);
end = add_msg_type(&m->options[4], DHCPREQUEST);
end = add_server_id(end);
end = add_req_ipaddr(end);
end = add_end(end);
uip_send(uip_appdata, end - (u8_t *)uip_appdata);
}
/*---------------------------------------------------------------------------*/
static u8_t
parse_options(u8_t *optptr, int len)
{
u8_t *end = optptr + len;
u8_t type = 0;
while(optptr < end) {
switch(*optptr) {
case DHCP_OPTION_SUBNET_MASK:
memcpy(s.netmask, optptr + 2, 4);
break;
case DHCP_OPTION_ROUTER:
memcpy(s.default_router, optptr + 2, 4);
break;
case DHCP_OPTION_DNS_SERVER:
memcpy(s.dnsaddr, optptr + 2, 4);
break;
case DHCP_OPTION_MSG_TYPE:
type = *(optptr + 2);
break;
case DHCP_OPTION_SERVER_ID:
memcpy(s.serverid, optptr + 2, 4);
break;
case DHCP_OPTION_LEASE_TIME:
memcpy(s.lease_time, optptr + 2, 4);
break;
case DHCP_OPTION_END:
return type;
}
optptr += optptr[1] + 2;
}
return type;
}
/*---------------------------------------------------------------------------*/
static u8_t
parse_msg(void)
{
struct dhcp_msg *m = (struct dhcp_msg *)uip_appdata;
if(m->op == DHCP_REPLY &&
memcmp(m->xid, xid, sizeof(xid)) == 0 &&
memcmp(m->chaddr, s.mac_addr, s.mac_len) == 0) {
memcpy(s.ipaddr, m->yiaddr, 4);
return parse_options(&m->options[4], uip_datalen());
}
return 0;
}
/*---------------------------------------------------------------------------*/
static
PT_THREAD(handle_dhcp(void))
{
PT_BEGIN(&s.pt);
/* try_again:*/
s.state = STATE_SENDING;
s.ticks = CLOCK_SECOND;
do {
send_discover();
timer_set(&s.timer, s.ticks);
PT_WAIT_UNTIL(&s.pt, uip_newdata() || timer_expired(&s.timer));
if(uip_newdata() && parse_msg() == DHCPOFFER) {
s.state = STATE_OFFER_RECEIVED;
break;
}
if(s.ticks < CLOCK_SECOND * 60) {
s.ticks *= 2;
}
} while(s.state != STATE_OFFER_RECEIVED);
s.ticks = CLOCK_SECOND;
do {
send_request();
timer_set(&s.timer, s.ticks);
PT_WAIT_UNTIL(&s.pt, uip_newdata() || timer_expired(&s.timer));
if(uip_newdata() && parse_msg() == DHCPACK) {
s.state = STATE_CONFIG_RECEIVED;
break;
}
if(s.ticks <= CLOCK_SECOND * 10) {
s.ticks += CLOCK_SECOND;
} else {
PT_RESTART(&s.pt);
}
} while(s.state != STATE_CONFIG_RECEIVED);
#if 0
printf("Got IP address %d.%d.%d.%d\n",
uip_ipaddr1(s.ipaddr), uip_ipaddr2(s.ipaddr),
uip_ipaddr3(s.ipaddr), uip_ipaddr4(s.ipaddr));
printf("Got netmask %d.%d.%d.%d\n",
uip_ipaddr1(s.netmask), uip_ipaddr2(s.netmask),
uip_ipaddr3(s.netmask), uip_ipaddr4(s.netmask));
printf("Got DNS server %d.%d.%d.%d\n",
uip_ipaddr1(s.dnsaddr), uip_ipaddr2(s.dnsaddr),
uip_ipaddr3(s.dnsaddr), uip_ipaddr4(s.dnsaddr));
printf("Got default router %d.%d.%d.%d\n",
uip_ipaddr1(s.default_router), uip_ipaddr2(s.default_router),
uip_ipaddr3(s.default_router), uip_ipaddr4(s.default_router));
printf("Lease expires in %ld seconds\n",
ntohs(s.lease_time[0])*65536ul + ntohs(s.lease_time[1]));
#endif
dhcpc_configured(&s);
/* timer_stop(&s.timer);*/
/*
* PT_END restarts the thread so we do this instead. Eventually we
* should reacquire expired leases here.
*/
while(1) {
PT_YIELD(&s.pt);
}
PT_END(&s.pt);
}
/*---------------------------------------------------------------------------*/
void
dhcpc_init(const void *mac_addr, int mac_len)
{
uip_ipaddr_t addr;
s.mac_addr = mac_addr;
s.mac_len = mac_len;
s.state = STATE_INITIAL;
uip_ipaddr(addr, 255,255,255,255);
s.conn = uip_udp_new(&addr, HTONS(DHCPC_SERVER_PORT));
if(s.conn != NULL) {
uip_udp_bind(s.conn, HTONS(DHCPC_CLIENT_PORT));
}
PT_INIT(&s.pt);
}
/*---------------------------------------------------------------------------*/
void
dhcpc_appcall(void)
{
handle_dhcp();
}
/*---------------------------------------------------------------------------*/
void
dhcpc_request(void)
{
u16_t ipaddr[2];
if(s.state == STATE_INITIAL) {
uip_ipaddr(ipaddr, 0,0,0,0);
uip_sethostaddr(ipaddr);
/* handle_dhcp(PROCESS_EVENT_NONE, NULL);*/
}
}
/*---------------------------------------------------------------------------*/

View File

@ -0,0 +1,68 @@
/*
* Copyright (c) 2005, Swedish Institute of Computer Science
* 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 above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE 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 INSTITUTE 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.
*
* This file is part of the uIP TCP/IP stack
*
* @(#)$Id: dhcpc.h,v 1.3 2006/06/11 21:46:37 adam Exp $
*/
#ifndef __DHCPC_H__
#define __DHCPC_H__
#include "timer.h"
#include "pt.h"
struct dhcpc_state {
struct pt pt;
char state;
struct uip_udp_conn *conn;
struct timer timer;
u16_t ticks;
const void *mac_addr;
int mac_len;
u8_t serverid[4];
u16_t lease_time[2];
u16_t ipaddr[2];
u16_t netmask[2];
u16_t dnsaddr[2];
u16_t default_router[2];
};
void dhcpc_init(const void *mac_addr, int mac_len);
void dhcpc_request(void);
void dhcpc_appcall(void);
void dhcpc_configured(const struct dhcpc_state *s);
typedef struct dhcpc_state uip_udp_appstate_t;
#define UIP_UDP_APPCALL dhcpc_appcall
#endif /* __DHCPC_H__ */

View File

@ -0,0 +1 @@
APP_SOURCES += hello-world.c

View File

@ -0,0 +1,100 @@
/**
* \addtogroup helloworld
* @{
*/
/**
* \file
* An example of how to write uIP applications
* with protosockets.
* \author
* Adam Dunkels <adam@sics.se>
*/
/*
* This is a short example of how to write uIP applications using
* protosockets.
*/
/*
* We define the application state (struct hello_world_state) in the
* hello-world.h file, so we need to include it here. We also include
* uip.h (since this cannot be included in hello-world.h) and
* <string.h>, since we use the memcpy() function in the code.
*/
#include "hello-world.h"
#include "uip.h"
#include <string.h>
/*
* Declaration of the protosocket function that handles the connection
* (defined at the end of the code).
*/
static int handle_connection(struct hello_world_state *s);
/*---------------------------------------------------------------------------*/
/*
* The initialization function. We must explicitly call this function
* from the system initialization code, some time after uip_init() is
* called.
*/
void
hello_world_init(void)
{
/* We start to listen for connections on TCP port 1000. */
uip_listen(HTONS(1000));
}
/*---------------------------------------------------------------------------*/
/*
* In hello-world.h we have defined the UIP_APPCALL macro to
* hello_world_appcall so that this funcion is uIP's application
* function. This function is called whenever an uIP event occurs
* (e.g. when a new connection is established, new data arrives, sent
* data is acknowledged, data needs to be retransmitted, etc.).
*/
void
hello_world_appcall(void)
{
/*
* The uip_conn structure has a field called "appstate" that holds
* the application state of the connection. We make a pointer to
* this to access it easier.
*/
struct hello_world_state *s = &(uip_conn->appstate);
/*
* If a new connection was just established, we should initialize
* the protosocket in our applications' state structure.
*/
if(uip_connected()) {
PSOCK_INIT(&s->p, s->inputbuffer, sizeof(s->inputbuffer));
}
/*
* Finally, we run the protosocket function that actually handles
* the communication. We pass it a pointer to the application state
* of the current connection.
*/
handle_connection(s);
}
/*---------------------------------------------------------------------------*/
/*
* This is the protosocket function that handles the communication. A
* protosocket function must always return an int, but must never
* explicitly return - all return statements are hidden in the PSOCK
* macros.
*/
static int
handle_connection(struct hello_world_state *s)
{
PSOCK_BEGIN(&s->p);
PSOCK_SEND_STR(&s->p, "Hello. What is your name?\n");
PSOCK_READTO(&s->p, '\n');
strncpy(s->name, s->inputbuffer, sizeof(s->name));
PSOCK_SEND_STR(&s->p, "Hello ");
PSOCK_SEND_STR(&s->p, s->name);
PSOCK_CLOSE(&s->p);
PSOCK_END(&s->p);
}
/*---------------------------------------------------------------------------*/

View File

@ -0,0 +1,52 @@
/**
* \addtogroup apps
* @{
*/
/**
* \defgroup helloworld Hello, world
* @{
*
* A small example showing how to write applications with
* \ref psock "protosockets".
*/
/**
* \file
* Header file for an example of how to write uIP applications
* with protosockets.
* \author
* Adam Dunkels <adam@sics.se>
*/
#ifndef __HELLO_WORLD_H__
#define __HELLO_WORLD_H__
/* Since this file will be included by uip.h, we cannot include uip.h
here. But we might need to include uipopt.h if we need the u8_t and
u16_t datatypes. */
#include "uipopt.h"
#include "psock.h"
/* Next, we define the uip_tcp_appstate_t datatype. This is the state
of our application, and the memory required for this state is
allocated together with each TCP connection. One application state
for each TCP connection. */
typedef struct hello_world_state {
struct psock p;
char inputbuffer[10];
char name[40];
} uip_tcp_appstate_t;
/* Finally we define the application function to be called by uIP. */
void hello_world_appcall(void);
#ifndef UIP_APPCALL
#define UIP_APPCALL hello_world_appcall
#endif /* UIP_APPCALL */
void hello_world_init(void);
#endif /* __HELLO_WORLD_H__ */
/** @} */
/** @} */

View File

@ -0,0 +1 @@
APP_SOURCES += resolv.c

View File

@ -0,0 +1,464 @@
/**
* \addtogroup apps
* @{
*/
/**
* \defgroup resolv DNS resolver
* @{
*
* The uIP DNS resolver functions are used to lookup a hostname and
* map it to a numerical IP address. It maintains a list of resolved
* hostnames that can be queried with the resolv_lookup()
* function. New hostnames can be resolved using the resolv_query()
* function.
*
* When a hostname has been resolved (or found to be non-existant),
* the resolver code calls a callback function called resolv_found()
* that must be implemented by the module that uses the resolver.
*/
/**
* \file
* DNS host name to IP address resolver.
* \author Adam Dunkels <adam@dunkels.com>
*
* This file implements a DNS host name to IP address resolver.
*/
/*
* Copyright (c) 2002-2003, Adam Dunkels.
* 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 above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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.
*
* This file is part of the uIP TCP/IP stack.
*
* $Id: resolv.c,v 1.5 2006/06/11 21:46:37 adam Exp $
*
*/
#include "resolv.h"
#include "uip.h"
#include <string.h>
#ifndef NULL
#define NULL (void *)0
#endif /* NULL */
/** \internal The maximum number of retries when asking for a name. */
#define MAX_RETRIES 8
/** \internal The DNS message header. */
struct dns_hdr {
u16_t id;
u8_t flags1, flags2;
#define DNS_FLAG1_RESPONSE 0x80
#define DNS_FLAG1_OPCODE_STATUS 0x10
#define DNS_FLAG1_OPCODE_INVERSE 0x08
#define DNS_FLAG1_OPCODE_STANDARD 0x00
#define DNS_FLAG1_AUTHORATIVE 0x04
#define DNS_FLAG1_TRUNC 0x02
#define DNS_FLAG1_RD 0x01
#define DNS_FLAG2_RA 0x80
#define DNS_FLAG2_ERR_MASK 0x0f
#define DNS_FLAG2_ERR_NONE 0x00
#define DNS_FLAG2_ERR_NAME 0x03
u16_t numquestions;
u16_t numanswers;
u16_t numauthrr;
u16_t numextrarr;
};
/** \internal The DNS answer message structure. */
struct dns_answer {
/* DNS answer record starts with either a domain name or a pointer
to a name already present somewhere in the packet. */
u16_t type;
u16_t class;
u16_t ttl[2];
u16_t len;
uip_ipaddr_t ipaddr;
};
struct namemap {
#define STATE_UNUSED 0
#define STATE_NEW 1
#define STATE_ASKING 2
#define STATE_DONE 3
#define STATE_ERROR 4
u8_t state;
u8_t tmr;
u8_t retries;
u8_t seqno;
u8_t err;
char name[32];
uip_ipaddr_t ipaddr;
};
#ifndef UIP_CONF_RESOLV_ENTRIES
#define RESOLV_ENTRIES 4
#else /* UIP_CONF_RESOLV_ENTRIES */
#define RESOLV_ENTRIES UIP_CONF_RESOLV_ENTRIES
#endif /* UIP_CONF_RESOLV_ENTRIES */
static struct namemap names[RESOLV_ENTRIES];
static u8_t seqno;
static struct uip_udp_conn *resolv_conn = NULL;
/*---------------------------------------------------------------------------*/
/** \internal
* Walk through a compact encoded DNS name and return the end of it.
*
* \return The end of the name.
*/
/*---------------------------------------------------------------------------*/
static unsigned char *
parse_name(unsigned char *query)
{
unsigned char n;
do {
n = *query++;
while(n > 0) {
/* printf("%c", *query);*/
++query;
--n;
};
/* printf(".");*/
} while(*query != 0);
/* printf("\n");*/
return query + 1;
}
/*---------------------------------------------------------------------------*/
/** \internal
* Runs through the list of names to see if there are any that have
* not yet been queried and, if so, sends out a query.
*/
/*---------------------------------------------------------------------------*/
static void
check_entries(void)
{
register struct dns_hdr *hdr;
char *query, *nptr, *nameptr;
static u8_t i;
static u8_t n;
register struct namemap *namemapptr;
for(i = 0; i < RESOLV_ENTRIES; ++i) {
namemapptr = &names[i];
if(namemapptr->state == STATE_NEW ||
namemapptr->state == STATE_ASKING) {
if(namemapptr->state == STATE_ASKING) {
if(--namemapptr->tmr == 0) {
if(++namemapptr->retries == MAX_RETRIES) {
namemapptr->state = STATE_ERROR;
resolv_found(namemapptr->name, NULL);
continue;
}
namemapptr->tmr = namemapptr->retries;
} else {
/* printf("Timer %d\n", namemapptr->tmr);*/
/* Its timer has not run out, so we move on to next
entry. */
continue;
}
} else {
namemapptr->state = STATE_ASKING;
namemapptr->tmr = 1;
namemapptr->retries = 0;
}
hdr = (struct dns_hdr *)uip_appdata;
memset(hdr, 0, sizeof(struct dns_hdr));
hdr->id = htons(i);
hdr->flags1 = DNS_FLAG1_RD;
hdr->numquestions = HTONS(1);
query = (char *)uip_appdata + 12;
nameptr = namemapptr->name;
--nameptr;
/* Convert hostname into suitable query format. */
do {
++nameptr;
nptr = query;
++query;
for(n = 0; *nameptr != '.' && *nameptr != 0; ++nameptr) {
*query = *nameptr;
++query;
++n;
}
*nptr = n;
} while(*nameptr != 0);
{
static unsigned char endquery[] =
{0,0,1,0,1};
memcpy(query, endquery, 5);
}
uip_udp_send((unsigned char)(query + 5 - (char *)uip_appdata));
break;
}
}
}
/*---------------------------------------------------------------------------*/
/** \internal
* Called when new UDP data arrives.
*/
/*---------------------------------------------------------------------------*/
static void
newdata(void)
{
char *nameptr;
struct dns_answer *ans;
struct dns_hdr *hdr;
static u8_t nquestions, nanswers;
static u8_t i;
register struct namemap *namemapptr;
hdr = (struct dns_hdr *)uip_appdata;
/* printf("ID %d\n", htons(hdr->id));
printf("Query %d\n", hdr->flags1 & DNS_FLAG1_RESPONSE);
printf("Error %d\n", hdr->flags2 & DNS_FLAG2_ERR_MASK);
printf("Num questions %d, answers %d, authrr %d, extrarr %d\n",
htons(hdr->numquestions),
htons(hdr->numanswers),
htons(hdr->numauthrr),
htons(hdr->numextrarr));
*/
/* The ID in the DNS header should be our entry into the name
table. */
i = htons(hdr->id);
namemapptr = &names[i];
if(i < RESOLV_ENTRIES &&
namemapptr->state == STATE_ASKING) {
/* This entry is now finished. */
namemapptr->state = STATE_DONE;
namemapptr->err = hdr->flags2 & DNS_FLAG2_ERR_MASK;
/* Check for error. If so, call callback to inform. */
if(namemapptr->err != 0) {
namemapptr->state = STATE_ERROR;
resolv_found(namemapptr->name, NULL);
return;
}
/* We only care about the question(s) and the answers. The authrr
and the extrarr are simply discarded. */
nquestions = htons(hdr->numquestions);
nanswers = htons(hdr->numanswers);
/* Skip the name in the question. XXX: This should really be
checked agains the name in the question, to be sure that they
match. */
nameptr = parse_name((char *)uip_appdata + 12) + 4;
while(nanswers > 0) {
/* The first byte in the answer resource record determines if it
is a compressed record or a normal one. */
if(*nameptr & 0xc0) {
/* Compressed name. */
nameptr +=2;
/* printf("Compressed anwser\n");*/
} else {
/* Not compressed name. */
nameptr = parse_name((char *)nameptr);
}
ans = (struct dns_answer *)nameptr;
/* printf("Answer: type %x, class %x, ttl %x, length %x\n",
htons(ans->type), htons(ans->class), (htons(ans->ttl[0])
<< 16) | htons(ans->ttl[1]), htons(ans->len));*/
/* Check for IP address type and Internet class. Others are
discarded. */
if(ans->type == HTONS(1) &&
ans->class == HTONS(1) &&
ans->len == HTONS(4)) {
/* printf("IP address %d.%d.%d.%d\n",
htons(ans->ipaddr[0]) >> 8,
htons(ans->ipaddr[0]) & 0xff,
htons(ans->ipaddr[1]) >> 8,
htons(ans->ipaddr[1]) & 0xff);*/
/* XXX: we should really check that this IP address is the one
we want. */
namemapptr->ipaddr[0] = ans->ipaddr[0];
namemapptr->ipaddr[1] = ans->ipaddr[1];
resolv_found(namemapptr->name, namemapptr->ipaddr);
return;
} else {
nameptr = nameptr + 10 + htons(ans->len);
}
--nanswers;
}
}
}
/*---------------------------------------------------------------------------*/
/** \internal
* The main UDP function.
*/
/*---------------------------------------------------------------------------*/
void
resolv_appcall(void)
{
if(uip_udp_conn->rport == HTONS(53)) {
if(uip_poll()) {
check_entries();
}
if(uip_newdata()) {
newdata();
}
}
}
/*---------------------------------------------------------------------------*/
/**
* Queues a name so that a question for the name will be sent out.
*
* \param name The hostname that is to be queried.
*/
/*---------------------------------------------------------------------------*/
void
resolv_query(char *name)
{
static u8_t i;
static u8_t lseq, lseqi;
register struct namemap *nameptr;
lseq = lseqi = 0;
for(i = 0; i < RESOLV_ENTRIES; ++i) {
nameptr = &names[i];
if(nameptr->state == STATE_UNUSED) {
break;
}
if(seqno - nameptr->seqno > lseq) {
lseq = seqno - nameptr->seqno;
lseqi = i;
}
}
if(i == RESOLV_ENTRIES) {
i = lseqi;
nameptr = &names[i];
}
/* printf("Using entry %d\n", i);*/
strcpy(nameptr->name, name);
nameptr->state = STATE_NEW;
nameptr->seqno = seqno;
++seqno;
}
/*---------------------------------------------------------------------------*/
/**
* Look up a hostname in the array of known hostnames.
*
* \note This function only looks in the internal array of known
* hostnames, it does not send out a query for the hostname if none
* was found. The function resolv_query() can be used to send a query
* for a hostname.
*
* \return A pointer to a 4-byte representation of the hostname's IP
* address, or NULL if the hostname was not found in the array of
* hostnames.
*/
/*---------------------------------------------------------------------------*/
u16_t *
resolv_lookup(char *name)
{
static u8_t i;
struct namemap *nameptr;
/* Walk through the list to see if the name is in there. If it is
not, we return NULL. */
for(i = 0; i < RESOLV_ENTRIES; ++i) {
nameptr = &names[i];
if(nameptr->state == STATE_DONE &&
strcmp(name, nameptr->name) == 0) {
return nameptr->ipaddr;
}
}
return NULL;
}
/*---------------------------------------------------------------------------*/
/**
* Obtain the currently configured DNS server.
*
* \return A pointer to a 4-byte representation of the IP address of
* the currently configured DNS server or NULL if no DNS server has
* been configured.
*/
/*---------------------------------------------------------------------------*/
u16_t *
resolv_getserver(void)
{
if(resolv_conn == NULL) {
return NULL;
}
return resolv_conn->ripaddr;
}
/*---------------------------------------------------------------------------*/
/**
* Configure which DNS server to use for queries.
*
* \param dnsserver A pointer to a 4-byte representation of the IP
* address of the DNS server to be configured.
*/
/*---------------------------------------------------------------------------*/
void
resolv_conf(u16_t *dnsserver)
{
if(resolv_conn != NULL) {
uip_udp_remove(resolv_conn);
}
resolv_conn = uip_udp_new(dnsserver, HTONS(53));
}
/*---------------------------------------------------------------------------*/
/**
* Initalize the resolver.
*/
/*---------------------------------------------------------------------------*/
void
resolv_init(void)
{
static u8_t i;
for(i = 0; i < RESOLV_ENTRIES; ++i) {
names[i].state = STATE_DONE;
}
}
/*---------------------------------------------------------------------------*/
/** @} */
/** @} */

View File

@ -0,0 +1,75 @@
/**
* \addtogroup resolv
* @{
*/
/**
* \file
* DNS resolver code header file.
* \author Adam Dunkels <adam@dunkels.com>
*/
/*
* Copyright (c) 2002-2003, Adam Dunkels.
* 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 above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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.
*
* This file is part of the uIP TCP/IP stack.
*
* $Id: resolv.h,v 1.4 2006/06/11 21:46:37 adam Exp $
*
*/
#ifndef __RESOLV_H__
#define __RESOLV_H__
typedef int uip_udp_appstate_t;
void resolv_appcall(void);
#define UIP_UDP_APPCALL resolv_appcall
#include "uipopt.h"
/**
* Callback function which is called when a hostname is found.
*
* This function must be implemented by the module that uses the DNS
* resolver. It is called when a hostname is found, or when a hostname
* was not found.
*
* \param name A pointer to the name that was looked up. \param
* ipaddr A pointer to a 4-byte array containing the IP address of the
* hostname, or NULL if the hostname could not be found.
*/
void resolv_found(char *name, u16_t *ipaddr);
/* Functions. */
void resolv_conf(u16_t *dnsserver);
u16_t *resolv_getserver(void);
void resolv_init(void);
u16_t *resolv_lookup(char *name);
void resolv_query(char *name);
#endif /* __RESOLV_H__ */
/** @} */

View File

@ -0,0 +1 @@
APP_SOURCES += smtp.c smtp-strings.c memb.c

View File

@ -0,0 +1,40 @@
#!/usr/bin/perl
sub stringify {
my $name = shift(@_);
open(OUTPUTC, "> $name.c");
open(OUTPUTH, "> $name.h");
open(FILE, "$name");
while(<FILE>) {
if(/(.+) "(.+)"/) {
$var = $1;
$data = $2;
$datan = $data;
$datan =~ s/\\r/\r/g;
$datan =~ s/\\n/\n/g;
$datan =~ s/\\01/\01/g;
$datan =~ s/\\0/\0/g;
printf(OUTPUTC "const char $var\[%d] = \n", length($datan) + 1);
printf(OUTPUTC "/* \"$data\" */\n");
printf(OUTPUTC "{");
for($j = 0; $j < length($datan); $j++) {
printf(OUTPUTC "%#02x, ", unpack("C", substr($datan, $j, 1)));
}
printf(OUTPUTC "};\n");
printf(OUTPUTH "extern const char $var\[%d];\n", length($datan) + 1);
}
}
close(OUTPUTC);
close(OUTPUTH);
}
stringify("smtp-strings");
exit 0;

Some files were not shown because too many files have changed in this diff Show More