clone from danieldin95

This commit is contained in:
sicheng
2022-07-29 23:38:54 +08:00
commit ac4f79bbf4
1931 changed files with 568263 additions and 0 deletions

26
.gitignore vendored Executable file
View File

@@ -0,0 +1,26 @@
# Binaries for programs and plugins
*.exe~
*.dll
*.so
*.dylib
*.exe
*.x86_64
*.rpm
*.zip
# Test binary, build with `go test -c`
*.test
*.idea
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
/build/
/py/build/
/py/dist/
/core/build/
/core/cmake-build-debug/
confd-idl.h
confd-idl.c
confd-idl.ovsidl

12
.gitmodules vendored Normal file
View File

@@ -0,0 +1,12 @@
[submodule "3rd/openvpn"]
path = 3rd/openvpn
url = https://github.com/OpenVPN/openvpn
branch = release/2.4
[submodule "dist/resource/cert"]
path = dist/resource/cert
url = https://github.com/danieldin95/freecert.git
branch = master
[submodule "3rd/ovs"]
path = 3rd/ovs
url = https://github.com/openvswitch/ovs.git
branch = branch-2.12

9
3rd/README.md Executable file
View File

@@ -0,0 +1,9 @@
## Compile
If you want to build OpenVPN and OpenvSwitch, the following SHOULD be installing.
```
[CentOS]
yum install -y lzo-devel pam-devel
[Ubuntu]
apt-get install -y liblzo2-dev libpam-dev
```

57
3rd/auto.sh Executable file
View File

@@ -0,0 +1,57 @@
#!/bin/bash
set -ex
action=$1
version=$(cat VERSION)
cd $(dirname $0)
build_openvswitch() {
obj_dir=$(pwd)/../build/obj
cd ovs && {
[ -e './configure' ] || ./boot.sh
[ -e './Makefile' ] || ./configure --prefix=/usr --sysconfdir=/etc --localstatedir=/var --disable-libcapng
make -j4 && make install DESTDIR=$obj_dir
cd -
}
}
build_openvpn() {
obj_dir=$(pwd)/../build/obj
cd openvpn && {
[ -e './configure' ] || autoreconf -i -v -f
[ -e './Makefile' ] || ./configure --prefix=/usr --sysconfdir=/etc --localstatedir=/var
make -j4 && make install DESTDIR=$obj_dir
cd -
}
}
clean_openvswitch() {
cd ovs && {
if [ -e Makefile ]; then
make clean
rm ./Makefile
fi
cd -
}
}
clean_openvpn() {
cd openvpn && {
if [ -e Makefile ]; then
make clean
rm ./Makefile
fi
cd -
}
}
if [ "$action"x == "build"x ] || [ "$action"x == ""x ]; then
build_openvswitch
build_openvpn
elif [ "$action"x == "clean"x ]; then
clean_openvswitch
clean_openvpn
fi

1
3rd/openvpn Submodule

Submodule 3rd/openvpn added at 058407a89c

1
3rd/ovs Submodule

Submodule 3rd/ovs added at 7a7e4db590

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

193
Makefile Executable file
View File

@@ -0,0 +1,193 @@
SHELL := /bin/bash
.ONESHELL:
.PHONY: linux linux-rpm darwin darwin-zip windows windows-zip test vendor
## version
LSB = $(shell lsb_release -i -s)$(shell lsb_release -r -s)
VER = $(shell cat VERSION)
ARCH = $(shell uname -m)
## declare directory
SD = $(shell pwd)
BD = "$(SD)/build"
LINUX_DIR ?= "openlan-linux-$(VER).$(ARCH)"
WIN_DIR ?= "openlan-windows-$(VER).$(ARCH)"
MAC_DIR ?= "openlan-darwin-$(VER).$(ARCH)"
## declare flags
MOD = github.com/luscis/openlan/pkg/libol
LDFLAGS += -X $(MOD).Date=$(shell date +%FT%T%z)
LDFLAGS += -X $(MOD).Version=$(VER)
build: test pkg
pkg: clean linux-rpm linux-bin windows-gz darwin-gz ## build all plaftorm packages
gz: linux-gz windows-gz darwin-gz
help: ## show make targets
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {sub("\\\\n",sprintf("\n%22c"," "), $$2);\
printf " \033[36m%-20s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)
## all platform
bin: linux windows darwin ## build all platform binary
#
## docker run --network host --privileged \
## -v /var/run:/var/run -v /etc/openlan/switch:/etc/openlan/switch \
## openlan-switch:5.8.13
docker: pkg
docker build -t openlan-switch:$(VER) --build-arg VERSION=$(VER) -f ./dist/openlan-switch.docker .
## upgrade
upgrade:
ansible-playbook ./misc/playbook/upgrade.yaml -e "version=$(VER)"
clean: ## clean cache
rm -rvf ./build
rm -rvf ./core/build
rm -rvf ./core/cmake-build-debug
./core/auto.sh clean
./3rd/auto.sh clean
## prepare environment
update:
git submodule init
git submodule update
vendor: update
go clean -modcache
go mod tidy
go mod vendor -v
env:
@mkdir -p $(BD)
@go version
@gofmt -w -s ./pkg ./cmd ./misc
## linux platform
linux: linux-proxy linux-point linux-switch
core: env
./3rd/auto.sh build
./core/auto.sh build
cd $(BD) && cmake $(SD)/core && make
rpm: env ## build rpm packages
mkdir -p ~/rpmbuild/SPECS
mkdir -p ~/rpmbuild/SOURCES
sed -e "s/Version:.*/Version:\ $(VER)/" $(SD)/dist/openlan.spec.in > ~/rpmbuild/SPECS/openlan.spec
@dist/spec.sh
rpmbuild -ba ~/rpmbuild/SPECS/openlan.spec
## compile command line
cmd: env
go build -mod=vendor -ldflags "$(LDFLAGS)" -o $(BD)/openlan ./cmd/main.go
linux: linux-point linux-switch linux-proxy ## build all linux binary
linux-point: env
go build -mod=vendor -ldflags "$(LDFLAGS)" -o $(BD)/openlan-point ./cmd/point_linux
linux-switch: env cmd core
go build -mod=vendor -ldflags "$(LDFLAGS)" -o $(BD)/openlan-switch ./cmd/switch
linux-proxy: env
go build -mod=vendor -ldflags "$(LDFLAGS)" -o $(BD)/openlan-proxy ./cmd/proxy
linux-gz: install ## build linux packages
@rm -rf $(LINUX_DIR).tar.gz
tar -cf $(LINUX_DIR).tar $(LINUX_DIR) && mv $(LINUX_DIR).tar $(BD)
@rm -rf $(LINUX_DIR)
gzip -f $(BD)/$(LINUX_DIR).tar
linux-bin: linux-gz ## build linux install binary
cat $(SD)/dist/script/install.sh > $(BD)/$(LINUX_DIR).bin && \
echo "__ARCHIVE_BELOW__:" >> $(BD)/$(LINUX_DIR).bin && \
cat $(BD)/$(LINUX_DIR).tar.gz >> $(BD)/$(LINUX_DIR).bin && \
chmod +x $(BD)/$(LINUX_DIR).bin
install: env linux-point linux-switch linux-proxy ## install packages
@mkdir -p $(LINUX_DIR)/etc/sysctl.d
@cp -rvf $(SD)/dist/resource/90-openlan.conf $(LINUX_DIR)/etc/sysctl.d
@mkdir -p $(LINUX_DIR)/etc/openlan
@cp -rvf $(SD)/dist/resource/point.json.example $(LINUX_DIR)/etc/openlan
@cp -rvf $(SD)/dist/resource/proxy.json.example $(LINUX_DIR)/etc/openlan
@mkdir -p $(LINUX_DIR)/etc/openlan/switch
@cp -rvf $(SD)/dist/resource/confd.schema.json $(LINUX_DIR)/etc/openlan/switch
@cp -rvf $(SD)/dist/resource/switch.json.example $(LINUX_DIR)/etc/openlan/switch
@mkdir -p $(LINUX_DIR)/etc/openlan/switch/network
@cp -rvf $(SD)/dist/resource/acl-1.json.example $(LINUX_DIR)/etc/openlan/switch/network
@cp -rvf $(SD)/dist/resource/default.json.example $(LINUX_DIR)/etc/openlan/switch/network
@cp -rvf $(SD)/dist/resource/network.json.example $(LINUX_DIR)/etc/openlan/switch/network
@cp -rvf $(SD)/dist/resource/ipsec.json.example $(LINUX_DIR)/etc/openlan/switch/network
@cp -rvf $(SD)/dist/resource/v1024.json.example $(LINUX_DIR)/etc/openlan/switch/network
@cp -rvf $(SD)/dist/resource/fabric.json.example $(LINUX_DIR)/etc/openlan/switch/network
@mkdir -p $(LINUX_DIR)/usr/bin
@cp -rvf $(BD)/openudp $(LINUX_DIR)/usr/bin
@cp -rvf $(BD)/openlan $(LINUX_DIR)/usr/bin
@cp -rvf $(BD)/openlan-proxy $(LINUX_DIR)/usr/bin
@cp -rvf $(BD)/openlan-point $(LINUX_DIR)/usr/bin
@cp -rvf $(BD)/openlan-switch $(LINUX_DIR)/usr/bin
@mkdir -p $(LINUX_DIR)/var/openlan
@cp -rvf $(SD)/dist/resource/cert/openlan/cert $(LINUX_DIR)/var/openlan
@cp -rvf $(SD)/dist/script $(LINUX_DIR)/var/openlan
@cp -rvf $(SD)/pkg/public $(LINUX_DIR)/var/openlan
@cp -rvf $(SD)/dist/resource/cert/openlan/ca/ca.crt $(LINUX_DIR)/var/openlan/cert
@mkdir -p $(LINUX_DIR)/var/openlan/point
@mkdir -p $(LINUX_DIR)/var/openlan/openvpn
@mkdir -p $(LINUX_DIR)/var/openlan/dhcp
@mkdir -p $(LINUX_DIR)/etc/sysconfig/openlan
@cp -rvf $(SD)/dist/resource/point.cfg $(LINUX_DIR)/etc/sysconfig/openlan
@cp -rvf $(SD)/dist/resource/proxy.cfg $(LINUX_DIR)/etc/sysconfig/openlan
@cp -rvf $(SD)/dist/resource/switch.cfg $(LINUX_DIR)/etc/sysconfig/openlan
@mkdir -p $(LINUX_DIR)//usr/lib/systemd/system
@cp -rvf $(SD)/dist/resource/openlan-point@.service $(LINUX_DIR)/usr/lib/systemd/system
@cp -rvf $(SD)/dist/resource/openlan-proxy.service $(LINUX_DIR)/usr/lib/systemd/system
@cp -rvf $(SD)/dist/resource/openlan-confd.service $(LINUX_DIR)/usr/lib/systemd/system
@cp -rvf $(SD)/dist/resource/openlan-switch.service $(LINUX_DIR)/usr/lib/systemd/system
## cross build for windows
windows: windows-point ## build windows binary
windows-point: env
GOOS=windows GOARCH=amd64 go build -mod=vendor -ldflags "$(LDFLAGS)" -o $(BD)/openlan-point.exe ./cmd/point_windows
windows-gz: env windows ## build windows packages
@rm -rf $(WIN_DIR) && mkdir -p $(WIN_DIR)
@rm -rf $(WIN_DIR).tar.gz
@cp -rvf $(SD)/dist/resource/point.json.example $(WIN_DIR)/point.json
@cp -rvf $(BD)/openlan-point.exe $(WIN_DIR)
tar -cf $(WIN_DIR).tar $(WIN_DIR) && mv $(WIN_DIR).tar $(BD)
@rm -rf $(WIN_DIR)
gzip -f $(BD)/$(WIN_DIR).tar
windows-syso: ## build windows syso
rsrc -manifest ./cmd/point_windows/main.manifest -ico ./cmd/point_windows/main.ico -o ./cmd/point_windows/main.syso
## cross build for osx
osx: darwin
darwin: env ## build darwin binary
GOOS=darwin GOARCH=amd64 go build -mod=vendor -ldflags "$(LDFLAGS)" -o $(BD)/openlan-point.darwin ./cmd/point_darwin
darwin-gz: env darwin ## build darwin packages
@rm -rf $(MAC_DIR) && mkdir -p $(MAC_DIR)
@rm -rf $(MAC_DIR).tar.gz
@cp -rvf $(SD)/dist/resource/point.json.example $(MAC_DIR)/point.json
@cp -rvf $(BD)/openlan-point.darwin $(MAC_DIR)
tar -cf $(MAC_DIR).tar $(MAC_DIR) && mv $(MAC_DIR).tar $(BD)
@rm -rf $(MAC_DIR)
gzip -f $(BD)/$(MAC_DIR).tar
## unit test
test: ## execute unit test
go test -v -mod=vendor -bench=. github.com/luscis/openlan/pkg/access
go test -v -mod=vendor -bench=. github.com/luscis/openlan/pkg/libol
go test -v -mod=vendor -bench=. github.com/luscis/openlan/pkg/models

48
README.en.md Executable file
View File

@@ -0,0 +1,48 @@
# Overview
[![Build Status](https://travis-ci.org/luscis/openlan.svg?branch=master)](https://travis-ci.org/luscis/openlan)
[![Go Report Card](https://goreportcard.com/badge/github.com/luscis/openlan)](https://goreportcard.com/report/luscis/openlan)
[![Apache 2.0 License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
The OpenLAN project help you to build a local area network via the Internet.
## Terminology
* OLSW: OpenLAN Switch
* OLAP: OpenLAN Access Point
* NAT: Network Address translation
## Branch Access
OLSW(Central) - 10.1.2.10/24
^
|
Wifi(DNAT)
|
|
----------------------Internet-------------------------
^ ^ ^
| | |
Branch 1 Branch 2 Branch 3
| | |
OLAP OLAP OLAP
10.1.2.11/24 10.1.2.12/24 10.1.2.13/24
## Multiple Area
192.168.1.20/24 192.168.1.22/24
| |
OLAP ---- Wifi ---> OLSW(NanJing) <---- Wifi --- OLAP
|
|
Internet
|
|
OLSW(ShangHai) - 192.168.1.10/24
|
------------------------------------------------------
^ ^ ^
| | |
Office Wifi Home Wifi Hotel Wifi
| | |
OLAP OLAP OLAP
192.168.1.11/24 192.168.1.12/24 192.168.1.13/24

128
README.md Executable file
View File

@@ -0,0 +1,128 @@
简体中文 | [English](./README.en.md)
# 概述
[![Build Status](https://app.travis-ci.com/luscis/openlan.svg?token=3tnnPDv6XvR5zsJsD4kC&branch=master)](https://app.travis-ci.com/github/luscis/openlan)
[![Go Report Card](https://goreportcard.com/badge/github.com/luscis/openlan)](https://goreportcard.com/report/luscis/openlan-go)
[![GPL 3.0 License](https://img.shields.io/badge/License-GPL%203.0-blue.svg)](LICENSE)
OpenLAN提供一种局域网数据报文在广域网的传输实现并能够建立多个用户空间的虚拟以太网络。
## 缩略语
* OLSW: OpenLAN Switch开放局域网交换机
* OLAP: OpenLAN Access Point开放局域网接入点
* NAT: Network Address Translation, 网络地址转换
* VxLAN: Virtual eXtensible Local Area Network虚拟扩展局域网
* STT: Stateless Transport Tunneling无状态传输隧道
## 功能清单
* 支持多个网络空间划分,为不同的业务提供逻辑网络隔离;
* 支持OLAP或者OpenVPN接入提供网桥把局域网共享出去
* 支持IPSec隧道网络以及基于VxLAN/STT的租户网络划分
* 支持基于用户名密码的接入认证,使用预共享密约对数据报文进行加密;
* 支持TCP/TLSUDP/KCPWS/WSS等多种传输协议实现TCP模式具有较高的性能
* 支持HTTP/HTTPS以及SOCKS5等HTTP的正向代理技术灵活配置代理进行网络穿透
* 支持基于TCP的端口转发为防火墙下的主机提供TCP端口代理。
## 分支中心接入
OLSW(企业中心) - 10.16.1.10/24
^
|
Wifi(DNAT)
|
|
----------------------Internet-------------------------
^ ^ ^
| | |
分支1 分支2 分支3
| | |
OLAP OLAP OLAP
10.16.1.11/24 10.16.1.12/24 10.16.1.13/24
## 多区域互联
192.168.1.20/24 192.168.1.21/24
| |
OLAP -- 酒店 Wifi --> OLSW(南京) <--- 其他 Wifi --- OLAP
|
|
互联网
|
|
OLSW(上海) - 192.168.1.10/24
|
|
------------------------------------------------------
^ ^ ^
| | |
办公 Wifi 家庭 Wifi 酒店 Wifi
| | |
OLAP OLAP OLAP
192.168.1.11/24 192.168.1.12/24 192.168.1.13/24
## 数据中心全互联网络
* Underlay for VxLAN over Internet by IPSec.
47.example.com
|
|
|
+-------+
| vps-47| -- 100.65.0.117
+-------+
/ \
/ \
SPI-117118 / \ SPI-117119
/ \
/ \
+-------+ +-------+
| vps-92| -------------- | vps-12|
+-------+ +-------+
/ | | \
/ | SPI-118119 | \
100.65.0.118 | | 100.65.0.119
| |
92.example.com 12.example.com
* DCI Subnet: 192.168.x.x over IPSec Network: 100.65.0.x.
100.65.0.117
|
eth1.200 --- | --- eth1.100
\ | /
+--------+
| vps-47 |
+--------+
/ \
/ \
/ \
/ \
enp2s4.100 --- / \ --- eth4.30
\ / \ /
+--------+ +--------+
| vps-92 | --------------- | vps-12 |
+--------+ +--------+
/ | | \
enp2s4.101 --- | | --- eth4.200
| |
100.65.0.118 100.65.0.119
VNI-1023 192.168.30.0/24 [vps-47_eth1.100, vps-92_enp2s4.100, vps-12_eth4.30]
VNI-1024 192.168.40.0/24 [vps-47_eth1.200, vps-92_enp2s4.101, vps-12_eth4.200]
## 文档
- [软件安装](docs/install.md)
- [分支接入](docs/central.md)
- [多区域互联](docs/multiarea.md)
- [全互连网络](docs/fabric.md)
- [IPSec网络](docs/ipsec.md)

1
VERSION Executable file
View File

@@ -0,0 +1 @@
5.10.4

123
cmd/api/app.go Executable file
View File

@@ -0,0 +1,123 @@
package api
import (
"github.com/luscis/openlan/pkg/libol"
"github.com/urfave/cli/v2"
)
const (
ConfSockFile = "unix:/var/openlan/confd.sock"
ConfDatabase = "OpenLAN_Switch"
AdminTokenFile = "/etc/openlan/switch/token"
)
var (
Version = "v5"
Url = "https://localhost:10000"
Token = ""
Server = ConfSockFile
Database = ConfDatabase
Verbose = false
)
type App struct {
cli *cli.App
Before func(c *cli.Context) error
After func(c *cli.Context) error
}
func (a *App) Flags() []cli.Flag {
var flags []cli.Flag
switch Version {
case "v6":
flags = append(flags,
&cli.StringFlag{
Name: "format",
Aliases: []string{"f"},
Usage: "output format: json|yaml",
Value: "yaml",
})
flags = append(flags,
&cli.StringFlag{
Name: "conf",
Aliases: []string{"c"},
Usage: "confd server connection",
Value: Server,
})
flags = append(flags,
&cli.StringFlag{
Name: "database",
Aliases: []string{"d"},
Usage: "confd database",
Value: Database,
})
default:
flags = append(flags,
&cli.StringFlag{
Name: "format",
Aliases: []string{"f"},
Usage: "output format: json|yaml",
Value: "table",
})
flags = append(flags,
&cli.StringFlag{
Name: "token",
Aliases: []string{"t"},
Usage: "admin token",
Value: Token,
})
flags = append(flags,
&cli.StringFlag{
Name: "url",
Aliases: []string{"l"},
Usage: "server url",
Value: Url,
})
}
flags = append(flags,
&cli.BoolFlag{
Name: "verbose",
Aliases: []string{"v"},
Usage: "enable verbose",
Value: false,
})
return flags
}
func (a *App) New() *cli.App {
app := &cli.App{
Usage: "OpenLAN switch utility",
Flags: a.Flags(),
Commands: []*cli.Command{},
Before: func(c *cli.Context) error {
if c.Bool("verbose") {
Verbose = true
libol.SetLogger("", libol.DEBUG)
} else {
Verbose = false
libol.SetLogger("", libol.INFO)
}
if a.Before == nil {
return nil
}
return a.Before(c)
},
After: func(c *cli.Context) error {
if a.After == nil {
return nil
}
return a.After(c)
},
}
a.cli = app
return a.cli
}
func (a *App) Command(cmd *cli.Command) {
a.cli.Commands = append(a.cli.Commands, cmd)
}
func (a *App) Run(args []string) error {
return a.cli.Run(args)
}

84
cmd/api/out.go Executable file
View File

@@ -0,0 +1,84 @@
package api
import (
"fmt"
"github.com/luscis/openlan/pkg/libol"
"gopkg.in/yaml.v2"
"os"
"strconv"
"text/template"
)
func OutJson(data interface{}) error {
if out, err := libol.Marshal(data, true); err == nil {
fmt.Println(string(out))
} else {
return err
}
return nil
}
func OutYaml(data interface{}) error {
if out, err := yaml.Marshal(data); err == nil {
fmt.Println(string(out))
} else {
return err
}
return nil
}
func OutTable(data interface{}, tmpl string) error {
funcMap := template.FuncMap{
"ps": func(space int, args ...interface{}) string {
format := "%" + strconv.Itoa(space) + "s"
if space < 0 {
format = "%-" + strconv.Itoa(space) + "s"
}
return fmt.Sprintf(format, args...)
},
"pi": func(space int, args ...interface{}) string {
format := "%" + strconv.Itoa(space) + "d"
if space < 0 {
format = "%-" + strconv.Itoa(space) + "d"
}
return fmt.Sprintf(format, args...)
},
"pu": func(space int, args ...interface{}) string {
format := "%" + strconv.Itoa(space) + "u"
if space < 0 {
format = "%-" + strconv.Itoa(space) + "u"
}
return fmt.Sprintf(format, args...)
},
"pt": func(value int64) string {
return libol.PrettyTime(value)
},
"p2": func(space int, format, key1, key2 string) string {
value := fmt.Sprintf(format, key1, key2)
format = "%" + strconv.Itoa(space) + "s"
if space < 0 {
format = "%-" + strconv.Itoa(space) + "s"
}
return fmt.Sprintf(format, value)
},
}
if tmpl, err := template.New("main").Funcs(funcMap).Parse(tmpl); err != nil {
return err
} else {
if err := tmpl.Execute(os.Stdout, data); err != nil {
return err
}
}
return nil
}
func Out(data interface{}, format string, tmpl string) error {
switch format {
case "json":
return OutJson(data)
case "yaml":
return OutYaml(data)
default:
return OutTable(data, tmpl)
}
}

11
cmd/api/utils.go Executable file
View File

@@ -0,0 +1,11 @@
package api
import "os"
func GetEnv(key, value string) string {
val := os.Getenv(key)
if val == "" {
return value
}
return val
}

137
cmd/api/v5/acl.go Executable file
View File

@@ -0,0 +1,137 @@
package v5
import (
"github.com/luscis/openlan/cmd/api"
"github.com/urfave/cli/v2"
)
type ACL struct {
Cmd
}
func (u ACL) Url(prefix, name string) string {
if name == "" {
return prefix + "/api/acl"
} else {
return prefix + "/api/acl/" + name
}
}
func (u ACL) Add(c *cli.Context) error {
return nil
}
func (u ACL) Remove(c *cli.Context) error {
return nil
}
func (u ACL) List(c *cli.Context) error {
return nil
}
func (u ACL) Apply(c *cli.Context) error {
return nil
}
func (u ACL) Commands(app *api.App) {
rule := ACLRule{}
app.Command(&cli.Command{
Name: "acl",
Usage: "Access control list",
Flags: []cli.Flag{
&cli.StringFlag{Name: "name", Aliases: []string{"n"}},
},
Subcommands: []*cli.Command{
{
Name: "add",
Usage: "Add a new acl",
Action: u.Add,
},
{
Name: "remove",
Usage: "Remove an existing acl",
Aliases: []string{"ls"},
Action: u.Remove,
},
{
Name: "list",
Usage: "Display all acl",
Aliases: []string{"ls"},
Action: u.List,
},
rule.Commands(),
{
Name: "apply",
Usage: "Apply a new acl",
Flags: []cli.Flag{
&cli.StringFlag{Name: "network", Aliases: []string{"net"}},
},
Action: u.Apply,
},
},
})
}
type ACLRule struct {
Cmd
}
func (u ACLRule) Url(prefix, acl, name string) string {
if name == "" {
return prefix + "/api/acl/" + acl
} else {
return prefix + "/api/acl/" + acl + "/" + name
}
}
func (u ACLRule) Add(c *cli.Context) error {
return nil
}
func (u ACLRule) Remove(c *cli.Context) error {
return nil
}
func (u ACLRule) List(c *cli.Context) error {
return nil
}
func (u ACLRule) Commands() *cli.Command {
return &cli.Command{
Name: "rule",
Usage: "Access control list rule",
Subcommands: []*cli.Command{
{
Name: "add",
Usage: "Add a new acl rule",
Flags: []cli.Flag{
&cli.StringFlag{Name: "src", Aliases: []string{"s"}},
&cli.StringFlag{Name: "dst", Aliases: []string{"d"}},
&cli.StringFlag{Name: "proto", Aliases: []string{"p"}},
&cli.StringFlag{Name: "sport", Aliases: []string{"dp"}},
&cli.StringFlag{Name: "dport", Aliases: []string{"sp"}},
},
Action: u.Add,
},
{
Name: "remove",
Usage: "remove a new acl rule",
Aliases: []string{"rm"},
Flags: []cli.Flag{
&cli.StringFlag{Name: "src", Aliases: []string{"s"}},
&cli.StringFlag{Name: "dst", Aliases: []string{"d"}},
&cli.StringFlag{Name: "proto", Aliases: []string{"p"}},
&cli.StringFlag{Name: "sport", Aliases: []string{"dp"}},
&cli.StringFlag{Name: "dport", Aliases: []string{"sp"}},
},
Action: u.Remove,
},
{
Name: "list",
Usage: "Display all acl rules",
Aliases: []string{"ls"},
Action: u.List,
},
},
}
}

129
cmd/api/v5/client.go Executable file
View File

@@ -0,0 +1,129 @@
package v5
import (
"bytes"
"encoding/json"
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/libol"
"io/ioutil"
"net/http"
)
type Client struct {
Auth libol.Auth
Host string
}
func (cl Client) NewRequest(url string) *libol.HttpClient {
client := &libol.HttpClient{
Auth: libol.Auth{
Type: "basic",
Username: cl.Auth.Username,
Password: cl.Auth.Password,
},
Url: url,
}
return client
}
func (cl Client) GetBody(url string) ([]byte, error) {
client := cl.NewRequest(url)
r, err := client.Do()
if err != nil {
return nil, err
}
if r.StatusCode != http.StatusOK {
return nil, libol.NewErr(r.Status)
}
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
return body, nil
}
func (cl Client) JSON(client *libol.HttpClient, i, o interface{}) error {
out := cl.Log()
data, err := json.Marshal(i)
if err != nil {
return err
}
out.Debug("Client.JSON -> %s %s", client.Method, client.Url)
out.Debug("Client.JSON -> %s", string(data))
client.Payload = bytes.NewReader(data)
if r, err := client.Do(); err != nil {
return err
} else {
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
out.Debug("client.JSON <- %s", string(body))
if r.StatusCode != http.StatusOK {
return libol.NewErr("%s %s", r.Status, body)
} else if o != nil {
if err := json.Unmarshal(body, o); err != nil {
return err
}
}
}
return nil
}
func (cl Client) GetJSON(url string, v interface{}) error {
client := cl.NewRequest(url)
client.Method = "GET"
return cl.JSON(client, nil, v)
}
func (cl Client) PostJSON(url string, i, o interface{}) error {
client := cl.NewRequest(url)
client.Method = "POST"
return cl.JSON(client, i, o)
}
func (cl Client) PutJSON(url string, i, o interface{}) error {
client := cl.NewRequest(url)
client.Method = "PUT"
return cl.JSON(client, i, o)
}
func (cl Client) DeleteJSON(url string, i, o interface{}) error {
client := cl.NewRequest(url)
client.Method = "DELETE"
return cl.JSON(client, i, o)
}
func (cl Client) Log() *libol.SubLogger {
return libol.NewSubLogger("cli")
}
type Cmd struct {
}
func (c Cmd) NewHttp(token string) Client {
client := Client{
Auth: libol.Auth{
Username: token,
},
}
return client
}
func (c Cmd) Url(prefix, name string) string {
return ""
}
func (c Cmd) Tmpl() string {
return ""
}
func (c Cmd) Out(data interface{}, format string, tmpl string) error {
return api.Out(data, format, tmpl)
}
func (c Cmd) Log() *libol.SubLogger {
return libol.NewSubLogger("cli")
}

45
cmd/api/v5/cmd.go Executable file
View File

@@ -0,0 +1,45 @@
package v5
import (
"github.com/luscis/openlan/cmd/api"
"github.com/urfave/cli/v2"
"io/ioutil"
"strings"
)
func Before(c *cli.Context) error {
token := c.String("token")
if token == "" {
tokenFile := api.AdminTokenFile
if data, err := ioutil.ReadFile(tokenFile); err == nil {
token = strings.TrimSpace(string(data))
}
_ = c.Set("token", token)
}
return nil
}
func After(c *cli.Context) error {
return nil
}
func Commands(app *api.App) {
app.After = After
app.Before = Before
User{}.Commands(app)
ACL{}.Commands(app)
Device{}.Commands(app)
Lease{}.Commands(app)
Config{}.Commands(app)
Point{}.Commands(app)
VPNClient{}.Commands(app)
Link{}.Commands(app)
Server{}.Commands(app)
Network{}.Commands(app)
PProf{}.Commands(app)
Esp{}.Commands(app)
VxLAN{}.Commands(app)
State{}.Commands(app)
Policy{}.Commands(app)
Version{}.Commands(app)
}

202
cmd/api/v5/config.go Executable file
View File

@@ -0,0 +1,202 @@
package v5
import (
"fmt"
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/config"
"github.com/luscis/openlan/pkg/libol"
"github.com/luscis/openlan/pkg/schema"
"github.com/urfave/cli/v2"
"gopkg.in/yaml.v2"
"path/filepath"
)
type Config struct {
Cmd
}
func (u Config) Url(prefix, name string) string {
if name == "" {
return prefix + "/api/config"
}
return prefix + "/api/config/" + name
}
func (u Config) List(c *cli.Context) error {
url := u.Url(c.String("url"), "")
clt := u.NewHttp(c.String("token"))
cfg := &config.Switch{}
if err := clt.GetJSON(url, cfg); err == nil {
var data []byte
if c.String("format") == "yaml" {
data, _ = yaml.Marshal(cfg)
} else {
data, _ = libol.Marshal(cfg, true)
}
fmt.Println(string(data))
return nil
} else {
return err
}
}
func (u Config) Check(c *cli.Context) error {
out := u.Log()
dir := c.String("dir")
// Check proxy configurations.
out.Info("%15s: %s", "check", "proxy")
file := filepath.Join(dir, "proxy.json")
if err := libol.FileExist(file); err == nil {
obj := &config.Proxy{}
if err := libol.UnmarshalLoad(obj, file); err != nil {
out.Warn("%15s: %s", filepath.Base(file), err)
} else {
out.Info("%15s: %s", filepath.Base(file), "success")
}
}
// Check OLAP configurations.
out.Info("%15s: %s", "check", "point")
file = filepath.Join(dir, "point.json")
if err := libol.FileExist(file); err == nil {
obj := &config.Point{}
if err := libol.UnmarshalLoad(obj, file); err != nil {
out.Warn("%15s: %s", filepath.Base(file), err)
} else {
out.Info("%15s: %s", filepath.Base(file), "success")
}
}
// Check OLSW configurations.
out.Info("%15s: %s", "check", "switch")
file = filepath.Join(dir, "switch", "switch.json")
if err := libol.FileExist(file); err == nil {
obj := &config.Switch{}
if err := libol.UnmarshalLoad(obj, file); err != nil {
out.Warn("%15s: %s", filepath.Base(file), err)
} else {
out.Info("%15s: %s", filepath.Base(file), "success")
}
}
// Check network configurations.
out.Info("%15s: %s", "check", "network")
pattern := filepath.Join(dir, "switch", "network", "*.json")
if files, err := filepath.Glob(pattern); err == nil {
for _, file := range files {
obj := &config.Network{}
if err := libol.UnmarshalLoad(obj, file); err != nil {
out.Warn("%15s: %s", filepath.Base(file), err)
} else {
out.Info("%15s: %s", filepath.Base(file), "success")
}
}
}
// Check ACL configurations.
out.Info("%15s: %s", "check", "acl")
pattern = filepath.Join(dir, "switch", "acl", "*.json")
if files, err := filepath.Glob(pattern); err == nil {
for _, file := range files {
obj := &config.ACL{}
if err := libol.UnmarshalLoad(obj, file); err != nil {
out.Warn("%15s: %s", filepath.Base(file), err)
} else {
out.Info("%15s: %s", filepath.Base(file), "success")
}
}
}
// Check links configurations.
out.Info("%15s: %s", "check", "link")
pattern = filepath.Join(dir, "switch", "link", "*.json")
if files, err := filepath.Glob(pattern); err == nil {
for _, file := range files {
var obj []config.Point
if err := libol.UnmarshalLoad(&obj, file); err != nil {
out.Warn("%15s: %s", filepath.Base(file), err)
} else {
out.Info("%15s: %s", filepath.Base(file), "success")
}
}
}
// Check routes configurations.
out.Info("%15s: %s", "check", "route")
pattern = filepath.Join(dir, "switch", "route", "*.json")
if files, err := filepath.Glob(pattern); err == nil {
for _, file := range files {
var obj []config.PrefixRoute
if err := libol.UnmarshalLoad(&obj, file); err != nil {
out.Warn("%15s: %s", filepath.Base(file), err)
} else {
out.Info("%15s: %s", filepath.Base(file), "success")
}
}
}
return nil
}
func (u Config) Reload(c *cli.Context) error {
url := u.Url(c.String("url"), "reload")
clt := u.NewHttp(c.String("token"))
data := &schema.Message{}
if err := clt.PutJSON(url, nil, data); err == nil {
fmt.Println(data.Message)
return nil
} else {
return err
}
}
func (u Config) Save(c *cli.Context) error {
url := u.Url(c.String("url"), "save")
clt := u.NewHttp(c.String("token"))
data := &schema.Message{}
if err := clt.PutJSON(url, nil, data); err == nil {
fmt.Println(data.Message)
return nil
} else {
return err
}
}
func (u Config) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "config",
Aliases: []string{"cfg"},
Usage: "Switch configuration",
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "Display all configuration",
Aliases: []string{"ls"},
Flags: []cli.Flag{
&cli.StringFlag{Name: "format", Value: "json"},
},
Action: u.List,
},
{
Name: "check",
Usage: "Check all configuration",
Aliases: []string{"co"},
Flags: []cli.Flag{
&cli.StringFlag{Name: "dir", Value: "/etc/openlan"},
},
Action: u.Check,
},
{
Name: "reload",
Usage: "Reload configuration",
Aliases: []string{"re"},
Flags: []cli.Flag{
&cli.StringFlag{Name: "dir", Value: "/etc/openlan"},
},
Action: u.Reload,
},
{
Name: "save",
Usage: "Save configuration",
Aliases: []string{"sa"},
Flags: []cli.Flag{
&cli.StringFlag{Name: "dir", Value: "/etc/openlan"},
},
Action: u.Save,
},
},
})
}

54
cmd/api/v5/device.go Executable file
View File

@@ -0,0 +1,54 @@
package v5
import (
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/schema"
"github.com/urfave/cli/v2"
)
type Device struct {
Cmd
}
func (u Device) Url(prefix, name string) string {
if name == "" {
return prefix + "/api/device"
} else {
return prefix + "/api/device/" + name
}
}
func (u Device) Tmpl() string {
return `# total {{ len . }}
{{ps -13 "name"}} {{ps -13 "mtu"}} {{ps -16 "mac"}} {{ps -6 "provider"}}
{{- range . }}
{{ps -13 .Name}} {{pi -13 .Mtu}} {{ps -16 .Mac}} {{ps -6 .Provider}}
{{- end }}
`
}
func (u Device) List(c *cli.Context) error {
url := u.Url(c.String("url"), "")
clt := u.NewHttp(c.String("token"))
var items []schema.Device
if err := clt.GetJSON(url, &items); err != nil {
return err
}
return u.Out(items, c.String("format"), u.Tmpl())
}
func (u Device) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "device",
Aliases: []string{"dev"},
Usage: "linux network device",
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "Display all devices",
Aliases: []string{"ls"},
Action: u.List,
},
},
})
}

54
cmd/api/v5/esp.go Executable file
View File

@@ -0,0 +1,54 @@
package v5
import (
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/schema"
"github.com/urfave/cli/v2"
)
type Esp struct {
Cmd
}
func (u Esp) Url(prefix, name string) string {
if name == "" {
return prefix + "/api/esp"
} else {
return prefix + "/api/esp/" + name
}
}
func (u Esp) Tmpl() string {
return `# total {{ len . }}
{{ps -16 "name"}} {{ps -16 "address"}}
{{- range . }}
{{ps -16 .Name}} {{ps -16 .Address}}
{{- end }}
`
}
func (u Esp) List(c *cli.Context) error {
url := u.Url(c.String("url"), "")
clt := u.NewHttp(c.String("token"))
var items []schema.Esp
if err := clt.GetJSON(url, &items); err != nil {
return err
}
return u.Out(items, c.String("format"), u.Tmpl())
}
func (u Esp) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "esp",
Aliases: []string{"esp"},
Usage: "IPSec ESP configuration",
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "Display all esp",
Aliases: []string{"ls"},
Action: u.List,
},
},
})
}

54
cmd/api/v5/lease.go Executable file
View File

@@ -0,0 +1,54 @@
package v5
import (
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/schema"
"github.com/urfave/cli/v2"
)
type Lease struct {
Cmd
}
func (u Lease) Url(prefix, name string) string {
if name == "" {
return prefix + "/api/lease"
} else {
return prefix + "/api/lease/" + name
}
}
func (u Lease) Tmpl() string {
return `# total {{ len . }}
{{ps -16 "uuid"}} {{ps -16 "alias"}} {{ ps -16 "address" }} {{ps -22 "client"}} {{ps -8 "network"}} {{ ps -6 "type"}}
{{- range . }}
{{ps -16 .UUID}} {{ps -16 .Alias}} {{ ps -16 .Address}} {{ps -22 .Client}} {{ps -8 .Network}} {{ ps -6 .Type}}
{{- end }}
`
}
func (u Lease) List(c *cli.Context) error {
url := u.Url(c.String("url"), "")
clt := u.NewHttp(c.String("token"))
var items []schema.Lease
if err := clt.GetJSON(url, &items); err != nil {
return err
}
return u.Out(items, c.String("format"), u.Tmpl())
}
func (u Lease) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "lease",
Aliases: []string{"le"},
Usage: "DHCP address lease",
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "Display all lease",
Aliases: []string{"ls"},
Action: u.List,
},
},
})
}

54
cmd/api/v5/link.go Executable file
View File

@@ -0,0 +1,54 @@
package v5
import (
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/schema"
"github.com/urfave/cli/v2"
)
type Link struct {
Cmd
}
func (u Link) Url(prefix, name string) string {
if name == "" {
return prefix + "/api/link"
} else {
return prefix + "/api/link/" + name
}
}
func (u Link) Tmpl() string {
return `# total {{ len . }}
{{ps -16 "uuid"}} {{ps -8 "alive"}} {{ ps -8 "device" }} {{ps -8 "user"}} {{ps -22 "server"}} {{ps -8 "network"}} {{ ps -6 "state"}}
{{- range . }}
{{ps -16 .UUID}} {{pt .AliveTime | ps -8}} {{ ps -8 .Device}} {{ps -8 .User}} {{ps -22 .Server}} {{ps -8 .Network}} {{ ps -6 .State}}
{{- end }}
`
}
func (u Link) List(c *cli.Context) error {
url := u.Url(c.String("url"), "")
clt := u.NewHttp(c.String("token"))
var items []schema.Link
if err := clt.GetJSON(url, &items); err != nil {
return err
}
return u.Out(items, c.String("format"), u.Tmpl())
}
func (u Link) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "link",
Aliases: []string{"ln"},
Usage: "Link connect to others",
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "Display all links",
Aliases: []string{"ls"},
Action: u.List,
},
},
})
}

43
cmd/api/v5/network.go Executable file
View File

@@ -0,0 +1,43 @@
package v5
import (
"fmt"
"github.com/luscis/openlan/cmd/api"
"github.com/urfave/cli/v2"
)
type Network struct {
Cmd
}
func (u Network) Url(prefix, name string) string {
return prefix + "/api/network"
}
func (u Network) List(c *cli.Context) error {
url := u.Url(c.String("url"), "")
url += "?format=" + c.String("format")
clt := u.NewHttp(c.String("token"))
if data, err := clt.GetBody(url); err == nil {
fmt.Println(string(data))
return nil
} else {
return err
}
}
func (u Network) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "network",
Aliases: []string{"net"},
Usage: "Logical network",
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "Display all network",
Aliases: []string{"ls"},
Action: u.List,
},
},
})
}

54
cmd/api/v5/openvpn.go Executable file
View File

@@ -0,0 +1,54 @@
package v5
import (
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/schema"
"github.com/urfave/cli/v2"
)
type VPNClient struct {
Cmd
}
func (u VPNClient) Url(prefix, name string) string {
if name == "" {
return prefix + "/api/vpn/client"
} else {
return prefix + "/api/vpn/client/" + name
}
}
func (u VPNClient) Tmpl() string {
return `# total {{ len . }}
{{ps -8 "alive"}} {{ps -16 "address"}} {{ ps -13 "device" }} {{ps -15 "name"}} {{ps -22 "remote"}} {{ ps -6 "state"}}
{{- range . }}
{{pt .AliveTime | ps -8}} {{ps -16 .Address}} {{ ps -13 .Device }} {{ps -15 .Name}} {{ps -22 .Remote}} {{ ps -6 .State}}
{{- end }}
`
}
func (u VPNClient) List(c *cli.Context) error {
url := u.Url(c.String("url"), c.String("network"))
clt := u.NewHttp(c.String("token"))
var items []schema.VPNClient
if err := clt.GetJSON(url, &items); err != nil {
return err
}
return u.Out(items, c.String("format"), u.Tmpl())
}
func (u VPNClient) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "client",
Aliases: []string{"cl"},
Usage: "Connected client by OpenVPN",
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "Display all clients",
Aliases: []string{"ls"},
Action: u.List,
},
},
})
}

54
cmd/api/v5/point.go Executable file
View File

@@ -0,0 +1,54 @@
package v5
import (
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/schema"
"github.com/urfave/cli/v2"
)
type Point struct {
Cmd
}
func (u Point) Url(prefix, name string) string {
if name == "" {
return prefix + "/api/point"
} else {
return prefix + "/api/point/" + name
}
}
func (u Point) Tmpl() string {
return `# total {{ len . }}
{{ps -16 "uuid"}} {{ps -8 "alive"}} {{ ps -8 "device" }} {{ps -16 "alias"}} {{ps -8 "user"}} {{ps -22 "remote"}} {{ps -8 "network"}} {{ ps -6 "state"}}
{{- range . }}
{{ps -16 .UUID}} {{pt .AliveTime | ps -8}} {{ ps -8 .Device}} {{ps -16 .Alias}} {{ps -8 .User}} {{ps -22 .Remote}} {{ps -8 .Network}} {{ ps -6 .State}}
{{- end }}
`
}
func (u Point) List(c *cli.Context) error {
url := u.Url(c.String("url"), "")
clt := u.NewHttp(c.String("token"))
var items []schema.Point
if err := clt.GetJSON(url, &items); err != nil {
return err
}
return u.Out(items, c.String("format"), u.Tmpl())
}
func (u Point) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "point",
Aliases: []string{"ap"},
Usage: "Point connected to this",
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "Display all points",
Aliases: []string{"ls"},
Action: u.List,
},
},
})
}

60
cmd/api/v5/policy.go Executable file
View File

@@ -0,0 +1,60 @@
package v5
import (
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/schema"
"github.com/urfave/cli/v2"
"sort"
)
type Policy struct {
Cmd
}
func (u Policy) Url(prefix, name string) string {
if name == "" {
return prefix + "/api/policy"
} else {
return prefix + "/api/policy/" + name
}
}
func (u Policy) Tmpl() string {
return `# total {{ len . }}
{{ps -16 "name"}} {{ ps -20 "source" }} {{ ps -20 "destination" }}
{{- range . }}
{{ps -16 .Name}} {{ ps -20 .Source }} {{ ps -20 .Dest }}
{{- end }}
`
}
func (u Policy) List(c *cli.Context) error {
url := u.Url(c.String("url"), "")
clt := u.NewHttp(c.String("token"))
var items []schema.EspPolicy
if err := clt.GetJSON(url, &items); err != nil {
return err
}
sort.SliceStable(items, func(i, j int) bool {
ii := items[i]
jj := items[j]
return ii.Name+ii.Source > jj.Name+jj.Source
})
return u.Out(items, c.String("format"), u.Tmpl())
}
func (u Policy) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "policy",
Aliases: []string{"po"},
Usage: "IPSec policy configuration",
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "Display all xfrm policy",
Aliases: []string{"ls"},
Action: u.List,
},
},
})
}

76
cmd/api/v5/pprof.go Executable file
View File

@@ -0,0 +1,76 @@
package v5
import (
"fmt"
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/libol"
"github.com/luscis/openlan/pkg/schema"
"github.com/urfave/cli/v2"
)
type PProf struct {
Cmd
}
func (u PProf) Url(prefix, name string) string {
return prefix + "/api/pprof"
}
func (u PProf) Add(c *cli.Context) error {
pp := schema.PProf{
Listen: c.String("listen"),
}
if pp.Listen == "" {
return libol.NewErr("listen value is empty")
}
url := u.Url(c.String("url"), "")
clt := u.NewHttp(c.String("token"))
if err := clt.PostJSON(url, pp, nil); err != nil {
return err
}
return nil
}
func (u PProf) Del(c *cli.Context) error {
url := u.Url(c.String("url"), "")
clt := u.NewHttp(c.String("token"))
if err := clt.DeleteJSON(url, nil, nil); err != nil {
return err
}
return nil
}
func (u PProf) List(c *cli.Context) error {
url := u.Url(c.String("url"), "")
clt := u.NewHttp(c.String("token"))
var pp schema.PProf
if err := clt.GetJSON(url, &pp); err != nil {
return err
}
fmt.Println(pp.Listen)
return nil
}
func (u PProf) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "pprof",
Aliases: []string{"pp"},
Usage: "Configure pprof tool",
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "Show configuration",
Aliases: []string{"ls"},
Action: u.List,
},
{
Name: "enable",
Usage: "Enable pprof tool",
Flags: []cli.Flag{
&cli.StringFlag{Name: "listen", Value: "127.0.0.1:6060"},
},
Action: u.Add,
},
},
})
}

43
cmd/api/v5/server.go Executable file
View File

@@ -0,0 +1,43 @@
package v5
import (
"fmt"
"github.com/luscis/openlan/cmd/api"
"github.com/urfave/cli/v2"
)
type Server struct {
Cmd
}
func (u Server) Url(prefix, name string) string {
return prefix + "/api/server"
}
func (u Server) List(c *cli.Context) error {
url := u.Url(c.String("url"), "")
url += "?format=" + c.String("format")
clt := u.NewHttp(c.String("token"))
if data, err := clt.GetBody(url); err == nil {
fmt.Println(string(data))
return nil
} else {
return err
}
}
func (u Server) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "server",
Aliases: []string{"sr"},
Usage: "Socket server status",
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "Display server status",
Aliases: []string{"ls"},
Action: u.List,
},
},
})
}

60
cmd/api/v5/state.go Normal file
View File

@@ -0,0 +1,60 @@
package v5
import (
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/schema"
"github.com/urfave/cli/v2"
"sort"
)
type State struct {
Cmd
}
func (u State) Url(prefix, name string) string {
if name == "" {
return prefix + "/api/state"
} else {
return prefix + "/api/state/" + name
}
}
func (u State) Tmpl() string {
return `# total {{ len . }}
{{ps -16 "name"}} {{ps -8 "spi"}} {{ ps -16 "local" }} {{ ps -16 "remote" }} {{ ps -12 "rx bytes" }} {{ ps -12 "tx bytes" }} {{ ps -12 "rx packages" }} {{ ps -12 "tx packages" }}
{{- range . }}
{{ps -16 .Name}} {{pi -8 .Spi }} {{ ps -16 .Local }} {{ ps -16 .Remote }} {{ pi -12 .RxBytes }} {{ pi -12 .TxBytes }} {{ pi -12 .RxPackages }} {{ pi -12 .TxPackages }}
{{- end }}
`
}
func (u State) List(c *cli.Context) error {
url := u.Url(c.String("url"), "")
clt := u.NewHttp(c.String("token"))
var items []schema.EspState
if err := clt.GetJSON(url, &items); err != nil {
return err
}
sort.SliceStable(items, func(i, j int) bool {
ii := items[i]
jj := items[j]
return ii.Spi > jj.Spi
})
return u.Out(items, c.String("format"), u.Tmpl())
}
func (u State) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "state",
Aliases: []string{"se"},
Usage: "IPSec state configuration",
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "Display all xfrm state",
Aliases: []string{"ls"},
Action: u.List,
},
},
})
}

198
cmd/api/v5/user.go Executable file
View File

@@ -0,0 +1,198 @@
package v5
import (
"fmt"
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/libol"
"github.com/luscis/openlan/pkg/schema"
"github.com/urfave/cli/v2"
"os"
"strings"
"time"
)
type User struct {
Cmd
}
func (u User) Url(prefix, name string) string {
if name == "" {
return prefix + "/api/user"
} else {
return prefix + "/api/user/" + name
}
}
func (u User) Add(c *cli.Context) error {
username := c.String("name")
user := &schema.User{
Name: username,
Password: c.String("password"),
Role: c.String("role"),
Lease: c.String("lease"),
}
if user.Name == "" {
return libol.NewErr("name is empty")
}
if !strings.Contains(username, "@") {
return libol.NewErr("name not contains network")
}
values := strings.SplitN(username, "@", 2)
user.Name = values[0]
user.Network = values[1]
url := u.Url(c.String("url"), user.Name)
clt := u.NewHttp(c.String("token"))
if err := clt.PostJSON(url, user, nil); err != nil {
return err
}
return nil
}
func (u User) Remove(c *cli.Context) error {
username := c.String("name")
url := u.Url(c.String("url"), username)
clt := u.NewHttp(c.String("token"))
if err := clt.DeleteJSON(url, nil, nil); err != nil {
return err
}
return nil
}
func (u User) Tmpl() string {
return `# total {{ len . }}
{{ps -24 "username"}} {{ps -24 "password"}} {{ps -6 "role"}} {{ps -15 "lease"}}
{{- range . }}
{{p2 -24 "%s@%s" .Name .Network}} {{ps -24 .Password}} {{ps -6 .Role}} {{ps -15 .Lease }}
{{- end }}
`
}
func (u User) List(c *cli.Context) error {
url := u.Url(c.String("url"), "")
clt := u.NewHttp(c.String("token"))
var items []schema.User
if err := clt.GetJSON(url, &items); err != nil {
return err
}
return u.Out(items, c.String("format"), u.Tmpl())
}
func (u User) Get(c *cli.Context) error {
username := c.String("name")
url := u.Url(c.String("url"), username)
client := u.NewHttp(c.String("token"))
items := []schema.User{{}}
if err := client.GetJSON(url, &items[0]); err != nil {
return err
}
return u.Out(items, c.String("format"), u.Tmpl())
}
func (u User) Check(c *cli.Context) error {
netFromO := c.String("network")
nameFromE := c.String("name")
passFromE := c.String("password")
if nameFromE == "" {
nameFromE = os.Getenv("username")
passFromE = os.Getenv("password")
}
netFromE := "default"
if strings.Contains(nameFromE, "@") {
netFromE = strings.Split(nameFromE, "@")[1]
}
fullName := nameFromE
if !strings.Contains(nameFromE, "@") {
fullName = nameFromE + "@" + netFromE
}
if netFromO != "" && netFromE != netFromO {
return libol.NewErr("wrong: zo=%s, us=%s", netFromO, nameFromE)
}
alias := ""
if ip, ok := os.LookupEnv("untrusted_ip"); ok {
alias = ip + ":" + os.Getenv("untrusted_port")
}
url := u.Url(c.String("url"), fullName)
url += "/check"
client := u.NewHttp(c.String("token"))
data := &schema.User{
Name: fullName,
Password: passFromE,
Alias: alias,
}
if err := client.PostJSON(url, data, nil); err == nil {
fmt.Printf("success: us=%s\n", nameFromE)
return nil
} else {
return err
}
}
func (u User) Commands(app *api.App) {
lease := time.Now().AddDate(99, 0, 0)
app.Command(&cli.Command{
Name: "user",
Aliases: []string{"us"},
Usage: "User authentication",
Subcommands: []*cli.Command{
{
Name: "add",
Usage: "Add a new user",
Flags: []cli.Flag{
&cli.StringFlag{Name: "name"},
&cli.StringFlag{Name: "password", Value: libol.GenRandom(24)},
&cli.StringFlag{Name: "role", Value: "guest"},
&cli.StringFlag{Name: "lease", Value: lease.Format(libol.LeaseTime)},
},
Action: u.Add,
},
{
Name: "set",
Usage: "Update a user",
Flags: []cli.Flag{
&cli.StringFlag{Name: "name"},
&cli.StringFlag{Name: "password"},
&cli.StringFlag{Name: "role"},
&cli.StringFlag{Name: "lease"},
},
Action: u.Add,
},
{
Name: "remove",
Usage: "Remove an existing user",
Aliases: []string{"rm"},
Flags: []cli.Flag{
&cli.StringFlag{Name: "name"},
},
Action: u.Remove,
},
{
Name: "list",
Usage: "Display all users",
Aliases: []string{"ls"},
Flags: []cli.Flag{
&cli.StringFlag{Name: "network"},
},
Action: u.List,
},
{
Name: "get",
Usage: "Get an user",
Flags: []cli.Flag{
&cli.StringFlag{Name: "name"},
},
Action: u.Get,
},
{
Name: "check",
Usage: "Check an user",
Aliases: []string{"co"},
Flags: []cli.Flag{
&cli.StringFlag{Name: "name"},
&cli.StringFlag{Name: "password"},
&cli.StringFlag{Name: "network"},
},
Action: u.Check,
},
},
})
}

40
cmd/api/v5/version.go Executable file
View File

@@ -0,0 +1,40 @@
package v5
import (
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/schema"
"github.com/urfave/cli/v2"
)
type Version struct {
Cmd
}
func (v Version) Url(prefix, name string) string {
return prefix + "/api/version"
}
func (v Version) Tmpl() string {
return `Version : {{ .Version }}
Build at: {{ .Date}}
`
}
func (v Version) List(c *cli.Context) error {
url := v.Url(c.String("url"), "")
clt := v.NewHttp(c.String("token"))
var item schema.Version
if err := clt.GetJSON(url, &item); err != nil {
return err
}
return v.Out(item, c.String("format"), v.Tmpl())
}
func (v Version) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "version",
Aliases: []string{"v"},
Usage: "show version information",
Action: v.List,
})
}

54
cmd/api/v5/vxlan.go Executable file
View File

@@ -0,0 +1,54 @@
package v5
import (
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/schema"
"github.com/urfave/cli/v2"
)
type VxLAN struct {
Cmd
}
func (u VxLAN) Url(prefix, name string) string {
if name == "" {
return prefix + "/api/vxlan"
} else {
return prefix + "/api/vxlan/" + name
}
}
func (u VxLAN) Tmpl() string {
return `# total {{ len . }}
{{ps -16 "name"}} {{ps -15 "bridge"}} {{ ps -16 "address" }} {{ps -16 "vni"}} {{ps -16 "local"}} {{ps -22 "remote"}}
{{- range . }}
{{ps -16 .UUID}} {{pt .AliveTime | ps -8}} {{ ps -8 .Device}} {{ps -16 .Alias}} {{ps -8 .User}} {{ps -22 .Remote}}
{{- end }}
`
}
func (u VxLAN) List(c *cli.Context) error {
url := u.Url(c.String("url"), "")
clt := u.NewHttp(c.String("token"))
var items []schema.VxLAN
if err := clt.GetJSON(url, &items); err != nil {
return err
}
return u.Out(items, c.String("format"), u.Tmpl())
}
func (u VxLAN) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "vxlan",
Aliases: []string{"vx"},
Usage: "VxLAN configuration",
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "Display all vxlan",
Aliases: []string{"ls"},
Action: u.List,
},
},
})
}

29
cmd/api/v6/cmd.go Executable file
View File

@@ -0,0 +1,29 @@
package v6
import (
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/database"
"github.com/urfave/cli/v2"
)
func Before(c *cli.Context) error {
if _, err := database.NewDBClient(nil); err == nil {
return nil
} else {
return err
}
}
func After(c *cli.Context) error {
return nil
}
func Commands(app *api.App) {
app.After = After
app.Before = Before
Switch{}.Commands(app)
Network{}.Commands(app)
Link{}.Commands(app)
Name{}.Commands(app)
Prefix{}.Commands(app)
}

262
cmd/api/v6/link.go Executable file
View File

@@ -0,0 +1,262 @@
package v6
import (
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/database"
"github.com/luscis/openlan/pkg/libol"
"github.com/ovn-org/libovsdb/model"
"github.com/ovn-org/libovsdb/ovsdb"
"github.com/urfave/cli/v2"
"sort"
"strings"
)
type Link struct {
}
func (l Link) List(c *cli.Context) error {
var lsLn []database.VirtualLink
network := c.String("network")
if err := database.Client.WhereList(
func(l *database.VirtualLink) bool {
return network == "" || l.Network == network
}, &lsLn); err != nil {
return err
} else {
sort.SliceStable(lsLn, func(i, j int) bool {
ii := lsLn[i]
jj := lsLn[j]
return ii.Network+ii.UUID > jj.Network+jj.UUID
})
return api.Out(lsLn, c.String("format"), "")
}
}
func GetUserPassword(auth string) (string, string) {
values := strings.SplitN(auth, ":", 2)
if len(values) == 2 {
return values[0], values[1]
}
return auth, auth
}
func GetDeviceName(conn, device string) string {
if libol.GetPrefix(conn, 4) == "spi:" {
return conn
} else {
return device
}
}
func (l Link) Add(c *cli.Context) error {
auth := c.String("authentication")
connection := c.String("connection")
device := c.String("device")
lsLn := database.VirtualLink{
UUID: c.String("uuid"),
Network: c.String("network"),
Connection: connection,
Device: device,
}
remoteAddr := c.String("remote-address")
user, pass := GetUserPassword(auth)
if err := database.Client.Get(&lsLn); err == nil {
lsVn := database.VirtualNetwork{
Name: lsLn.Network,
}
if lsVn.Name == "" {
return libol.NewErr("network is nil")
}
if err := database.Client.Get(&lsVn); err != nil {
return libol.NewErr("find network %s: %s", lsVn.Name, err)
}
newLn := lsLn
if connection != "" {
newLn.Connection = connection
}
if user != "" {
newLn.Authentication["username"] = user
}
if pass != "" {
newLn.Authentication["password"] = pass
}
if remoteAddr != "" {
newLn.OtherConfig["remote_address"] = remoteAddr
}
if device != "" {
newLn.Device = device
}
ops, err := database.Client.Where(&lsLn).Update(&newLn)
if err != nil {
return err
}
if ret, err := database.Client.Transact(ops...); err != nil {
return err
} else {
database.PrintError(ret)
}
} else {
lsVn := database.VirtualNetwork{
Name: c.String("network"),
}
if lsVn.Name == "" {
return libol.NewErr("network is nil")
}
if err := database.Client.Get(&lsVn); err != nil {
return libol.NewErr("find network %s: %s", lsVn.Name, err)
}
uuid := c.String("uuid")
if uuid == "" {
uuid = database.GenUUID()
}
newLn := database.VirtualLink{
Network: lsLn.Network,
Connection: lsLn.Connection,
UUID: uuid,
Device: GetDeviceName(connection, device),
Authentication: map[string]string{
"username": user,
"password": pass,
},
OtherConfig: map[string]string{
"local_address": lsVn.Address,
"remote_address": remoteAddr,
},
}
ops, err := database.Client.Create(&newLn)
if err != nil {
return err
}
libol.Debug("Link.Add %s %s", ops, lsVn)
database.Client.Execute(ops)
ops, err = database.Client.Where(&lsVn).Mutate(&lsVn, model.Mutation{
Field: &lsVn.LocalLinks,
Mutator: ovsdb.MutateOperationInsert,
Value: []string{newLn.UUID},
})
if err != nil {
return err
}
libol.Debug("Link.Add %s", ops)
database.Client.Execute(ops)
if ret, err := database.Client.Commit(); err != nil {
return err
} else {
database.PrintError(ret)
}
}
return nil
}
func (l Link) Remove(c *cli.Context) error {
lsLn := database.VirtualLink{
Network: c.String("network"),
Connection: c.String("connection"),
UUID: c.String("uuid"),
}
if err := database.Client.Get(&lsLn); err != nil {
return err
}
lsVn := database.VirtualNetwork{
Name: lsLn.Network,
}
if err := database.Client.Get(&lsVn); err != nil {
return libol.NewErr("find network %s: %s", lsVn.Name, err)
}
if err := database.Client.Get(&lsLn); err != nil {
return err
}
ops, err := database.Client.Where(&lsLn).Delete()
if err != nil {
return err
}
libol.Debug("Link.Remove %s", ops)
database.Client.Execute(ops)
ops, err = database.Client.Where(&lsVn).Mutate(&lsVn, model.Mutation{
Field: &lsVn.LocalLinks,
Mutator: ovsdb.MutateOperationDelete,
Value: []string{lsLn.UUID},
})
if err != nil {
return err
}
libol.Debug("Link.Remove %s", ops)
database.Client.Execute(ops)
if ret, err := database.Client.Commit(); err != nil {
return err
} else {
database.PrintError(ret)
}
return nil
}
func (l Link) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "link",
Aliases: []string{"li"},
Usage: "Virtual Link",
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "List virtual links",
Aliases: []string{"ls"},
Flags: []cli.Flag{
&cli.StringFlag{
Name: "network",
Usage: "the network name",
},
},
Action: l.List,
},
{
Name: "add",
Usage: "Add a virtual link",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "uuid",
},
&cli.StringFlag{
Name: "network",
Usage: "the network name",
},
&cli.StringFlag{
Name: "connection",
Value: "any",
Usage: "connection for remote server",
},
&cli.StringFlag{
Name: "device",
Usage: "the device name, like spi:10",
},
&cli.StringFlag{
Name: "authentication",
Usage: "user and password for authentication",
},
&cli.StringFlag{
Name: "remote-address",
Usage: "remote address in this link",
},
},
Action: l.Add,
},
{
Name: "del",
Usage: "Del a virtual link",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "uuid",
},
&cli.StringFlag{
Name: "network",
Usage: "the network name",
},
&cli.StringFlag{
Name: "connection",
Usage: "connection for remote server",
},
},
Action: l.Remove,
},
},
})
}

146
cmd/api/v6/name.go Executable file
View File

@@ -0,0 +1,146 @@
package v6
import (
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/database"
"github.com/luscis/openlan/pkg/libol"
"github.com/urfave/cli/v2"
"net"
"sort"
"time"
)
type Name struct {
}
func (u Name) List(c *cli.Context) error {
var listNa []database.NameCache
if err := database.Client.List(&listNa); err != nil {
return err
} else {
sort.SliceStable(listNa, func(i, j int) bool {
ii := listNa[i]
jj := listNa[j]
return ii.UUID > jj.UUID
})
return api.Out(listNa, c.String("format"), "")
}
}
func (u Name) Add(c *cli.Context) error {
name := c.String("name")
lsNa := database.NameCache{
Name: name,
UUID: c.String("uuid"),
}
if lsNa.Name == "" && lsNa.UUID == "" {
return libol.NewErr("Name is nil")
}
address := c.String("address")
if address == "" {
addrIps, _ := net.LookupIP(lsNa.Name)
if len(addrIps) > 0 {
address = addrIps[0].String()
}
}
newNa := lsNa
if name != "" {
newNa.Name = name
}
if address != "" {
newNa.Address = address
}
newNa.UpdateAt = time.Now().Format("2006-01-02T15:04")
if err := database.Client.Get(&lsNa); err == nil {
if lsNa.Address != address {
ops, err := database.Client.Where(&lsNa).Update(&newNa)
if err != nil {
return err
}
if ret, err := database.Client.Transact(ops...); err != nil {
return err
} else {
database.PrintError(ret)
}
}
} else {
ops, err := database.Client.Create(&newNa)
if err != nil {
return err
}
libol.Debug("Name.Add %s", ops)
if ret, err := database.Client.Transact(ops...); err != nil {
return err
} else {
database.PrintError(ret)
}
}
return nil
}
func (u Name) Remove(c *cli.Context) error {
lsNa := database.NameCache{
Name: c.String("name"),
UUID: c.String("uuid"),
}
if err := database.Client.Get(&lsNa); err != nil {
return nil
}
ops, err := database.Client.Where(&lsNa).Delete()
if err != nil {
return err
}
libol.Debug("Name.Remove %s", ops)
database.Client.Execute(ops)
if ret, err := database.Client.Commit(); err != nil {
return err
} else {
database.PrintError(ret)
}
return nil
}
func (u Name) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "name",
Aliases: []string{"na"},
Usage: "Name cache",
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "List name cache",
Aliases: []string{"ls"},
Action: u.List,
},
{
Name: "add",
Usage: "Add or update name cache",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "uuid",
},
&cli.StringFlag{
Name: "name",
},
&cli.StringFlag{
Name: "address",
},
},
Action: u.Add,
},
{
Name: "del",
Usage: "Delete a name cache",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "uuid",
},
&cli.StringFlag{
Name: "name",
},
},
Action: u.Remove,
},
},
})
}

154
cmd/api/v6/network.go Executable file
View File

@@ -0,0 +1,154 @@
package v6
import (
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/database"
"github.com/luscis/openlan/pkg/libol"
"github.com/ovn-org/libovsdb/model"
"github.com/ovn-org/libovsdb/ovsdb"
"github.com/urfave/cli/v2"
"sort"
)
type Network struct {
}
func (u Network) List(c *cli.Context) error {
var listVn []database.VirtualNetwork
err := database.Client.List(&listVn)
if err != nil {
return err
}
sort.SliceStable(listVn, func(i, j int) bool {
ii := listVn[i]
jj := listVn[j]
return ii.UUID > jj.UUID
})
return api.Out(listVn, c.String("format"), "")
}
func (u Network) Add(c *cli.Context) error {
name := c.String("name")
if name == "" {
return libol.NewErr("name is nil")
}
oldVn := database.VirtualNetwork{Name: name}
if err := database.Client.Get(&oldVn); err == nil {
return libol.NewErr("network %s already existed.", oldVn.Name)
}
address := c.String("address")
provider := c.String("provider")
newVn := database.VirtualNetwork{
Name: name,
Address: address,
Bridge: "br-" + name,
UUID: database.GenUUID(),
Provider: provider,
}
ops, err := database.Client.Create(&newVn)
if err != nil {
return err
}
libol.Debug("Network.Add %s", ops)
database.Client.Execute(ops)
sw, err := database.Client.Switch()
if err != nil {
return err
}
ops, err = database.Client.Where(sw).Mutate(sw, model.Mutation{
Field: &sw.VirtualNetworks,
Mutator: ovsdb.MutateOperationInsert,
Value: []string{newVn.UUID},
})
if err != nil {
return err
}
libol.Debug("Network.Add %s", ops)
database.Client.Execute(ops)
if ret, err := database.Client.Commit(); err != nil {
return err
} else {
database.PrintError(ret)
}
return nil
}
func (u Network) Remove(c *cli.Context) error {
name := c.String("name")
oldVn := database.VirtualNetwork{
Name: name,
}
if err := database.Client.Get(&oldVn); err != nil {
return err
}
ops, err := database.Client.Where(&oldVn).Delete()
if err != nil {
return err
}
libol.Debug("Switch.Remove %s", ops)
database.Client.Execute(ops)
sw, err := database.Client.Switch()
if err != nil {
return err
}
ops, err = database.Client.Where(sw).Mutate(sw, model.Mutation{
Field: &sw.VirtualNetworks,
Mutator: ovsdb.MutateOperationDelete,
Value: []string{oldVn.UUID},
})
if err != nil {
return err
}
libol.Debug("Network.Remove %s", ops)
database.Client.Execute(ops)
if ret, err := database.Client.Commit(); err != nil {
return err
} else {
database.PrintError(ret)
}
return nil
}
func (u Network) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "network",
Aliases: []string{"ne"},
Usage: "Virtual network",
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "List virtual networks",
Aliases: []string{"ls"},
Action: u.List,
},
{
Name: "add",
Usage: "Add a virtual network",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "name",
Usage: "unique name with short long"},
&cli.StringFlag{
Name: "provider",
Value: "openlan",
Usage: "provider name"},
&cli.StringFlag{
Name: "address",
Value: "169.255.169.0/24",
Usage: "ip address"},
},
Action: u.Add,
},
{
Name: "del",
Usage: "Del a virtual network",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "name",
Usage: "unique name with short long"},
},
Action: u.Remove,
},
},
})
}

171
cmd/api/v6/prefix.go Executable file
View File

@@ -0,0 +1,171 @@
package v6
import (
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/database"
"github.com/luscis/openlan/pkg/libol"
"github.com/ovn-org/libovsdb/model"
"github.com/ovn-org/libovsdb/ovsdb"
"github.com/urfave/cli/v2"
"sort"
)
type Prefix struct {
}
func (u Prefix) List(c *cli.Context) error {
var list []database.PrefixRoute
if err := database.Client.List(&list); err != nil {
return err
} else {
sort.SliceStable(list, func(i, j int) bool {
ii := list[i]
jj := list[j]
return ii.UUID > jj.UUID
})
return api.Out(list, c.String("format"), "")
}
}
func (u Prefix) Add(c *cli.Context) error {
lsVn := database.VirtualNetwork{
Name: c.String("network"),
}
if lsVn.Name == "" {
return libol.NewErr("network is nil")
}
if err := database.Client.Get(&lsVn); err != nil {
return libol.NewErr("find network %s: %s", lsVn.Name, err)
}
newPf := database.PrefixRoute{
UUID: database.GenUUID(),
Network: lsVn.Name,
Source: c.String("source"),
Prefix: c.String("prefix"),
Gateway: c.String("gateway"),
Mode: c.String("mode"),
}
ops, err := database.Client.Create(&newPf)
if err != nil {
return err
}
libol.Debug("Prefix.Add %s %s", ops, lsVn)
database.Client.Execute(ops)
ops, err = database.Client.Where(&lsVn).Mutate(&lsVn, model.Mutation{
Field: &lsVn.PrefixRoutes,
Mutator: ovsdb.MutateOperationInsert,
Value: []string{newPf.UUID},
})
if err != nil {
return err
}
libol.Debug("Prefix.Add %s", ops)
database.Client.Execute(ops)
if ret, err := database.Client.Commit(); err != nil {
return err
} else {
database.PrintError(ret)
}
return nil
}
func (u Prefix) Remove(c *cli.Context) error {
lsPf := database.PrefixRoute{
Network: c.String("network"),
Prefix: c.String("prefix"),
UUID: c.String("uuid"),
}
if err := database.Client.Get(&lsPf); err != nil {
return err
}
lsVn := database.VirtualNetwork{
Name: lsPf.Network,
}
if err := database.Client.Get(&lsVn); err != nil {
return libol.NewErr("find network %s: %s", lsVn.Name, err)
}
if err := database.Client.Get(&lsPf); err != nil {
return err
}
ops, err := database.Client.Where(&lsPf).Delete()
if err != nil {
return err
}
libol.Debug("Prefix.Remove %s", ops)
database.Client.Execute(ops)
ops, err = database.Client.Where(&lsVn).Mutate(&lsVn, model.Mutation{
Field: &lsVn.PrefixRoutes,
Mutator: ovsdb.MutateOperationDelete,
Value: []string{lsPf.UUID},
})
if err != nil {
return err
}
libol.Debug("Prefix.Remove %s", ops)
database.Client.Execute(ops)
if ret, err := database.Client.Commit(); err != nil {
return err
} else {
database.PrintError(ret)
}
return nil
}
func (u Prefix) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "route",
Aliases: []string{"ro"},
Usage: "Prefix route",
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "List prefix routes",
Aliases: []string{"ls"},
Action: u.List,
},
{
Name: "add",
Usage: "Add a prefix route",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "network",
Usage: "the network name",
},
&cli.StringFlag{
Name: "prefix",
},
&cli.StringFlag{
Name: "source",
Value: "0.0.0.0/0",
},
&cli.StringFlag{
Name: "gateway",
Value: "local",
},
&cli.StringFlag{
Name: "mode",
Value: "direct",
},
},
Action: u.Add,
},
{
Name: "del",
Usage: "delete a prefix route",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "uuid",
},
&cli.StringFlag{
Name: "network",
Usage: "the network name",
},
&cli.StringFlag{
Name: "prefix",
},
},
Action: u.Remove,
},
},
})
}

85
cmd/api/v6/switch.go Executable file
View File

@@ -0,0 +1,85 @@
package v6
import (
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/database"
"github.com/luscis/openlan/pkg/libol"
"github.com/urfave/cli/v2"
)
type Switch struct {
}
func (u Switch) List(c *cli.Context) error {
var listSw []database.Switch
if err := database.Client.List(&listSw); err == nil {
return api.Out(listSw, c.String("format"), "")
}
return nil
}
func (u Switch) Add(c *cli.Context) error {
protocol := c.String("protocol")
listen := c.Int("listen")
newSw := database.Switch{
Protocol: protocol,
Listen: listen,
}
sw, _ := database.Client.Switch()
if sw == nil {
ops, err := database.Client.Create(&newSw)
if err != nil {
return err
}
libol.Debug("Switch.Add %s", ops)
if ret, err := database.Client.Transact(ops...); err != nil {
return err
} else {
database.PrintError(ret)
}
} else {
ops, err := database.Client.Where(sw).Update(&newSw)
if err != nil {
return err
}
libol.Debug("Switch.Add %s", ops)
if ret, err := database.Client.Transact(ops...); err != nil {
return err
} else {
database.PrintError(ret)
}
}
return nil
}
func (u Switch) Commands(app *api.App) {
app.Command(&cli.Command{
Name: "switch",
Aliases: []string{"sw"},
Usage: "Global switch",
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "List global switch",
Aliases: []string{"ls"},
Action: u.List,
},
{
Name: "add",
Usage: "Add or update switch",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "protocol",
Value: "tcp",
Usage: "used protocol: tcp|udp|http|tls"},
&cli.IntFlag{
Name: "listen",
Value: 10002,
Usage: "listen on port: 1024-65535",
},
},
Action: u.Add,
},
},
})
}

29
cmd/main.go Executable file
View File

@@ -0,0 +1,29 @@
package main
import (
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/cmd/api/v5"
"github.com/luscis/openlan/cmd/api/v6"
"log"
"os"
)
func main() {
api.Version = api.GetEnv("VERSION", api.Version)
api.Url = api.GetEnv("URL", api.Url)
api.Token = api.GetEnv("TOKEN", api.Token)
api.Server = api.GetEnv("CONFSERVER", api.Server)
api.Database = api.GetEnv("DATABASE", api.Database)
app := &api.App{}
app.New()
switch api.Version {
case "v6":
v6.Commands(app)
default:
v5.Commands(app)
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}

23
cmd/point_darwin/main.go Executable file
View File

@@ -0,0 +1,23 @@
// +build darwin
package main
import (
"github.com/luscis/openlan/pkg/access"
"github.com/luscis/openlan/pkg/config"
"github.com/luscis/openlan/pkg/libol"
)
func main() {
c := config.NewPoint()
p := access.NewPoint(c)
p.Initialize()
libol.Go(p.Start)
if c.Terminal == "on" {
t := access.NewTerminal(p)
t.Start()
} else {
libol.Wait()
}
p.Stop()
}

31
cmd/point_linux/main.go Executable file
View File

@@ -0,0 +1,31 @@
// +build linux
package main
import (
"github.com/luscis/openlan/pkg/access"
"github.com/luscis/openlan/pkg/config"
"github.com/luscis/openlan/pkg/libol"
)
func main() {
c := config.NewPoint()
p := access.NewPoint(c)
// terminal off for linux service, on for open a terminal
// and others just wait.
if c.Terminal == "off" {
libol.PreNotify()
}
p.Initialize()
libol.Go(p.Start)
if c.Terminal == "on" {
t := access.NewTerminal(p)
t.Start()
} else if c.Terminal == "off" {
libol.SdNotify()
libol.Wait()
} else {
libol.Wait()
}
p.Stop()
}

23
cmd/point_windows/main.go Executable file
View File

@@ -0,0 +1,23 @@
// +build windows
package main
import (
"github.com/luscis/openlan/pkg/access"
"github.com/luscis/openlan/pkg/config"
"github.com/luscis/openlan/pkg/libol"
)
func main() {
c := config.NewPoint()
p := access.NewPoint(c)
p.Initialize()
libol.Go(p.Start)
if c.Terminal == "on" {
t := access.NewTerminal(p)
t.Start()
} else {
libol.Wait()
}
p.Stop()
}

BIN
cmd/point_windows/main.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 164 KiB

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
version="1.0.0.0"
processorArchitecture="x86"
name="uradiam.openlan.openlan-point"
type="win32"
/>
<description>Uradiam OpenLAN Point Software</description>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>

BIN
cmd/point_windows/main.syso Normal file

Binary file not shown.

20
cmd/proxy/main.go Executable file
View File

@@ -0,0 +1,20 @@
package main
import (
"github.com/luscis/openlan/pkg/config"
"github.com/luscis/openlan/pkg/libol"
"github.com/luscis/openlan/pkg/proxy"
)
func main() {
c := config.NewProxy()
libol.SetLogger(c.Log.File, c.Log.Verbose)
p := proxy.NewProxy(c)
libol.PreNotify()
p.Initialize()
libol.Go(p.Start)
libol.SdNotify()
libol.Wait()
p.Stop()
}

25
cmd/switch/main.go Executable file
View File

@@ -0,0 +1,25 @@
package main
import (
"github.com/luscis/openlan/cmd/api"
"github.com/luscis/openlan/pkg/cache"
"github.com/luscis/openlan/pkg/config"
"github.com/luscis/openlan/pkg/libol"
"github.com/luscis/openlan/pkg/switch"
)
func main() {
udp := api.GetEnv("ESPUDP", "4500")
config.SetLocalUdp(udp)
c := config.NewSwitch()
libol.SetLogger(c.Log.File, c.Log.Verbose)
libol.Debug("main %s", c)
cache.Init(&c.Perf)
s := _switch.NewSwitch(c)
libol.PreNotify()
s.Initialize()
s.Start()
libol.SdNotify()
libol.Wait()
s.Stop()
}

28
core/CMakeLists.txt Executable file
View File

@@ -0,0 +1,28 @@
cmake_minimum_required(VERSION 2.8)
project(openlan C)
set(CMAKE_C_STANDARD 99)
set(CMAKE_C_FLAGS "-std=gnu99 -g -DHAVE_CONFIG_H")
set(CMAKE_VERBOSE_MAKEFILE ON)
include_directories(../3rd/ovs)
include_directories(../3rd/ovs/lib)
include_directories(../3rd/ovs/include)
include_directories(.)
include_directories(idlc)
include_directories(tcp)
include_directories(udp)
link_directories(${CMAKE_SOURCE_DIR}/../build/obj/usr/lib)
link_directories(${CMAKE_SOURCE_DIR}/../build/obj/usr/lib64)
file(GLOB IDL_SOURCES "idlc/*.c")
file(GLOB UDP_SOURCES "udp/*.c")
file(GLOB TCP_SOURCES "tcp/*.c")
add_executable(openudp ${UDP_SOURCES} ${IDL_SOURCES})
target_link_libraries(openudp libopenvswitch.a)
target_link_libraries(openudp pthread ssl crypto rt m unbound)
add_executable(opentcp ${TCP_SOURCES})
target_link_libraries(opentcp pthread)

46
core/auto.sh Executable file
View File

@@ -0,0 +1,46 @@
#!/bin/bash
set -ex
action=$1
version=$(cat VERSION)
cd $(dirname $0)
check_and_update() {
file0=$1
file1=$2
md5f0=$(md5sum $file0 | awk '{print $1}')
md5f1=$(md5sum $file1 | awk '{print $1}')
if [ "$md5f0"x != "$md5f1"x ]; then
mv $file0 $file1
fi
}
python_bin=python
type $python_bin || python_bin="python3"
ovs_dir="../3rd/ovs"
build_idlc() {
idlc_bin="$ovs_dir/ovsdb/ovsdb-idlc.in"
[ -e "idlc/confd.ovsschema" ] || ln -s -f ../../dist/resource/confd.schema.json idlc/confd.ovsschema
PYTHONPATH="$ovs_dir/python:"$PYTHONPATH PYTHONDONTWRITEBYTECODE=yes $python_bin $idlc_bin annotate idlc/confd.ovsschema idlc/confd-idl.ann > /tmp/confd-idl.ovsidl
check_and_update /tmp/confd-idl.ovsidl idlc/confd-idl.ovsidl
PYTHONPATH="$ovs_dir/python:"$PYTHONPATH PYTHONDONTWRITEBYTECODE=yes $python_bin $idlc_bin c-idl-source idlc/confd-idl.ovsidl > /tmp/confd-idl.c
check_and_update /tmp/confd-idl.c idlc/confd-idl.c
PYTHONPATH="$ovs_dir/python:"$PYTHONPATH PYTHONDONTWRITEBYTECODE=yes $python_bin $idlc_bin c-idl-header idlc/confd-idl.ovsidl > /tmp/confd-idl.h
check_and_update /tmp/confd-idl.h idlc/confd-idl.h
}
update_version() {
cp version.h /tmp/version.h
sed -i "s/#define CORE_PACKAGE_STRING .*/#define CORE_PACKAGE_STRING \"opencore $version\"/g" /tmp/version.h
sed -i "s/#define CORE_PACKAGE_VERSION .*/#define CORE_PACKAGE_VERSION \"$version\"/g" /tmp/version.h
check_and_update /tmp/version.h version.h
}
if [ "$action"x == "build"x ] || [ "$action"x == ""x ]; then
update_version
build_idlc
elif [ "$action"x == "clean"x ]; then
echo "TODO"
fi

9
core/idlc/confd-idl.ann Normal file
View File

@@ -0,0 +1,9 @@
# -*- python -*-
# This code, when invoked by "ovsdb-idlc annotate" (by the build
# process), annotates vswitch.ovsschema with additional data that give
# the ovsdb-idl engine information about the types involved, so that
# it can generate more programmer-friendly data structures.
s["idlPrefix"] = "openrec_"
s["idlHeader"] = "\"confd-idl.h\""

1
core/idlc/confd.ovsschema Symbolic link
View File

@@ -0,0 +1 @@
../../dist/resource/confd.schema.json

9
core/tcp/README.md Normal file
View File

@@ -0,0 +1,9 @@
# build
mkdir -p build && cd ./build
cmake ..
make
# valgrind
valgrind --leak-check=yes ./build/core

10
core/tcp/control.c Normal file
View File

@@ -0,0 +1,10 @@
/*
* Copyright (c) 2021-2022 OpenLAN Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
*/
#include "control.h"

13
core/tcp/control.h Normal file
View File

@@ -0,0 +1,13 @@
/*
* Copyright (c) 2021-2022 OpenLAN Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
*/
#ifndef CORE_CONTROL_H
#define CORE_CONTROL_H
#endif //CORE_CONTROL_H

32
core/tcp/main.c Normal file
View File

@@ -0,0 +1,32 @@
/*
* Copyright (c) 2021-2022 OpenLAN Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
*/
#include <stdio.h>
#include "socket.h"
int main(int argc, char *argv[]) {
char *addr = NULL;
int port = 9090;
if (argc > 2) {
addr = argv[1];
sscanf(argv[2], "%d", &port);
} else if (argc > 1) {
sscanf(argv[1], "%d", &port);
}
if (addr == NULL) {
printf("Listen on %d!\n", port);
start_tcp_server(port);
} else {
printf("Connect to %s:%d\n", addr, port);
start_tcp_client(addr, port);
}
return 0;
}

10
core/tcp/message.c Normal file
View File

@@ -0,0 +1,10 @@
/*
* Copyright (c) 2021-2022 OpenLAN Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
*/
#include "message.h"

13
core/tcp/message.h Normal file
View File

@@ -0,0 +1,13 @@
/*
* Copyright (c) 2021-2022 OpenLAN Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
*/
#ifndef CORE_MESSAGE_H
#define CORE_MESSAGE_H
#endif //CORE_MESSAGE_H

206
core/tcp/socket.c Normal file
View File

@@ -0,0 +1,206 @@
/*
* Copyright (c) 2021-2022 OpenLAN Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
*/
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <memory.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <assert.h>
#include <pthread.h>
#include "tuntap.h"
#include "socket.h"
int non_blocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
int recv_full(int fd, char *buf, ssize_t size) {
ssize_t read_size = 0;
for (; size > 0;) {
read_size = recv(fd, buf, size, 0);
if (read_size <= 0) return read_size;
buf += read_size;
size -= read_size;
}
return 0;
}
int send_full(int fd, char *buf, ssize_t size) {
ssize_t write_size = 0;
for (;size > 0;) {
write_size = send(fd, buf, size, 0);
if (write_size <= 0) return write_size;
buf += write_size;
size -= write_size;
}
return 0;
}
void *read_client(void *argv) {
uint16_t buf_size = 0;
uint16_t read_size = 0;
uint8_t buf[4096];
peer_t *conn = NULL;
assert(NULL != argv);
conn = (peer_t *) argv;
for(;;) {
buf_size = recv_full(conn->socket_fd, buf, 4);
if (buf_size != 0) {
break;
}
read_size = ntohs(*(uint16_t *)(buf + 2));
memset(buf, 0, sizeof buf);
buf_size = recv_full(conn->socket_fd, buf, read_size);
if (buf_size != 0) {
printf("ERROR: on read %d != %d\n", read_size, buf_size);
break;
}
write(conn->device_fd, buf, read_size);
}
}
void *read_device(void *argv) {
uint16_t write_size = 0;
uint16_t read_size = 0;
uint8_t buf[4096];
peer_t *conn = NULL;
assert(NULL != argv);
conn = (peer_t *) argv;
for(;;) {
read_size = read(conn->device_fd, buf + 4, sizeof (buf));
if (read_size <= 0) {
continue;
}
*(uint16_t *)(buf + 2) = htons(read_size);
read_size += 4;
write_size = send_full(conn->socket_fd, buf, read_size);
if (write_size != 0) {
printf("ERROR: write to conn %d:%d", write_size, read_size);
break;
}
}
}
int start_peer(peer_t *peer) {
pthread_t client;
pthread_t device;
if(pthread_create(&client, NULL, read_client, &peer)) {
fprintf(stderr, "Error creating thread\n");
return 1;
}
if(pthread_create(&device, NULL, read_device, &peer)) {
fprintf(stderr, "Error creating thread\n");
return 1;
}
if(pthread_join(client, NULL)) {
fprintf(stderr, "Error joining thread\n");
return 2;
}
if(pthread_join(device, NULL)) {
fprintf(stderr, "Error joining thread\n");
return 2;
}
}
int start_tcp_server(uint16_t port) {
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(port);
int server_fd = 0;
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if(bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
printf("bind error\n");
return -1;
}
if(listen(server_fd, 2) < 0) {
printf("listen error\n");
return -1;
}
struct sockaddr_in conn_addr;
socklen_t conn_addr_len = sizeof(conn_addr);
int conn_fd = 0;
char dev_name[1024] = {0};
int tap_fd = 0;
conn_fd = accept(server_fd, (struct sockaddr *)&conn_addr, &conn_addr_len);
printf("accept connection on %d\n", conn_fd);
tap_fd = create_tap(dev_name);
printf("open device on %s with %d\n", dev_name, tap_fd);
peer_t peer = {
.socket_fd = conn_fd,
.device_fd = tap_fd,
};
start_peer(&peer);
finish:
close(conn_fd);
close(server_fd);
close(tap_fd);
printf("exit from %d\n", server_fd);
return 0;
}
int start_tcp_client(const char *addr, uint16_t port) {
int ret = 0;
int socket_fd = 0;
struct sockaddr_in server_addr;
socket_fd = socket(PF_INET, SOCK_STREAM, 0);
if (socket_fd < 0) {
printf("ERROR: open socket %d", socket_fd);
return socket_fd;
}
bzero(&server_addr, sizeof (server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr = inet_addr(addr);
ret = connect(socket_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
if(ret ==-1) {
printf("connect() error\n");
return ret;
}
char dev_name[1024] = {0};
int tap_fd = 0;
tap_fd = create_tap(dev_name);
printf("open device on %s with %d\n", dev_name, tap_fd);
peer_t peer = {
.socket_fd = socket_fd,
.device_fd = tap_fd,
};
start_peer(&peer);
finish:
close(socket_fd);
close(tap_fd);
return 0;
}

23
core/tcp/socket.h Normal file
View File

@@ -0,0 +1,23 @@
/*
* Copyright (c) 2021-2022 OpenLAN Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
*/
#ifndef CORE_SOCKET_H
#define CORE_SOCKET_H
#include "types.h"
typedef struct {
int socket_fd;
int device_fd;
} peer_t;
int start_tcp_server(uint16_t port);
int start_tcp_client(const char *addr, uint16_t port);
#endif //CORE_SOCKET_H

40
core/tcp/tuntap.c Normal file
View File

@@ -0,0 +1,40 @@
/*
* Copyright (c) 2021-2022 OpenLAN Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
*/
#include <assert.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/if.h>
#include <linux/if_tun.h>
#include <string.h>
#include "tuntap.h"
int create_tap(char *name) {
struct ifreq ifr;
int fd = -1;
int err = -1;
assert(NULL != name);
if((fd = open(DEV_NET_TUN, O_RDWR)) < 0 ) {
return -1;
}
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = IFF_TAP | IFF_NO_PI; /* IFF_TUN or IFF_TAP, plus maybe IFF_NO_PI */
if (*name) {
strncpy(ifr.ifr_name, name, IFNAMSIZ);
}
if((err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0) {
close(fd);
return err;
}
strcpy(name, ifr.ifr_name);
return fd;
}

19
core/tcp/tuntap.h Normal file
View File

@@ -0,0 +1,19 @@
/*
* Copyright (c) 2021-2022 OpenLAN Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
*/
#ifndef CORE_TUNTAP_H
#define CORE_TUNTAP_H
#include <unistd.h>
#define DEV_NET_TUN "/dev/net/tun"
int create_tap(char *name);
#endif //CORE_TUNTAP_H

37
core/tcp/types.h Normal file
View File

@@ -0,0 +1,37 @@
/*
* Copyright (c) 2021-2022 OpenLAN Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
*/
#ifndef CORE_TYPES_H
#define CORE_TYPES_H
#ifndef int8_t
#define int8_t char
#endif
#ifndef uint8_t
#define uint8_t unsigned char
#endif
#ifndef uint16_t
#define uint16_t unsigned short
#endif
#ifndef int16_t
#define int16_t short
#endif
#ifndef uint32_t
#define uint32_t unsigned int
#endif
#ifndef int32_t
#define int32_t int
#endif
#endif //CORE_TYPES_H

368
core/udp/main.c Executable file
View File

@@ -0,0 +1,368 @@
/*
* Copyright (c) 2021-2022 OpenLAN Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
*/
#include <config.h>
#include <errno.h>
#include <getopt.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "openvswitch/dynamic-string.h"
#include "openvswitch/poll-loop.h"
#include "openvswitch/vconn.h"
#include "openvswitch/vlog.h"
#include "ovsdb-data.h"
#include "ovsdb-idl-provider.h"
#include "command-line.h"
#include "confd-idl.h"
#include "daemon.h"
#include "udp.h"
#include "unixctl.h"
#include "ovs-thread.h"
#include "timeval.h"
#include "version.h"
#define RUN_DIR "/var/openlan"
#define UDP_PORT 4500
VLOG_DEFINE_THIS_MODULE(main);
/* Rate limit for error messages. */
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
static char *default_db_ = NULL;
static char *db_remote = NULL;
static int32_t udp_port = 0;
struct udp_context {
struct udp_server *srv;
struct ovsdb_idl *idl;
struct ovsdb_idl_txn *idl_txn;
struct shash names;
struct shash networks;
struct shash links;
};
static inline char *
unixctl_dir()
{
return xasprintf("%s/%s.ctl", RUN_DIR, program_name);
}
static inline char *
default_db(void)
{
if (!default_db_) {
default_db_ = xasprintf("unix:%s/confd.sock", RUN_DIR);
}
return default_db_;
}
static void
usage(void)
{
printf("\
%s: OpenLAN UDP Connection\n\
usage %s [OPTIONS]\n\
\n\
Options:\n\
--port=PORT listen on local udp PORT\n\
(default: %d)\n\
--db=DATABASE connect to database at DATABASE\n\
(default: %s)\n\
-h, --help display this help message\n\
-o, --options list available options\n\
-V, --version display version information\n\
", program_name, program_name, UDP_PORT, default_db());
vlog_usage();
exit(EXIT_SUCCESS);
}
static void
parse_options(int argc, char *argv[])
{
enum {
VLOG_OPTION_ENUMS,
};
static struct option long_options[] = {
{"port", required_argument, NULL, 'p'},
{"db", required_argument, NULL, 'd'},
{"help", no_argument, NULL, 'h'},
{"version", no_argument, NULL, 'V'},
VLOG_LONG_OPTIONS,
{NULL, 0, NULL, 0}
};
char *short_options = ovs_cmdl_long_options_to_short_options(long_options);
for (;;) {
int c;
c = getopt_long(argc, argv, short_options, long_options, NULL);
if (c == -1) {
break;
}
switch (c) {
case 'd':
db_remote = xstrdup(optarg);
break;
case 'p':
udp_port = atoi(optarg);
break;
case 'h':
usage();
case 'V':
ovs_print_version(OFP13_VERSION, OFP13_VERSION);
exit(EXIT_SUCCESS);
VLOG_OPTION_HANDLERS
case '?':
exit(EXIT_FAILURE);
default:
abort();
}
}
free(short_options);
if (!db_remote) {
db_remote = xstrdup(default_db());
}
if (!udp_port) {
udp_port = UDP_PORT;
}
}
static void
udp_exit(struct unixctl_conn *conn, int argc OVS_UNUSED,
const char *argv[] OVS_UNUSED, void *exiting_)
{
bool *exiting = exiting_;
*exiting = true;
unixctl_command_reply(conn, NULL);
}
static void
cache_run(struct udp_context *ctx)
{
const struct openrec_name_cache *nc;
const struct openrec_virtual_network *vn;
const struct openrec_virtual_link *vl;
shash_empty(&ctx->names);
shash_empty(&ctx->networks);
shash_empty(&ctx->links);
OPENREC_NAME_CACHE_FOR_EACH (nc, ctx->idl) {
VLOG_DBG("name_cache: %s %s", nc->name, nc->address);
shash_add(&ctx->names, nc->name, nc);
}
OPENREC_VIRTUAL_NETWORK_FOR_EACH (vn, ctx->idl) {
VLOG_DBG("virtual_network: %s %s", vn->name, vn->address);
shash_add(&ctx->networks, vn->name, vn);
}
OPENREC_VIRTUAL_LINK_FOR_EACH (vl, ctx->idl) {
VLOG_DBG("virtual_link: %s %s", vl->network, vl->connection);
if (!strncmp(vl->connection, "any", 3) || !strlen(vl->connection)) {
shash_add(&ctx->links, vl->device, vl);
} else {
shash_add(&ctx->links, vl->connection, vl);
}
}
}
static void
ping_run(struct udp_context *ctx)
{
char address[128] = {0};
struct udp_server *srv = ctx->srv;
if (time_msec() - srv->send_t < 5 *1000) {
return;
}
struct udp_connect conn = {
.socket = srv->socket,
.remote_port = UDP_PORT,
.remote_address = address,
};
struct shash_node *node;
SHASH_FOR_EACH(node, &ctx->links) {
const struct openrec_virtual_link *vl = node->data;
if (strncmp(vl->device, "spi:", 4) || strncmp(vl->connection, "udp:", 4)) {
continue;
}
VLOG_DBG("send_ping to %s on %s\n", vl->connection, vl->device);
ovs_scan(vl->device, "spi:%d", &conn.spi);
ovs_scan(vl->connection, "udp:%[^:]:%d", address, &conn.remote_port);
const struct shash_node *nc_node = shash_find(&ctx->names, address);
if (nc_node) {
const struct openrec_name_cache *nc = nc_node->data;
conn.remote_address = nc->address;
}
send_ping_once(&conn);
}
srv->send_t = time_msec();
}
static void
pong_run(struct udp_context *ctx)
{
int retval;
u_int8_t buf[1024];
struct sockaddr_in from;
struct udp_server *srv = ctx->srv;
struct udp_message *data = (struct udp_message *)buf;
retval = recv_ping_once(srv, &from, buf, sizeof buf);
if (retval <= 0) {
return;
}
const char *remote_addr = inet_ntoa(from.sin_addr);
char *spi_conn = xasprintf("spi:%d", ntohl(data->spi));
struct shash_node *node = shash_find(&ctx->links, spi_conn);
VLOG_DBG("pong_run from: %s:%d and spi %d\n", remote_addr, ntohs(from.sin_port), ntohl(data->spi));
if (node) {
struct openrec_virtual_link *vl = node->data;
VLOG_DBG("pong_run virtual link: %s %s\n", vl->connection, vl->network);
struct sockaddr_in dst_addr = from;
u_int32_t seqno = ntohl(data->seqno) + 1;
data->seqno = htonl(seqno);
retval = sendto(srv->socket, data, sizeof *data, 0, (struct sockaddr *)&dst_addr, sizeof dst_addr);
if (retval <= 0) {
VLOG_WARN_RL(&rl, "%s: could not send data\n", remote_addr);
}
// remote_connection=udp:a.b.c.d:1024
char *connection = xasprintf("udp:%s:%d", remote_addr, ntohs(from.sin_port));
openrec_virtual_link_update_status_setkey(vl, "remote_connection", connection);
free(connection);
}
free(spi_conn);
}
static void
ping_wait(struct udp_context *ctx)
{
poll_timer_wait_until(time_msec() + 5 * 1000);
}
static void
pong_wait(struct udp_context *ctx)
{
struct udp_server *srv = ctx->srv;
poll_fd_wait(srv->socket, POLLIN);
}
int
main(int argc, char *argv[])
{
struct unixctl_server *unixctl;
bool exiting = false;
int retval = 0;
char *unixdir;
ovs_cmdl_proctitle_init(argc, argv);
ovs_set_program_name(argv[0], CORE_PACKAGE_VERSION);
service_start(&argc, &argv);
parse_options(argc, argv);
unixdir = unixctl_dir();
/* Open and register unixctl */
retval = unixctl_server_create(unixdir, &unixctl);
if (retval) {
goto RET;
}
unixctl_command_register("exit", "", 0, 0, udp_exit, &exiting);
/* Connect to OpenLAN database. */
struct ovsdb_idl_loop open_idl_loop = OVSDB_IDL_LOOP_INITIALIZER(
ovsdb_idl_create(db_remote, &openrec_idl_class, true, true));
ovsdb_idl_get_initial_snapshot(open_idl_loop.idl);
struct udp_server srv = {
.port = udp_port,
.socket = -1,
.send_t = time_msec(),
};
open_socket(&srv);
if (configure_socket(&srv) < 0) {
VLOG_ERR("configure_socket: %s\n", strerror(errno));
goto RET;
}
struct udp_context ctx = {
.idl = open_idl_loop.idl,
.srv = &srv,
};
shash_init(&ctx.names);
shash_init(&ctx.networks);
shash_init(&ctx.links);
while(!exiting) {
ctx.idl_txn = ovsdb_idl_loop_run(&open_idl_loop);
if (ctx.idl_txn) {
cache_run(&ctx);
}
ping_run(&ctx);
pong_run(&ctx);
ping_wait(&ctx);
pong_wait(&ctx);
unixctl_server_run(unixctl);
unixctl_server_wait(unixctl);
if (exiting) {
poll_immediate_wake();
}
ovsdb_idl_loop_commit_and_wait(&open_idl_loop);
poll_block();
if (should_service_stop()) {
exiting = true;
}
}
shash_destroy(&ctx.names);
shash_destroy(&ctx.networks);
shash_destroy(&ctx.links);
unixctl_server_destroy(unixctl);
ovsdb_idl_loop_destroy(&open_idl_loop);
service_stop();
RET:
if (db_remote) free(db_remote);
if (default_db_) free(default_db_);
if (unixdir) free(unixdir);
exit(retval);
}

143
core/udp/udp.c Executable file
View File

@@ -0,0 +1,143 @@
/*
* Copyright (c) 2021-2022 OpenLAN Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
*/
#include <errno.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <linux/udp.h>
#include <linux/xfrm.h>
#include <linux/ipsec.h>
#include <linux/pfkeyv2.h>
#include <arpa/inet.h>
#include "openvswitch/dynamic-string.h"
#include "openvswitch/vlog.h"
#include "socket-util.h"
#include "udp.h"
VLOG_DEFINE_THIS_MODULE(udp);
/* Rate limit for error messages. */
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
void
print_hex(const char *prefix, u_int8_t *data, int len)
{
if (VLOG_IS_DBG_ENABLED()) {
struct ds s;
ds_init(&s);
for (int i = 0; i < len; i++ ) {
ds_put_format(&s, "%02x ", data[i]);
}
VLOG_DBG("%s%s\n", prefix, ds_cstr(&s));
ds_destroy(&s);
}
}
int
send_ping_once(struct udp_connect *conn)
{
int retval = 0;
struct udp_message data = {
.padding = {0, 0},
.spi = htonl(conn->spi),
};
data.seqno = htonl(conn->seqno++);
struct sockaddr_in dst_addr = {
.sin_family = AF_INET,
.sin_port = htons(conn->remote_port),
.sin_addr = {
.s_addr = inet_addr(conn->remote_address),
},
};
retval = sendto(conn->socket, &data, sizeof data, 0, (struct sockaddr *)&dst_addr, sizeof dst_addr);
if (retval <= 0) {
VLOG_WARN_RL(&rl, "%s: could not send data\n", conn->remote_address);
}
return retval;
}
int
recv_ping_once(struct udp_server *srv, struct sockaddr_in *addr, u_int8_t *buf, size_t len)
{
struct udp_message *data = (struct udp_message *)buf;
int retval = 0, addrlen = sizeof *addr;
memset(data, 0, sizeof *data);
retval = recvfrom(srv->socket, buf, len, 0, (struct sockaddr *)addr, &addrlen);
if ( retval <= 0 ) {
if (errno == EAGAIN) {
return 0;
}
VLOG_ERR_RL(&rl, "recvfrom: %s\n", strerror(errno));
return retval;
}
const char *remote_addr = inet_ntoa(addr->sin_addr);
VLOG_DBG("recvfrom: [%s:%d] %d bytes\n", remote_addr, ntohs(addr->sin_port), retval);
print_hex("recvfrom: ", buf, retval);
return retval;
}
int
open_socket(struct udp_server *srv)
{
int op = 1;
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_port = htons(srv->port),
.sin_addr = {
.s_addr = INADDR_ANY,
},
};
srv->socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (srv->socket == -1) {
return -1;
}
if (setsockopt(srv->socket, SOL_SOCKET, SO_REUSEADDR, (void *)&op, sizeof op) < 0) {
return -1;
}
if (bind(srv->socket, (struct sockaddr *)&addr, sizeof addr) == -1) {
return -1;
}
set_nonblocking(srv->socket);
return srv->socket;
}
int
configure_socket(struct udp_server *srv)
{
int encap = UDP_ENCAP_ESPINUDP;
struct xfrm_userpolicy_info pol;
memset(&pol, 0, sizeof(pol));
pol.action = XFRM_POLICY_ALLOW;
pol.sel.family = AF_INET;
pol.dir = XFRM_POLICY_OUT;
if (setsockopt(srv->socket, IPPROTO_IP, IP_XFRM_POLICY, &pol, sizeof pol) < 0) {
return -1;
}
pol.dir = XFRM_POLICY_IN;
if (setsockopt(srv->socket, IPPROTO_IP, IP_XFRM_POLICY, &pol, sizeof pol) < 0) {
return -1;
}
if (setsockopt(srv->socket, IPPROTO_UDP, UDP_ENCAP, &encap, sizeof encap) < 0) {
return -1;
}
return srv->socket;
}

40
core/udp/udp.h Executable file
View File

@@ -0,0 +1,40 @@
#ifndef __OPENUDP_UDP_H
#define __OPENUDP_UDP_H 1
#include <netinet/in.h>
#include "openvswitch/shash.h"
struct udp_message {
u_int32_t padding[2];
u_int32_t spi;
u_int32_t seqno;
};
struct udp_server {
u_int16_t port;
int32_t socket;
long long int send_t;
};
struct udp_connect {
int32_t socket;
int32_t remote_port;
const char *remote_address;
u_int32_t spi;
u_int32_t seqno;
};
int send_ping_once(struct udp_connect *);
int recv_ping_once(struct udp_server *, struct sockaddr_in *, u_int8_t *, size_t);
int open_socket(struct udp_server *);
int configure_socket(struct udp_server *);
static inline void shash_empty(struct shash *sh)
{
shash_destroy(sh);
shash_init(sh);
}
#endif

20
core/version.h Normal file
View File

@@ -0,0 +1,20 @@
/*
* Copyright (c) 2021-2022 OpenLAN Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
*/
#ifndef OPENUDP_VERSION_H
#define OPENUDP_VERSION_H 1
#define CORE_PACKAGE_STRING "opencore 5.10.4"
#define CORE_PACKAGE_VERSION "5.10.4"
#define CORE_LIB_VERSION 0
#define CORE_LIB_REVISION 0
#define CORE_LIB_AGE 0
#endif /* version.h */

21
dist/openlan-switch.docker vendored Executable file
View File

@@ -0,0 +1,21 @@
FROM centos:7
ARG VERSION
WORKDIR /root
ADD build/openlan-switch-${VERSION}-1.el7.x86_64.rpm /tmp
RUN yum install -y epel-release \
&& yum install -y iptables bridge-utils \
&& yum install -y /tmp/openlan-switch-${VERSION}-1.el7.x86_64.rpm
LABEL application="OpenLAN Switch Application"
LABEL maintainer="luscis@163.com"
EXPOSE 10000/tcp
EXPOSE 10002/tcp
EXPOSE 10002/udp
CMD ["/usr/bin/openlan-switch", "-conf:dir", "/etc/openlan/switch", "-log:level", "20"]

70
dist/openlan.spec.in vendored Executable file
View File

@@ -0,0 +1,70 @@
Name: openlan
Version: @VERSION@
Release: 1%{?dist}
Source: %{name}-%{version}-source.tar.gz
Summary: OpenLAN's Project Software
Group: Applications/Communications
License: GPL-3.0
URL: https://github.com/luscis/openlan
BuildRequires: unbound-devel openssl-devel libcap-ng-devel
Requires: net-tools, iptables, iputils, openvpn, openssl, openvswitch, dnsmasq
# binary no-debug by go build
%define __debug_install_post \
%{_rpmconfigdir}/find-debuginfo.sh %{?_find_debuginfo_opts} "%{_builddir}/%{?buildsubdir}"\
%{nil}
%description
OpenLAN's Project Software
%prep
%setup -q
%build
make clean
make linux
%install
make install LINUX_DIR=%{buildroot}
%pre
%post
[ -e "/etc/openlan/switch/switch.json" ] || {
/usr/bin/cp -rvf /etc/openlan/switch/switch.json.example /etc/openlan/switch/switch.json
}
[ -e "/var/openlan/openvpn/dh.pem" ] || {
/usr/bin/openssl dhparam -out /var/openlan/openvpn/dh.pem 2048
}
[ -e "/var/openlan/openvpn/ta.key" ] || {
/usr/sbin/openvpn --genkey --secret /var/openlan/openvpn/ta.key
}
[ -e "/etc/openlan/switch/confd.db" ] || {
/usr/bin/ovsdb-tool create /etc/openlan/switch/confd.db /etc/openlan/switch/confd.schema.json
}
[ -e "/var/openlan/confd.sock" ] && {
/usr/bin/ovsdb-client convert unix:///var/openlan/confd.sock /etc/openlan/switch/confd.schema.json
}
[ -e "/etc/sysctl.d/90-openlan.conf" ] && {
/usr/sbin/sysctl -p /etc/sysctl.d/90-openlan.conf || :
}
[ -e "/etc/openlan/switch/network/ipsec.json" ] || {
/usr/bin/cat > /etc/openlan/switch/network/ipsec.json <<EOF
{
"name": "ipsec",
"provider": "esp"
}
EOF
}
%files
%defattr(-,root,root)
/etc/sysconfig/*
/etc/openlan/*
/etc/sysctl.d/*
/usr/bin/*
/usr/lib/systemd/system/*
/var/openlan/*
%clean
rm -rf %_env

13
dist/resource/90-openlan.conf vendored Executable file
View File

@@ -0,0 +1,13 @@
## This file Generated by OpenLAN,
## and allowed ip_forward and disabled bridged netfilter.
net.ipv4.ip_forward = 1
## modprobe br_netfilter
#net.bridge.bridge-nf-call-ip6tables = 0
#net.bridge.bridge-nf-call-iptables = 0
#net.bridge.bridge-nf-call-arptables = 0
## enable multipath and check neigh status
#net.ipv4.fib_multipath_hash_policy = 1
#net.ipv4.fib_multipath_use_neigh = 1

21
dist/resource/acl-1.json.example vendored Executable file
View File

@@ -0,0 +1,21 @@
{
"name": "acl-1",
"rules": [
{
"dst": "192.168.77.121",
"proto": "tcp",
"dport": 443,
"action": "drop"
},
{
"dst": "192.168.10.0/24",
"action": "drop"
},
{
"src": "192.168.100.0/24",
"proto": "udp",
"sport": 68,
"action": "drop"
}
]
}

1
dist/resource/cert vendored Submodule

Submodule dist/resource/cert added at b92121a0bf

244
dist/resource/confd.schema.json vendored Executable file
View File

@@ -0,0 +1,244 @@
{
"name": "OpenLAN_Switch",
"version": "22.02.13",
"tables": {
"Global_Switch": {
"columns": {
"protocol": {
"type": "string"
},
"listen": {
"type": {
"key": {
"type": "integer",
"minInteger": 1024,
"maxInteger": 65535
}
}
},
"other_config": {
"type": {
"key": "string",
"value": "string",
"min": 0,
"max": "unlimited"
}
},
"virtual_networks": {
"type": {
"key": {
"type": "uuid",
"refTable": "Virtual_Network"
},
"min": 0,
"max": "unlimited"
}
}
},
"isRoot": true,
"maxRows": 1
},
"Virtual_Network": {
"columns": {
"name": {
"type": "string",
"mutable": false
},
"other_config": {
"type": {
"key": "string",
"value": "string",
"min": 0,
"max": "unlimited"
}
},
"provider": {
"type": "string"
},
"bridge": {
"type": "string"
},
"address": {
"type": "string"
},
"remote_links": {
"type": {
"key": {
"type": "uuid",
"refTable": "Virtual_Link"
},
"min": 0,
"max": "unlimited"
},
"ephemeral": true
},
"local_links": {
"type": {
"key": {
"type": "uuid",
"refTable": "Virtual_Link"
},
"min": 0,
"max": "unlimited"
}
},
"prefix_routes": {
"type": {
"key": {
"type": "uuid",
"refTable": "Prefix_Route"
},
"min": 0,
"max": "unlimited"
}
},
"open_vpn": {
"type": {
"key": {
"type": "uuid",
"refTable": "Open_VPN"
},
"min": 0,
"max": 1
}
}
},
"indexes": [
["name"]
]
},
"Virtual_Link": {
"columns": {
"network": {
"type": "string",
"mutable": false
},
"connection": {
"type": "string"
},
"link_state": {
"type": "string",
"ephemeral": true
},
"device": {
"type": "string"
},
"authentication": {
"type": {
"key": "string",
"value": "string",
"min": 0,
"max": "unlimited"
}
},
"other_config": {
"type": {
"key": "string",
"value": "string",
"min": 0,
"max": "unlimited"
}
},
"status": {
"type": {
"key": "string",
"value": "string",
"min": 0,
"max": "unlimited"
},
"ephemeral": true
},
"statistics": {
"type": {
"key": "string",
"value": "integer",
"min": 0,
"max": "unlimited"
}
}
},
"indexes": [
["connection","device", "network"]
]
},
"Prefix_Route": {
"columns": {
"network": {
"type": "string",
"mutable": false
},
"prefix": {
"type": "string",
"mutable": false
},
"source": {
"type": "string"
},
"gateway": {
"type": "string"
},
"mode": {
"type": "string"
}
},
"indexes": [
["prefix", "network"]
]
},
"Open_VPN": {
"columns": {
"protocol": {
"type": "string"
},
"listen": {
"type": {
"key": {
"type": "integer",
"minInteger": 1024,
"maxInteger": 65535
}
}
},
"subnet": {
"type": "string"
},
"push": {
"type": {
"key": "string",
"value": "string",
"min": 0,
"max": "unlimited"
}
},
"clients": {
"type": {
"key": "string",
"value": "string",
"min": 0,
"max": "unlimited"
}
}
},
"indexes": [
["protocol", "listen"]
]
},
"Name_Cache": {
"columns": {
"name": {
"type": "string"
},
"address": {
"type": "string"
},
"update_at": {
"type": "string"
}
},
"indexes": [
["name"]
],
"isRoot": true
}
}
}

23
dist/resource/default.json.example vendored Executable file
View File

@@ -0,0 +1,23 @@
{
"name": "default",
"provider": "openlan",
"bridge": {
"address": "172.32.99.40/24"
},
"subnet": {
"start": "172.32.99.250",
"end": "172.32.99.254",
"netmask": "255.255.255.0"
},
"routes": [
{
"prefix": "172.32.10.0/24"
}
],
"openvpn": {
"protocol": "tcp",
"listen": "0.0.0.0:3294",
"subnet": "172.32.194.0/24"
},
"acl": "acl-99"
}

BIN
dist/resource/donation.jpg vendored Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

58
dist/resource/example.ovpn vendored Executable file
View File

@@ -0,0 +1,58 @@
client
dev tun
proto tcp
remote 192.168.77.30 1194
resolv-retry infinite
nobind
persist-key
persist-tun
<ca>
-----BEGIN CERTIFICATE-----
MIIDGDCCAgCgAwIBAgIJAJPUuCImsVp3MA0GCSqGSIb3DQEBCwUAMA0xCzAJBgNV
BAMMAm5qMB4XDTIwfcTAwNjE4MDgyNloXDTMwMTAwNDE4MDgyNlowDTELMAkGA1UE
AwwCbmowggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDL4vdtg5m0XeEa
99f8bUO4TmuouhQ5+jr2kDxN4adDGHTANqOpV9yTsHE3NfrcOlecm3MCk1b05g3p
6nzu4iF4de/c6avy0Vpq8w8XnfUYS1lCIb9R9q8heN5P3Awn3Tszctw+QMBgH0Hb
TrYYOm6QIir0XOyB82traZxZyVL6XObVy993wbRpyVF4YDFzbSx/08au7+7tNf4l
DZRTCPHx0lYYKgzAwdM9yD95D/mpbfsE5TxArzADNTEBUSvoUU3q7ulEaSE0yKgP
iu5c8UIHbBFDAy98e+kqgqLd8ljOuMNEezZsLm1mxrFFQBQ/Efw3LqzAjR/D5fJw
qr6cRZPFAgMBAAGjezB5MB0GA1UdDgQWBBQqkJzxLx4q0nA/MaT+2YJef5CFBzA9
BgNVHSMENjA0gBQqkJzxLx4q0nA/MaT+2YJef5CFB6ERpA8wDTELMAkGA1UEAwwC
bmqCCQCT1LgiJrFadzAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG
9w0BAQsFAAOCAQEAqGY0Z2cQmtUWNhTWQQ0Lq4hSq0zpRqXBwF1jy8j/aLAzdw9M
V/3/N5UvbyNyUz6sRmFc9E+qY+8ze7cby5O8eydOXoht8UX/agh3IroEghy+JA5d
QSkZkk5DAxUQamXVRYKCySJwzbmHSx5wzb9Dh8VXU5ILippdTMBHvrpr86+NDF2m
VsusYb+S1h2GgfvwxqDMwiqz06sy0Jm+mTqJn5Ssf9rdmD7lJiE8953LmEUtdepe
aPL9aLDbePx+6UQEchotYYnV4f7cuR6l9gChshih/EE9eorU/itgY4+ZgOuT60BB
am0CqJZqZF4SdWuuz2wzVsQWsITIB3JCDhR0rQ==
-----END CERTIFICATE-----
</ca>
ns-cert-type server
<tls-auth>
#
# 2048 bit OpenVPN static key
#
-----BEGIN OpenVPN Static key V1-----
164ee33c50503cea99000524dccdb7f055
dc15bad47ebfe29beaf0988ba87da88522
4b10f6a458d6e8e7d4f6bd7532686ed2
827e086c3dc89f87483a078f7918c71f1
bae2f8fe4f94e966a772129cb1d8114c
fd1aa1754ef590fbf5e0c88c433eec82
d99d74b25c8595f515554946e045e3b7
d79ee8b0042c27994ee9f342d56668bb
33be2f1bfca0809e50b9acfae9532b24
2337781ac187dc691ea5606c6e3b1a58
ed2dd0fbcc0ac513ecad1aa7890065e0
297494854df9da1d931b0eab4b935987
38202c9ea8b8f9b769ad4357e2bab881
706fae5bcbc64737973f168f556b6bfb
726ef63b7c38c82e0baf089106743891
70656a96ba2dd6d594aa7bef00e582df
-----END OpenVPN Static key V1-----
</tls-auth>
key-direction 1
cipher AES-256-CBC
auth-nocache
verb 4
auth-user-pass

62
dist/resource/fabric.json.example vendored Executable file
View File

@@ -0,0 +1,62 @@
{
"name": "fabric",
"provider": "fabric",
"bridge": {
"name": "br-tun"
},
"specifies": {
"tcpMss": 1332,
"tunnels": [
{
"remote": "100.64.0.20"
},
{
"remote": "100.64.0.21"
},
{
"remote": "100.64.0.33"
}
],
"networks": [
{
"vni": 2077,
"outputs": [
{
"interface": "vxlan:10.10.1.7:3303"
},
{
"vlan": 60,
"interface": "gre:10.10.1.8"
}
]
},
{
"vni": 2088,
"outputs": [
{
"vlan": 99,
"interface": "gre:10.10.1.10"
}
]
},
{
"vni": 2099,
"bridge": {
"address": "172.16.100.1/24"
}
"outputs": [
{
"vlan": 100,
"interface": "eth1"
}
],
"subnet": {
"start": "172.32.100.250",
"end": "172.32.100.254",
"dns": "8.8.8.8,8.8.4.4",
},
"dhcp": "enable"
}
]
}
}

41
dist/resource/ipsec.json.example vendored Executable file
View File

@@ -0,0 +1,41 @@
{
"name": "ipsec",
"provider": "esp",
"specifies": {
"address": "100.64.0.10",
"members": [
{
"spi": 300,
"peer": "100.64.0.30",
"state": {
"auth": "a263d01a96db11eb9",
"crypt": "9b73bc48e3864b3ebc"
}
},
{
"spi": 100,
"peer": "100.64.0.20",
"state": {
"remote": "2.16.1.2"
}
},
{
"spi": 200,
"address": "100.64.0.11",
"peer": "100.64.0.30",
"state": {
"local": "192.168.1.10",
"remote": "2.16.1.2",
"auth": "a263d01a96db11eb9",
"crypt": "9b73bc48e3864b3ebc"
},
"policy": [
{
"source": "192.168.1.0/24",
"destination": "192.168.2.0/24"
}
]
}
]
}
}

55
dist/resource/network.json.example vendored Executable file
View File

@@ -0,0 +1,55 @@
{
"name": "example",
"bridge": {
"name": "br-eth0",
"address": "172.32.100.40/24"
},
"subnet": {
"start": "172.32.100.250",
"end": "172.32.100.254",
"netmask": "255.255.255.0",
"dns": "8.8.8.8,8.8.4.4",
},
"hosts": [
{
"hostname": "pc-99",
"address": "172.32.100.99"
}
],
"routes": [
{
"prefix": "172.32.10.0/24"
}
],
"password": [
{
"username": "hi",
"password": "1f4ee82b5eb6"
}
],
"links": [
{
"protocol": "tls",
"connection": "hi.openlan.net",
"username": "hi",
"password": "1f4ee82b5eb6"
}
],
"openvpn": {
"protocol": "tcp",
"listen": "0.0.0.0:3295",
"subnet": "172.32.195.0/24",
"push": [
"dhcp-option DNS 8.8.8.8"
],
"clients": [
{
"name": "hi",
"address": "172.32.195.233",
"netmask": "172.32.195.234"
}
]
},
"acl": "acl-100",
"dhcp": "enable",
}

16
dist/resource/openlan-confd.service vendored Executable file
View File

@@ -0,0 +1,16 @@
[Unit]
Description=OpenLAN Switch Database Unit
After=syslog.target network-pre.target
Before=network.target network.service
[Service]
Type=forking
PIDFile=/var/openlan/confd.pid
Restart=on-failure
EnvironmentFile=-/etc/sysconfig/openlan/confd
ExecStart=/var/openlan/script/confd start
ExecStop=/var/openlan/script/confd stop
[Install]
WantedBy=multi-user.target

12
dist/resource/openlan-point@.service vendored Executable file
View File

@@ -0,0 +1,12 @@
[Unit]
Description=OpenLAN Point daemon for %I
After=network.target
[Service]
Type=notify
EnvironmentFile=/etc/sysconfig/openlan/point.cfg
ExecStart=/usr/bin/openlan-point $OPTIONS -conf /etc/openlan/%i.json
Restart=always
[Install]
WantedBy=multi-user.target

13
dist/resource/openlan-proxy.service vendored Executable file
View File

@@ -0,0 +1,13 @@
[Unit]
Description=OpenLAN Proxy daemon
After=network.target
[Service]
Type=notify
EnvironmentFile=/etc/sysconfig/openlan/proxy.cfg
ExecStart=/usr/bin/openlan-proxy $OPTIONS
LimitNOFILE=102400
Restart=always
[Install]
WantedBy=multi-user.target

15
dist/resource/openlan-switch.service vendored Executable file
View File

@@ -0,0 +1,15 @@
[Unit]
Description=OpenLAN Virtual Switch daemon
After=network.target openlan-confd.service
Requires=openlan-confd.service
[Service]
Type=notify
EnvironmentFile=/etc/sysconfig/openlan/switch.cfg
ExecStartPre=-/var/openlan/script/setup.sh
ExecStart=/usr/bin/openlan-switch $OPTIONS
LimitNOFILE=102400
Restart=always
[Install]
WantedBy=multi-user.target

41
dist/resource/openssl vendored Executable file
View File

@@ -0,0 +1,41 @@
#!/bin/bash
action=$1
if [ "$action" == "" ]; then
echo "$0 <cert|ca|sign|show>"
exit 0
fi
[ -e "ca" ] || mkdir ca
[ -e "cert" ] || mkdir cert
if [ "$action" == "cert" ]; then
source cert.vars
[ -e "cert/key" ] || openssl genrsa -out cert/key 2048
# openssl rsa -in key -noout -text
[ -e "cert/key.pub" ] || openssl rsa -in cert/key -pubout -out cert/key.pub
# openssl rsa -pubin -in key.pub -noout -text
# using private to sign pem and generate a csr request.
[ -e "cert/crt.csr" ] || openssl req -new -key cert/key -out cert/crt.csr -subj "/C=$C/ST=$ST/L=$NJ/O=$O/OU=$OU/CN=$CN/emailAddress=$emailAddress"
fi
if [ "$action" == "ca" ]; then #### CA &x509
source ca.vars
[ -e "ca/ca.key" ] || openssl genrsa -out ca/ca.key 2048
[ -e "ca/ca.crt" ] || openssl req -new -x509 -days 3650 -key ca/ca.key -out ca/ca.crt -subj "/C=$C/ST=$ST/L=$L/O=$O/OU=$OU/CN=$CN/emailAddress=$emailAddress"
fi
if [ "$action" == "sign" ]; then
#### Sign cert using myself ca
[ -e "cert/crt" ] || openssl x509 -req -days 730 -in cert/crt.csr -CA ./ca/ca.crt -CAkey ./ca/ca.key -CAcreateserial -out cert/crt -sha256 -extfile cert.ext
fi
if [ "$action" == "show" ]; then
echo "### ca.crt"
openssl x509 -in ca/ca.crt -noout -text
echo "### crt.csr"
openssl req -noout -text -in cert/crt.csr
echo "### crt"
openssl x509 -in cert/crt -noout -text
fi

30
dist/resource/openvpn.md vendored Executable file
View File

@@ -0,0 +1,30 @@
# OpenVPN
yum install -y epel-release
yum install -y openvpn
## Generate Diffie-Hellman
openssl dhparam -out /var/openlan/openvpn/dh.pem 1024
## Generate TLS Auth Key
openvpn --genkey --secret /var/openlan/openvpn/ta.key
# Configure OpenVPN in Network
{
"name": "example",
"openvpn": {
"listen": "0.0.0.0:1194",
"subnet": "10.9.9.0/24"
}
}
## Restart OpenLAN Switch Service
systemctl reload openlan-switch

2
dist/resource/password.example vendored Executable file
View File

@@ -0,0 +1,2 @@
hi@example:efb19651
hei@guest:abef6f1e

4
dist/resource/point.cfg vendored Executable file
View File

@@ -0,0 +1,4 @@
# --- point.cfg ---
# This file define the configuration for OpenLAN Point.
OPTIONS='-log:file /dev/null -terminal off -cacert /etc/openlan/ca-trusted.crt'

7
dist/resource/point.json.example vendored Executable file
View File

@@ -0,0 +1,7 @@
{
"protocol": "tls",
"connection": "who.openlan.net",
"username": "hi@default",
"password": "cb2ff088a34d",
"cert": { "insecure": true }
}

19
dist/resource/point.json.full.example vendored Executable file
View File

@@ -0,0 +1,19 @@
{
"network": "default",
"interface": {
"name": "tap0",
"bridge": "br-default",
"address": "172.32.100.10/24"
},
"connection": "who.openlan.net",
"username": "hi",
"password": "1f4ee82b5eb6",
"protocol": "tls",
"cert": {
"insecure": true
},
"crypt": {
"algo": "aes-256",
"secret": "1f4ee82b5eb6"
}
}

4
dist/resource/proxy.cfg vendored Executable file
View File

@@ -0,0 +1,4 @@
# --- point.cfg ---
# This file define the configuration for OpenLAN Proxy.
OPTIONS='-log:file /dev/null -conf /etc/openlan/proxy.json'

42
dist/resource/proxy.json.example vendored Executable file
View File

@@ -0,0 +1,42 @@
{
"socks": [
{
"listen": "0.0.0.0:11080"
}
],
"shadow": [
{
"server": ":8488",
"password": "ecd0820973c9",
"cipher": "AEAD_CHACHA20_POLY1305"
}
],
"http": [
{
"listen": "0.0.0.0:11082",
"auth": {
"username": "hi",
"password": "cb2ff088a34d"
}
},
{
"listen": "0.0.0.0:11083",
"auth": {
"username": "hi",
"password": "cb2ff088a34d"
},
"cert": {
"dir": "/var/openlan/cert"
}
}
],
"tcp": [
{
"listen": "0.0.0.0:80",
"target": [
"192.168.100.80:80",
"192.168.100.81:80"
]
}
]
}

5
dist/resource/switch.cfg vendored Executable file
View File

@@ -0,0 +1,5 @@
# --- switch.cfg ---
# This file define the configuration for OpenLAN Switch.
# ESPUDP="4600"
OPTIONS='-log:file /dev/null -conf:dir /etc/openlan/switch'

11
dist/resource/switch.json.example vendored Executable file
View File

@@ -0,0 +1,11 @@
{
"cert": {
"dir": "/var/openlan/cert"
},
"http": {
"public": "/var/openlan/public"
},
"crypt": {
"secret": "cb2ff088a34d"
}
}

37
dist/resource/switch.json.full.example vendored Executable file
View File

@@ -0,0 +1,37 @@
{
"protocol": "tls",
"cert": {
"dir": "/var/openlan/cert"
},
"http": {
"public": "/var/openlan/public"
},
"crypt": {
"algo": "aes-128",
"secret": "cb2ff088a34d"
},
"inspect": [
"neighbor",
"online"
],
"firewall": [
{
"table": "nat",
"chain": "PREROUTING",
"protocol": "tcp",
"match": "tcp",
"destination": "0.0.0.0/0",
"dport": 80,
"jump": "DNAT",
"to-destination": "100.44.85.6:80"
}
],
"ldap": {
"server": "ldap-server.net:389",
"bindDN": "cn=admin,dc=openlan,dc=com",
"password": "your-passowrd",
"baseDN": "dc=openlan,dc=com",
"attribute": "cn",
"filter": "(cn=%s)"
}
}

26
dist/resource/v1024.json.example vendored Normal file
View File

@@ -0,0 +1,26 @@
{
"name": "v1024",
"provider": "vxlan",
"specifies": {
"vni": 1024,
"fabric": "fabric"
},
"bridge": {
"address": "192.168.55.1/24"
},
"subnet": {
"start": "192.168.55.100",
"end": "192.168.55.130"
},
"dhcp": "enable",
"outputs": [
{
"vlan": 100,
"interface": "vxlan:3.3.3.5:43"
},
{
"vlan": 0,
"interface": "gre:3.3.3.3"
}
]
}

67
dist/script/bridge vendored Executable file
View File

@@ -0,0 +1,67 @@
#!/bin/bash
## Load configuration.
cfg="eth0.cfg"
if [ $# -ge 1 ]; then
cfg="$1"
shift
fi
if [ -e "$cfg" ]; then
. $cfg
fi
## Check enviroment.
if [ -z "$PHY" ] || [ -z "$ADDR" ] || [ -z "$PREFIX" ]; then
echo "Variable(PHY|ADDR|PREFIX) is NULL"
exit
fi
yum install bridge-utils -y
## Set variable
phy="$PHY"
addr="$ADDR"
prefix="$PREFIX"
br=br-"$PHY"
gw="$GATEWAY"
dns1="$DNS1"
## Configure script
brCfg=/etc/sysconfig/network-scripts/ifcfg-"$br"
phyCfg=/etc/sysconfig/network-scripts/ifcfg-"$phy"
## Generate bridge configure
echo "## Generate by OpenLAN project" > $brCfg
echo "STP=\"yes\"" >> $brCfg
echo "DELAY=\"2\"" >> $brCfg
echo "TYPE=\"Bridge\"" >> $brCfg
echo "NAME=\"$br\"" >> $brCfg
echo "DEVICE=\"$br\"" >> $brCfg
echo "BOOTPROTO=\"none\"" >> $brCfg
if [ -n "$addr" ]; then
echo "IPADDR=\"$addr\"" >> $brCfg
fi
if [ -n "$prefix" ]; then
echo "PREFIX=\"$prefix\"" >> $brCfg
fi
if [ -n "$gw" ]; then
echo "GATEWAY=\"$gw\"" >> $brCfg
fi
if [ -n "$dns1" ]; then
echo "DNS1=\"$dns1\"" >> $brCfg
fi
echo "ONBOOT=\"yes\"" >> $brCfg
echo "NM_CONTROLLED=\"no\"" >> $brCfg
## Generate physical configure
echo "## Generate by OpenLAN project" > $phyCfg
echo "TYPE=\"Ethernet\"" >> $phyCfg
echo "NAME=\"$phy\"" >> $phyCfg
echo "DEVICE=\"$phy\"" >> $phyCfg
echo "BOOTPROTO=\"none\"" >> $phyCfg
echo "ONBOOT=\"yes\"" >> $phyCfg
echo "NM_CONTROLLED=\"no\"" >> $phyCfg
echo "BRIDGE=\"$br\"" >> $phyCfg
echo "BRIDGING_OPTS=\"path_cost=4\"" >> $phyCfg # 4: 1G, 2: 10G, 19: 100Mb and 100: 1Mb.
ifdown "$br"; ifdown "$phy"; ifup "$br"; ifup "$phy";

42
dist/script/confd vendored Executable file
View File

@@ -0,0 +1,42 @@
#!/bin/bash
set -e
command=$1
OVSDB_SERVER_BIN="/usr/bin/env ovsdb-server"
[ "$OVSDB_DATABASE" == "" ] && OVSDB_DATABASE="/etc/openlan/switch/confd.db"
[ "$OVSDB_LOG_FILE" == "" ] && OVSDB_LOG_FILE="/var/openlan/confd.log"
[ "$OVSDB_SOCK" == "" ] && OVSDB_SOCK="/var/openlan/confd.sock"
[ "$OVSDB_PID_FILE" == "" ] && OVSDB_PID_FILE="/var/openlan/confd.pid"
function stop() {
[ -e "$OVSDB_PID_FILE" ] && kill "$(cat $OVSDB_PID_FILE)"
}
function start() {
set $OVSDB_SERVER_BIN $OVSDB_DATABASE
set "$@" -vconsole:emer -vsyslog:err -vfile:info
set "$@" --remote=punix:"$OVSDB_SOCK"
set "$@" --log-file="$OVSDB_LOG_FILE"
set "$@" --pidfile="$OVSDB_PID_FILE"
[ "$OVSDB_OPTIONS" != "" ] && set "$@" $OVSDB_OPTIONS
set "$@" --detach
OVS_RUNDIR="/var/openlan" "$@"
}
case $command in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
*)
echo >&2 "$0: unknown command \"$command\" (start/stop/restart)"
exit 1
;;
esac

5
dist/script/eth0.cfg vendored Executable file
View File

@@ -0,0 +1,5 @@
PHY="eth0"
ADDR="192.168.2.2"
PREFIX="24"
GATEWAY=""
DNS1=""

9
dist/script/ifcfg-veth0 vendored Normal file
View File

@@ -0,0 +1,9 @@
DEVICE="veth0"
TYPE="veth"
DEVICETYPE="Ethernet"
BOOTPROTO="static"
IPADDR="192.168.3.4"
NETMASK="255.255.255.0"
ONBOOT="no"
NM_CONTROLLED="no"
VETH_PARENT="br0"

60
dist/script/ifdown-veth vendored Executable file
View File

@@ -0,0 +1,60 @@
#!/bin/bash
#
# Derived from initscripts-macvlan
# Copyright (C) 2014 Lars Kellogg-Stedman
#
# Adopted for veth by Oleksandr Natalenko <o.natalenko@lanet.ua>
# Copyright (C) 2015 Lanet Network
#
# Based on Network Interface Configuration System
# Copyright (c) 1996-2009 Red Hat, Inc. all rights reserved.
#
# 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/>.
. /etc/init.d/functions
cd /etc/sysconfig/network-scripts
. ./network-functions
[ -f ../network ] && . ../network
CONFIG=${1}
need_config ${CONFIG}
source_config
OTHERSCRIPT="/etc/sysconfig/network-scripts/ifdown-${REAL_DEVICETYPE}"
if [ ! -x ${OTHERSCRIPT} ]; then
OTHERSCRIPT="/etc/sysconfig/network-scripts/ifdown-eth"
fi
${OTHERSCRIPT} ${CONFIG}
if [ -n "${VETH_PARENT}" ] && [ -x /usr/sbin/brctl ]; then
ip link set \
dev ${DEVICE}-bp down
brctl delif -- \
${VETH_PARENT} ${DEVICE}-bp
[ -r /var/run/radvd/radvd.pid ] && kill -HUP $(cat /var/run/radvd/radvd.pid)
if [ -d /sys/class/net/${VETH_PARENT}/brif ] && [ $(ls -1 /sys/class/net/${VETH_PARENT}/brif | wc -l) -eq 0 ]; then
ip link set \
dev ${VETH_PARENT} down
brctl delbr -- ${VETH_PARENT}
fi
fi
ip link del ${DEVICE}

78
dist/script/ifup-veth vendored Executable file
View File

@@ -0,0 +1,78 @@
#!/bin/bash
#
# Derived from initscripts-macvlan
# Copyright (C) 2014 Lars Kellogg-Stedman
#
# Adopted for veth by Oleksandr Natalenko <o.natalenko@lanet.ua>
# Copyright (C) 2015 Lanet Network
#
# Based on Network Interface Configuration System
# Copyright (c) 1996-2009 Red Hat, Inc. all rights reserved.
#
# 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/>.
. /etc/init.d/functions
cd /etc/sysconfig/network-scripts
. ./network-functions
[ -f ../network ] && . ../network
CONFIG=${1}
need_config ${CONFIG}
source_config
OTHERSCRIPT="/etc/sysconfig/network-scripts/ifup-${REAL_DEVICETYPE}"
if [ ! -x ${OTHERSCRIPT} ]; then
OTHERSCRIPT="/etc/sysconfig/network-scripts/ifup-eth"
fi
ip link add \
name ${DEVICE} \
type veth \
peer name ${DEVICE}-bp
if [ -n "${VETH_MAC}" ]; then
ip link set \
dev ${DEVICE} \
address ${VETH_MAC}
fi
if [ -n "${VETH_PARENT}" ] && [ -x /usr/sbin/brctl ]; then
if [ ! -d /sys/class/net/${VETH_PARENT}/bridge ]; then
brctl addbr -- \
${VETH_PARENT} 2>/dev/null
ip link set \
dev ${VETH_PARENT} up
fi
ip addr flush dev ${DEVICE}-bp 2>/dev/null
ip link set \
dev ${DEVICE}-bp up
ethtool_set
[ -n "${LINKDELAY}" ] && /bin/sleep ${LINKDELAY}
brctl addif -- \
${VETH_PARENT} ${DEVICE}-bp
for arg in $BRIDGING_OPTS ; do
key=${arg%%=*};
value=${arg##*=};
echo $value > /sys/class/net/${DEVICE}-bp/brport/$key
done
[ -r /var/run/radvd/radvd.pid ] && kill -HUP $(cat /var/run/radvd/radvd.pid)
fi
${OTHERSCRIPT} ${CONFIG}

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