Compare commits
21 Commits
20230104
...
f16176e927
| Author | SHA1 | Date | |
|---|---|---|---|
| f16176e927 | |||
| 0c5a8d56c9 | |||
| 7428512222 | |||
| 759a9b2dbf | |||
| 1ed23317cb | |||
| 9b55f1f29c | |||
| 5d26426074 | |||
| 39ff53f2ba | |||
| 96d264d15f | |||
| 6c23951d74 | |||
| 6ea8a927a3 | |||
| 4d0b4929c5 | |||
| d6c8964380 | |||
| ed25eed31e | |||
| 6fdcc8c07c | |||
| f82925dbcb | |||
| 71e22bc328 | |||
| e86b29c03a | |||
| 672e866897 | |||
| 80ecb3c5d2 | |||
| 134e27feb6 |
52
.drone.yml
Normal file
52
.drone.yml
Normal file
@@ -0,0 +1,52 @@
|
||||
---
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: default
|
||||
|
||||
steps:
|
||||
- name: web_build
|
||||
image: node:20
|
||||
volumes:
|
||||
- name: web_app
|
||||
path: /tmp/web_build
|
||||
commands:
|
||||
- cd virtweb_frontend
|
||||
- npm install
|
||||
- npm run build
|
||||
- mv dist /tmp/web_build
|
||||
|
||||
- name: backend_check
|
||||
image: rust
|
||||
volumes:
|
||||
- name: rust_registry
|
||||
path: /usr/local/cargo/registry
|
||||
commands:
|
||||
- apt update && apt install -y libvirt-dev
|
||||
- rustup component add clippy
|
||||
- cd virtweb_backend
|
||||
- cargo clippy -- -D warnings
|
||||
- cargo test
|
||||
|
||||
- name: backend_compile
|
||||
image: rust
|
||||
volumes:
|
||||
- name: rust_registry
|
||||
path: /usr/local/cargo/registry
|
||||
- name: web_app
|
||||
path: /tmp/web_build
|
||||
depends_on:
|
||||
- backend_check
|
||||
- web_build
|
||||
commands:
|
||||
- apt update && apt install -y libvirt-dev
|
||||
- cd virtweb_backend
|
||||
- mv /tmp/web_build/dist static
|
||||
- cargo build --release
|
||||
- ls -lah target/release/virtweb_backend
|
||||
|
||||
|
||||
volumes:
|
||||
- name: rust_registry
|
||||
temp: {}
|
||||
- name: web_app
|
||||
temp: {}
|
||||
674
LICENSE
Normal file
674
LICENSE
Normal file
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -1,5 +1,5 @@
|
||||
# VirtWEB
|
||||
WIP project
|
||||
Open Source Web interface for LibVirt. Simplify the management of VM.
|
||||
|
||||
## Setup for dev
|
||||
Please refer to this guide: [virtweb_docs/SETUP_DEV.md](virtweb_docs/SETUP_DEV.md)
|
||||
|
||||
9
renovate.json
Normal file
9
renovate.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"packageRules": [
|
||||
{
|
||||
"matchUpdateTypes": ["major", "minor", "patch"],
|
||||
"automerge": true
|
||||
}
|
||||
]
|
||||
}
|
||||
1338
virtweb_backend/Cargo.lock
generated
1338
virtweb_backend/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -6,41 +6,42 @@ edition = "2021"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
log = "0.4.19"
|
||||
env_logger = "0.10.1"
|
||||
clap = { version = "4.4.11", features = ["derive", "env"] }
|
||||
light-openid = { version = "1.0.1", features = ["crypto-wrapper"] }
|
||||
log = "0.4.21"
|
||||
env_logger = "0.11.3"
|
||||
clap = { version = "4.5.4", features = ["derive", "env"] }
|
||||
light-openid = { version = "1.0.2", features = ["crypto-wrapper"] }
|
||||
lazy_static = "1.4.0"
|
||||
actix = "0.13.1"
|
||||
actix-web = "4"
|
||||
actix = "0.13.3"
|
||||
actix-web = "4.5.1"
|
||||
actix-remote-ip = "0.1.0"
|
||||
actix-session = { version = "0.8.0", features = ["cookie-session"] }
|
||||
actix-identity = "0.6.0"
|
||||
actix-cors = "0.6.5"
|
||||
actix-files = "0.6.2"
|
||||
actix-web-actors = "4.2.0"
|
||||
actix-http = "3.4.0"
|
||||
serde = { version = "1.0.193", features = ["derive"] }
|
||||
serde_json = "1.0.108"
|
||||
actix-session = { version = "0.9.0", features = ["cookie-session"] }
|
||||
actix-identity = "0.7.1"
|
||||
actix-cors = "0.7.0"
|
||||
actix-files = "0.6.5"
|
||||
actix-web-actors = "4.3.0"
|
||||
actix-http = "3.6.0"
|
||||
serde = { version = "1.0.197", features = ["derive"] }
|
||||
serde_json = "1.0.115"
|
||||
quick-xml = { version = "0.31.0", features = ["serialize", "overlapped-lists"] }
|
||||
futures-util = "0.3.28"
|
||||
anyhow = "1.0.75"
|
||||
futures-util = "0.3.30"
|
||||
anyhow = "1.0.81"
|
||||
actix-multipart = "0.6.1"
|
||||
tempfile = "3.8.1"
|
||||
reqwest = { version = "0.11.23", features = ["stream"] }
|
||||
tempfile = "3.10.1"
|
||||
reqwest = { version = "0.12.3", features = ["stream"] }
|
||||
url = "2.5.0"
|
||||
virt = "0.3.1"
|
||||
sysinfo = { version = "0.29.11", features = ["serde"] }
|
||||
uuid = { version = "1.6.1", features = ["v4", "serde"] }
|
||||
sysinfo = { version = "0.30.8", features = ["serde"] }
|
||||
uuid = { version = "1.8.0", features = ["v4", "serde"] }
|
||||
lazy-regex = "3.1.0"
|
||||
thiserror = "1.0.51"
|
||||
image = "0.24.7"
|
||||
thiserror = "1.0.58"
|
||||
image = "0.25.1"
|
||||
rand = "0.8.5"
|
||||
bytes = "1.5.0"
|
||||
tokio = "1.35.0"
|
||||
futures = "0.3.29"
|
||||
bytes = "1.6.0"
|
||||
tokio = "1.37.0"
|
||||
futures = "0.3.30"
|
||||
ipnetwork = "0.20.0"
|
||||
num = "0.4.1"
|
||||
rust-embed = { version = "8.1.0" }
|
||||
rust-embed = { version = "8.3.0" }
|
||||
mime_guess = "2.0.4"
|
||||
dotenvy = "0.15.7"
|
||||
nix = { version = "0.28.0", features = ["net"] }
|
||||
|
||||
@@ -7,8 +7,9 @@ use crate::libvirt_rest_structures::hypervisor::*;
|
||||
use crate::libvirt_rest_structures::net::*;
|
||||
use crate::libvirt_rest_structures::nw_filter::{NetworkFilter, NetworkFilterName};
|
||||
use crate::libvirt_rest_structures::vm::*;
|
||||
use crate::nat::nat_lib;
|
||||
use actix::{Actor, Context, Handler, Message};
|
||||
use image::ImageOutputFormat;
|
||||
use image::ImageFormat;
|
||||
use std::io::Cursor;
|
||||
use virt::connect::Connect;
|
||||
use virt::domain::Domain;
|
||||
@@ -336,7 +337,7 @@ impl Handler<ScreenshotDomainReq> for LibVirtActor {
|
||||
|
||||
let image = image::load_from_memory(&screen_out)?;
|
||||
let mut png_out = Cursor::new(Vec::new());
|
||||
image.write_to(&mut png_out, ImageOutputFormat::Png)?;
|
||||
image.write_to(&mut png_out, ImageFormat::Png)?;
|
||||
|
||||
Ok(png_out.into_inner())
|
||||
}
|
||||
@@ -395,6 +396,9 @@ impl Handler<DefineNetwork> for LibVirtActor {
|
||||
let network = Network::define_xml(&self.m, &network_xml)?;
|
||||
let uuid = XMLUuid::parse_from_str(&network.get_uuid_string()?)?;
|
||||
|
||||
// Save NAT definition
|
||||
nat_lib::save_nat_def(&msg.0)?;
|
||||
|
||||
// Save a copy of the source definition
|
||||
msg.0.uuid = Some(uuid);
|
||||
let json = serde_json::to_string(&msg.0)?;
|
||||
@@ -464,9 +468,12 @@ impl Handler<DeleteNetwork> for LibVirtActor {
|
||||
fn handle(&mut self, msg: DeleteNetwork, _ctx: &mut Self::Context) -> Self::Result {
|
||||
log::debug!("Delete network: {}\n", msg.0.as_string());
|
||||
let network = Network::lookup_by_uuid_string(&self.m, &msg.0.as_string())?;
|
||||
let network_name = network.get_name()?;
|
||||
let network_name = NetworkName(network.get_name()?);
|
||||
network.undefine()?;
|
||||
|
||||
// Remove NAT definition, if any
|
||||
nat_lib::remove_nat_def(&network_name)?;
|
||||
|
||||
// Remove backup definition
|
||||
let backup_definition = AppConfig::get().net_definition_path(&network_name);
|
||||
if backup_definition.exists() {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use crate::constants;
|
||||
use crate::libvirt_lib_structures::XMLUuid;
|
||||
use crate::libvirt_rest_structures::net::NetworkName;
|
||||
use crate::libvirt_rest_structures::nw_filter::NetworkFilterName;
|
||||
use clap::Parser;
|
||||
use std::net::IpAddr;
|
||||
@@ -250,8 +252,16 @@ impl AppConfig {
|
||||
self.definitions_path().join(format!("vm-{name}.json"))
|
||||
}
|
||||
|
||||
pub fn net_definition_path(&self, name: &str) -> PathBuf {
|
||||
self.definitions_path().join(format!("net-{name}.json"))
|
||||
pub fn net_definition_path(&self, name: &NetworkName) -> PathBuf {
|
||||
self.definitions_path().join(format!("net-{}.json", name.0))
|
||||
}
|
||||
|
||||
pub fn nat_path(&self) -> PathBuf {
|
||||
self.storage_path().join(constants::STORAGE_NAT_DIR)
|
||||
}
|
||||
|
||||
pub fn net_nat_path(&self, name: &NetworkName) -> PathBuf {
|
||||
self.nat_path().join(name.nat_file_name())
|
||||
}
|
||||
|
||||
pub fn net_filter_definition_path(&self, name: &NetworkFilterName) -> PathBuf {
|
||||
|
||||
@@ -44,6 +44,9 @@ pub const DISK_SIZE_MIN: usize = 100;
|
||||
/// Disk size max (MB)
|
||||
pub const DISK_SIZE_MAX: usize = 1000 * 1000 * 2;
|
||||
|
||||
/// Net nat entry comment max size
|
||||
pub const NET_NAT_COMMENT_MAX_SIZE: usize = 250;
|
||||
|
||||
/// Network mac address default prefix
|
||||
pub const NET_MAC_ADDR_PREFIX: &str = "52:54:00";
|
||||
|
||||
@@ -77,3 +80,12 @@ pub const BUILTIN_NETWORK_FILTER_RULES: [&str; 24] = [
|
||||
|
||||
/// List of valid network chains
|
||||
pub const NETWORK_CHAINS: [&str; 8] = ["root", "mac", "stp", "vlan", "arp", "rarp", "ipv4", "ipv6"];
|
||||
|
||||
/// Directory where nat rules are stored, inside storage directory
|
||||
pub const STORAGE_NAT_DIR: &str = "nat";
|
||||
|
||||
/// Environment variable that is set to run VirtWeb in NAT configuration mode
|
||||
pub const NAT_MODE_ENV_VAR_NAME: &str = "NAT_MODE";
|
||||
|
||||
/// Nat hook file path
|
||||
pub const NAT_HOOK_PATH: &str = "/etc/libvirt/hooks/network";
|
||||
|
||||
@@ -5,8 +5,10 @@ use crate::constants::{DISK_NAME_MAX_LEN, DISK_NAME_MIN_LEN, DISK_SIZE_MAX, DISK
|
||||
use crate::controllers::{HttpResult, LibVirtReq};
|
||||
use crate::extractors::local_auth_extractor::LocalAuthEnabled;
|
||||
use crate::libvirt_rest_structures::hypervisor::HypervisorInfo;
|
||||
use crate::nat::nat_hook;
|
||||
use crate::utils::net_utils;
|
||||
use actix_web::{HttpResponse, Responder};
|
||||
use sysinfo::{NetworksExt, System, SystemExt};
|
||||
use sysinfo::{Components, Disks, Networks, System};
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
struct StaticConfig {
|
||||
@@ -43,6 +45,7 @@ struct ServerConstraints {
|
||||
disk_size: LenConstraints,
|
||||
net_name_size: LenConstraints,
|
||||
net_title_size: LenConstraints,
|
||||
net_nat_comment_size: LenConstraints,
|
||||
dhcp_reservation_host_name: LenConstraints,
|
||||
nwfilter_name_size: LenConstraints,
|
||||
nwfilter_comment_size: LenConstraints,
|
||||
@@ -81,6 +84,10 @@ pub async fn static_config(local_auth: LocalAuthEnabled) -> impl Responder {
|
||||
|
||||
net_name_size: LenConstraints { min: 2, max: 50 },
|
||||
net_title_size: LenConstraints { min: 0, max: 50 },
|
||||
net_nat_comment_size: LenConstraints {
|
||||
min: 0,
|
||||
max: constants::NET_NAT_COMMENT_MAX_SIZE,
|
||||
},
|
||||
|
||||
dhcp_reservation_host_name: LenConstraints { min: 2, max: 250 },
|
||||
|
||||
@@ -99,18 +106,48 @@ pub async fn static_config(local_auth: LocalAuthEnabled) -> impl Responder {
|
||||
struct ServerInfo {
|
||||
hypervisor: HypervisorInfo,
|
||||
system: System,
|
||||
components: Components,
|
||||
disks: Disks,
|
||||
networks: Networks,
|
||||
}
|
||||
|
||||
pub async fn server_info(client: LibVirtReq) -> HttpResult {
|
||||
let mut system = System::new();
|
||||
system.refresh_disks_list();
|
||||
system.refresh_components_list();
|
||||
system.refresh_networks_list();
|
||||
system.refresh_all();
|
||||
|
||||
let mut components = Components::new();
|
||||
components.refresh_list();
|
||||
components.refresh();
|
||||
|
||||
let mut disks = Disks::new();
|
||||
disks.refresh_list();
|
||||
disks.refresh();
|
||||
|
||||
let mut networks = Networks::new();
|
||||
networks.refresh_list();
|
||||
networks.refresh();
|
||||
|
||||
Ok(HttpResponse::Ok().json(ServerInfo {
|
||||
hypervisor: client.get_info().await?,
|
||||
system,
|
||||
components,
|
||||
disks,
|
||||
networks,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
struct NetworkHookStatus {
|
||||
installed: bool,
|
||||
content: String,
|
||||
path: &'static str,
|
||||
}
|
||||
|
||||
pub async fn network_hook_status() -> HttpResult {
|
||||
Ok(HttpResponse::Ok().json(NetworkHookStatus {
|
||||
installed: nat_hook::is_installed()?,
|
||||
content: nat_hook::hook_content()?,
|
||||
path: constants::NAT_HOOK_PATH,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -132,14 +169,5 @@ pub async fn number_vcpus() -> HttpResult {
|
||||
}
|
||||
|
||||
pub async fn networks_list() -> HttpResult {
|
||||
let mut system = System::new();
|
||||
system.refresh_networks_list();
|
||||
|
||||
Ok(HttpResponse::Ok().json(
|
||||
system
|
||||
.networks()
|
||||
.iter()
|
||||
.map(|n| n.0.to_string())
|
||||
.collect::<Vec<_>>(),
|
||||
))
|
||||
Ok(HttpResponse::Ok().json(net_utils::net_list()))
|
||||
}
|
||||
|
||||
@@ -7,4 +7,5 @@ pub mod libvirt_client;
|
||||
pub mod libvirt_lib_structures;
|
||||
pub mod libvirt_rest_structures;
|
||||
pub mod middlewares;
|
||||
pub mod nat;
|
||||
pub mod utils;
|
||||
|
||||
@@ -43,14 +43,6 @@ pub struct NetworkDomainXML {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
fn invalid_prefix() -> u32 {
|
||||
u32::MAX
|
||||
}
|
||||
|
||||
fn invalid_ip() -> IpAddr {
|
||||
IpAddr::V4(Ipv4Addr::BROADCAST)
|
||||
}
|
||||
|
||||
/// Network ip information
|
||||
#[derive(serde::Serialize, serde::Deserialize, Debug)]
|
||||
#[serde(rename = "ip")]
|
||||
@@ -60,12 +52,13 @@ pub struct NetworkIPXML {
|
||||
#[serde(rename = "@address")]
|
||||
pub address: IpAddr,
|
||||
/// Network Prefix
|
||||
#[serde(rename = "@prefix", default = "invalid_prefix")]
|
||||
pub prefix: u32,
|
||||
#[serde(rename = "@prefix")]
|
||||
pub prefix: Option<u8>,
|
||||
/// Network Netmask. This field is never serialized, but because we can't know if LibVirt will
|
||||
/// provide us netmask or prefix, we need to handle both of these fields
|
||||
#[serde(rename = "@netmask", default = "invalid_ip", skip_serializing)]
|
||||
pub netmask: IpAddr,
|
||||
#[serde(rename = "@netmask", skip_serializing)]
|
||||
pub netmask: Option<IpAddr>,
|
||||
|
||||
pub dhcp: Option<NetworkDHCPXML>,
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
use crate::libvirt_lib_structures::network::*;
|
||||
use crate::libvirt_lib_structures::XMLUuid;
|
||||
use crate::libvirt_rest_structures::LibVirtStructError::StructureExtraction;
|
||||
use crate::nat::nat_definition::Nat;
|
||||
use crate::nat::nat_lib;
|
||||
use crate::utils::net_utils;
|
||||
use crate::utils::net_utils::{extract_ipv4, extract_ipv6};
|
||||
use ipnetwork::{Ipv4Network, Ipv6Network};
|
||||
use lazy_regex::regex;
|
||||
@@ -21,57 +24,75 @@ pub struct DHCPv4HostReservation {
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
|
||||
pub struct IPv4DHCPConfig {
|
||||
start: Ipv4Addr,
|
||||
end: Ipv4Addr,
|
||||
hosts: Vec<DHCPv4HostReservation>,
|
||||
pub start: Ipv4Addr,
|
||||
pub end: Ipv4Addr,
|
||||
pub hosts: Vec<DHCPv4HostReservation>,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
|
||||
pub struct IPV4Config {
|
||||
bridge_address: Ipv4Addr,
|
||||
prefix: u32,
|
||||
dhcp: Option<IPv4DHCPConfig>,
|
||||
pub bridge_address: Ipv4Addr,
|
||||
pub prefix: u8,
|
||||
pub dhcp: Option<IPv4DHCPConfig>,
|
||||
pub nat: Option<Vec<Nat<Ipv4Addr>>>,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
|
||||
pub struct DHCPv6HostReservation {
|
||||
name: String,
|
||||
ip: Ipv6Addr,
|
||||
pub name: String,
|
||||
pub ip: Ipv6Addr,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
|
||||
pub struct IPv6DHCPConfig {
|
||||
start: Ipv6Addr,
|
||||
end: Ipv6Addr,
|
||||
hosts: Vec<DHCPv6HostReservation>,
|
||||
pub start: Ipv6Addr,
|
||||
pub end: Ipv6Addr,
|
||||
pub hosts: Vec<DHCPv6HostReservation>,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
|
||||
pub struct IPV6Config {
|
||||
bridge_address: Ipv6Addr,
|
||||
prefix: u32,
|
||||
dhcp: Option<IPv6DHCPConfig>,
|
||||
pub bridge_address: Ipv6Addr,
|
||||
pub prefix: u8,
|
||||
pub dhcp: Option<IPv6DHCPConfig>,
|
||||
pub nat: Option<Vec<Nat<Ipv6Addr>>>,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
||||
pub struct NetworkName(pub String);
|
||||
|
||||
impl NetworkName {
|
||||
/// Get the name of the file that will store the NAT configuration of this network
|
||||
pub fn nat_file_name(&self) -> String {
|
||||
format!("nat-{}.json", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl NetworkName {
|
||||
pub fn is_valid(&self) -> bool {
|
||||
regex!("^[a-zA-Z0-9]+$").is_match(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Network configuration
|
||||
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
|
||||
pub struct NetworkInfo {
|
||||
pub name: String,
|
||||
pub name: NetworkName,
|
||||
pub uuid: Option<XMLUuid>,
|
||||
title: Option<String>,
|
||||
description: Option<String>,
|
||||
forward_mode: NetworkForwardMode,
|
||||
device: Option<String>,
|
||||
bridge_name: Option<String>,
|
||||
dns_server: Option<Ipv4Addr>,
|
||||
domain: Option<String>,
|
||||
ip_v4: Option<IPV4Config>,
|
||||
ip_v6: Option<IPV6Config>,
|
||||
pub title: Option<String>,
|
||||
pub description: Option<String>,
|
||||
pub forward_mode: NetworkForwardMode,
|
||||
pub device: Option<String>,
|
||||
pub bridge_name: Option<String>,
|
||||
pub dns_server: Option<Ipv4Addr>,
|
||||
pub domain: Option<String>,
|
||||
pub ip_v4: Option<IPV4Config>,
|
||||
pub ip_v6: Option<IPV6Config>,
|
||||
}
|
||||
|
||||
impl NetworkInfo {
|
||||
pub fn as_virt_network(&self) -> anyhow::Result<NetworkXML> {
|
||||
if !regex!("^[a-zA-Z0-9]+$").is_match(&self.name) {
|
||||
if !self.name.is_valid() {
|
||||
return Err(StructureExtraction("network name is invalid!").into());
|
||||
}
|
||||
|
||||
@@ -102,18 +123,26 @@ impl NetworkInfo {
|
||||
let mut ips = Vec::with_capacity(2);
|
||||
|
||||
if let Some(ipv4) = &self.ip_v4 {
|
||||
if ipv4.prefix > 32 {
|
||||
if !net_utils::is_ipv4_mask_valid(ipv4.prefix) {
|
||||
return Err(StructureExtraction("IPv4 prefix is invalid!").into());
|
||||
}
|
||||
|
||||
if let Some(nat) = &ipv4.nat {
|
||||
for n in nat {
|
||||
n.check()?;
|
||||
}
|
||||
}
|
||||
|
||||
ips.push(NetworkIPXML {
|
||||
family: "ipv4".to_string(),
|
||||
address: IpAddr::V4(ipv4.bridge_address),
|
||||
prefix: ipv4.prefix,
|
||||
netmask: Ipv4Network::new(ipv4.bridge_address, ipv4.prefix as u8)
|
||||
.unwrap()
|
||||
.mask()
|
||||
.into(),
|
||||
prefix: Some(ipv4.prefix),
|
||||
netmask: Some(
|
||||
Ipv4Network::new(ipv4.bridge_address, ipv4.prefix)
|
||||
.unwrap()
|
||||
.mask()
|
||||
.into(),
|
||||
),
|
||||
dhcp: ipv4.dhcp.as_ref().map(|dhcp| NetworkDHCPXML {
|
||||
range: NetworkDHCPRangeXML {
|
||||
start: IpAddr::V4(dhcp.start),
|
||||
@@ -133,14 +162,26 @@ impl NetworkInfo {
|
||||
}
|
||||
|
||||
if let Some(ipv6) = &self.ip_v6 {
|
||||
if !net_utils::is_ipv6_mask_valid(ipv6.prefix) {
|
||||
return Err(StructureExtraction("IPv6 prefix is invalid!").into());
|
||||
}
|
||||
|
||||
if let Some(nat) = &ipv6.nat {
|
||||
for n in nat {
|
||||
n.check()?;
|
||||
}
|
||||
}
|
||||
|
||||
ips.push(NetworkIPXML {
|
||||
family: "ipv6".to_string(),
|
||||
address: IpAddr::V6(ipv6.bridge_address),
|
||||
prefix: ipv6.prefix,
|
||||
netmask: Ipv6Network::new(ipv6.bridge_address, ipv6.prefix as u8)
|
||||
.unwrap()
|
||||
.mask()
|
||||
.into(),
|
||||
prefix: Some(ipv6.prefix),
|
||||
netmask: Some(
|
||||
Ipv6Network::new(ipv6.bridge_address, ipv6.prefix)
|
||||
.unwrap()
|
||||
.mask()
|
||||
.into(),
|
||||
),
|
||||
dhcp: ipv6.dhcp.as_ref().map(|dhcp| NetworkDHCPXML {
|
||||
range: NetworkDHCPRangeXML {
|
||||
start: IpAddr::V6(dhcp.start),
|
||||
@@ -160,7 +201,7 @@ impl NetworkInfo {
|
||||
}
|
||||
|
||||
Ok(NetworkXML {
|
||||
name: self.name.to_string(),
|
||||
name: self.name.0.to_string(),
|
||||
uuid: self.uuid,
|
||||
title: self.title.clone(),
|
||||
description: self.description.clone(),
|
||||
@@ -183,8 +224,12 @@ impl NetworkInfo {
|
||||
}
|
||||
|
||||
pub fn from_xml(xml: NetworkXML) -> anyhow::Result<Self> {
|
||||
let name = NetworkName(xml.name);
|
||||
|
||||
let nat = nat_lib::load_nat_def(&name)?;
|
||||
|
||||
Ok(Self {
|
||||
name: xml.name,
|
||||
name,
|
||||
uuid: xml.uuid,
|
||||
title: xml.title,
|
||||
description: xml.description,
|
||||
@@ -209,10 +254,9 @@ impl NetworkInfo {
|
||||
.map(|i| IPV4Config {
|
||||
bridge_address: extract_ipv4(i.address),
|
||||
prefix: match i.prefix {
|
||||
u32::MAX => ipnetwork::ipv4_mask_to_prefix(extract_ipv4(i.netmask))
|
||||
.expect("Failed to convert IPv4 netmask to network")
|
||||
as u32,
|
||||
p => p,
|
||||
None => ipnetwork::ipv4_mask_to_prefix(extract_ipv4(i.netmask.unwrap()))
|
||||
.expect("Failed to convert IPv4 netmask to network"),
|
||||
Some(p) => p,
|
||||
},
|
||||
dhcp: i.dhcp.as_ref().map(|d| IPv4DHCPConfig {
|
||||
start: extract_ipv4(d.range.start),
|
||||
@@ -227,6 +271,7 @@ impl NetworkInfo {
|
||||
})
|
||||
.collect(),
|
||||
}),
|
||||
nat: nat.ipv4,
|
||||
}),
|
||||
ip_v6: xml
|
||||
.ips
|
||||
@@ -235,10 +280,9 @@ impl NetworkInfo {
|
||||
.map(|i| IPV6Config {
|
||||
bridge_address: extract_ipv6(i.address),
|
||||
prefix: match i.prefix {
|
||||
u32::MAX => ipnetwork::ipv6_mask_to_prefix(extract_ipv6(i.netmask))
|
||||
.expect("Failed to convert IPv6 netmask to network")
|
||||
as u32,
|
||||
p => p,
|
||||
None => ipnetwork::ipv6_mask_to_prefix(extract_ipv6(i.netmask.unwrap()))
|
||||
.expect("Failed to convert IPv6 netmask to network"),
|
||||
Some(p) => p,
|
||||
},
|
||||
dhcp: i.dhcp.as_ref().map(|d| IPv6DHCPConfig {
|
||||
start: extract_ipv6(d.range.start),
|
||||
@@ -252,7 +296,25 @@ impl NetworkInfo {
|
||||
})
|
||||
.collect(),
|
||||
}),
|
||||
nat: nat.ipv6,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
/// Check if at least one NAT definition was specified on this interface
|
||||
pub fn has_nat_def(&self) -> bool {
|
||||
if let Some(ipv4) = &self.ip_v4 {
|
||||
if ipv4.nat.is_some() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ipv6) = &self.ip_v6 {
|
||||
if ipv6.nat.is_some() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,12 +27,19 @@ use virtweb_backend::controllers::{
|
||||
};
|
||||
use virtweb_backend::libvirt_client::LibVirtClient;
|
||||
use virtweb_backend::middlewares::auth_middleware::AuthChecker;
|
||||
use virtweb_backend::nat::nat_conf_mode;
|
||||
use virtweb_backend::utils::files_utils;
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
||||
|
||||
// Run in NAT configuration mode, if requested
|
||||
if std::env::var(constants::NAT_MODE_ENV_VAR_NAME).is_ok() {
|
||||
nat_conf_mode::sub_main().await.unwrap();
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Load additional config from file, if requested
|
||||
AppConfig::parse_env_file().unwrap();
|
||||
|
||||
@@ -41,6 +48,7 @@ async fn main() -> std::io::Result<()> {
|
||||
files_utils::create_directory_if_missing(AppConfig::get().vnc_sockets_path()).unwrap();
|
||||
files_utils::set_file_permission(AppConfig::get().vnc_sockets_path(), 0o777).unwrap();
|
||||
files_utils::create_directory_if_missing(AppConfig::get().disks_storage_path()).unwrap();
|
||||
files_utils::create_directory_if_missing(AppConfig::get().nat_path()).unwrap();
|
||||
files_utils::create_directory_if_missing(AppConfig::get().definitions_path()).unwrap();
|
||||
|
||||
let conn = Data::new(LibVirtClient(
|
||||
@@ -110,6 +118,10 @@ async fn main() -> std::io::Result<()> {
|
||||
"/api/server/info",
|
||||
web::get().to(server_controller::server_info),
|
||||
)
|
||||
.route(
|
||||
"/api/server/network_hook_status",
|
||||
web::get().to(server_controller::network_hook_status),
|
||||
)
|
||||
.route(
|
||||
"/api/server/number_vcpus",
|
||||
web::get().to(server_controller::number_vcpus),
|
||||
|
||||
4
virtweb_backend/src/nat/mod.rs
Normal file
4
virtweb_backend/src/nat/mod.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
pub mod nat_conf_mode;
|
||||
pub mod nat_definition;
|
||||
pub mod nat_hook;
|
||||
pub mod nat_lib;
|
||||
232
virtweb_backend/src/nat/nat_conf_mode.rs
Normal file
232
virtweb_backend/src/nat/nat_conf_mode.rs
Normal file
@@ -0,0 +1,232 @@
|
||||
use crate::constants;
|
||||
use crate::libvirt_rest_structures::net::NetworkName;
|
||||
use crate::nat::nat_definition::{Nat, NatSourceIP, NetNat};
|
||||
use crate::utils::net_utils;
|
||||
use clap::Parser;
|
||||
use std::collections::HashMap;
|
||||
use std::net::IpAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitStatus};
|
||||
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
enum NatConfModeError {
|
||||
#[error("UpdateFirewall failed!")]
|
||||
UpdateFirewall,
|
||||
}
|
||||
|
||||
/// VirtWeb NAT configuration mode. This executable should never be executed manually
|
||||
#[derive(Parser, Debug, Clone)]
|
||||
#[clap(author, version, about, long_about = None)]
|
||||
struct NatArgs {
|
||||
/// Storage directory
|
||||
#[clap(short, long)]
|
||||
storage: String,
|
||||
|
||||
/// Network name
|
||||
#[clap(short, long)]
|
||||
network_name: String,
|
||||
|
||||
/// Operation
|
||||
#[clap(short, long)]
|
||||
operation: String,
|
||||
|
||||
/// Sub operation
|
||||
#[clap(long)]
|
||||
sub_operation: String,
|
||||
}
|
||||
|
||||
impl NatArgs {
|
||||
pub fn network_file(&self) -> PathBuf {
|
||||
let network_name = NetworkName(self.network_name.to_string());
|
||||
Path::new(&self.storage)
|
||||
.join(constants::STORAGE_NAT_DIR)
|
||||
.join(network_name.nat_file_name())
|
||||
}
|
||||
}
|
||||
|
||||
/// NAT sub main function
|
||||
pub async fn sub_main() -> anyhow::Result<()> {
|
||||
let args = NatArgs::parse();
|
||||
|
||||
if !args.network_file().exists() {
|
||||
log::warn!("Cannot do anything for the network, because the NAT configuration file does not exixsts!");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let conf_json = std::fs::read_to_string(args.network_file())?;
|
||||
let conf: NetNat = serde_json::from_str(&conf_json)?;
|
||||
|
||||
let nic_ips = net_utils::net_list_and_ips()?;
|
||||
|
||||
match (args.operation.as_str(), args.sub_operation.as_str()) {
|
||||
("started", "begin") => {
|
||||
log::info!("Enable port forwarding for network");
|
||||
trigger_nat_forwarding(true, &conf, &nic_ips).await?
|
||||
}
|
||||
("stopped", "end") => {
|
||||
log::info!("Disable port forwarding for network");
|
||||
trigger_nat_forwarding(false, &conf, &nic_ips).await?
|
||||
}
|
||||
_ => log::debug!(
|
||||
"Operation {} - {} not supported",
|
||||
args.operation,
|
||||
args.sub_operation
|
||||
),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn trigger_nat_forwarding(
|
||||
enable: bool,
|
||||
conf: &NetNat,
|
||||
nic_ips: &HashMap<String, Vec<IpAddr>>,
|
||||
) -> anyhow::Result<()> {
|
||||
if let Some(ipv4) = &conf.ipv4 {
|
||||
trigger_nat_forwarding_nat_ipv(
|
||||
enable,
|
||||
&conf.interface,
|
||||
&ipv4.iter().map(|i| i.generalize()).collect::<Vec<_>>(),
|
||||
nic_ips,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
if let Some(ipv6) = &conf.ipv6 {
|
||||
trigger_nat_forwarding_nat_ipv(
|
||||
enable,
|
||||
&conf.interface,
|
||||
&ipv6.iter().map(|i| i.generalize()).collect::<Vec<_>>(),
|
||||
nic_ips,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn trigger_nat_forwarding_nat_ipv(
|
||||
enable: bool,
|
||||
net_interface: &str,
|
||||
rules: &[Nat<IpAddr>],
|
||||
nic_ips: &HashMap<String, Vec<IpAddr>>,
|
||||
) -> anyhow::Result<()> {
|
||||
for r in rules {
|
||||
let host_ips = match &r.host_ip {
|
||||
NatSourceIP::Interface { name } => nic_ips.get(name).cloned().unwrap_or_default(),
|
||||
NatSourceIP::Ip { ip } => vec![*ip],
|
||||
};
|
||||
|
||||
for host_ip in host_ips {
|
||||
let mut guest_port = r.guest_port;
|
||||
for host_port in r.host_port.as_seq() {
|
||||
if r.protocol.has_tcp() {
|
||||
toggle_port_forwarding(
|
||||
enable,
|
||||
false,
|
||||
host_ip,
|
||||
host_port,
|
||||
net_interface,
|
||||
r.guest_ip,
|
||||
guest_port,
|
||||
)?
|
||||
}
|
||||
|
||||
if r.protocol.has_udp() {
|
||||
toggle_port_forwarding(
|
||||
enable,
|
||||
true,
|
||||
host_ip,
|
||||
host_port,
|
||||
net_interface,
|
||||
r.guest_ip,
|
||||
guest_port,
|
||||
)?
|
||||
}
|
||||
|
||||
guest_port += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_cmd(s: ExitStatus) -> anyhow::Result<()> {
|
||||
if !s.success() {
|
||||
log::error!("Failed to update firewall rules!");
|
||||
return Err(NatConfModeError::UpdateFirewall.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn toggle_port_forwarding(
|
||||
enable: bool,
|
||||
is_udp: bool,
|
||||
host_ip: IpAddr,
|
||||
host_port: u16,
|
||||
net_interface: &str,
|
||||
guest_ip: IpAddr,
|
||||
guest_port: u16,
|
||||
) -> anyhow::Result<()> {
|
||||
if host_ip.is_ipv4() != guest_ip.is_ipv4() {
|
||||
log::trace!("Skipping invalid combination {host_ip} -> {guest_ip}");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let program = match host_ip.is_ipv4() {
|
||||
true => "/sbin/iptables",
|
||||
false => "/sbin/ip6tables",
|
||||
};
|
||||
|
||||
let protocol = match is_udp {
|
||||
true => "udp",
|
||||
false => "tcp",
|
||||
};
|
||||
|
||||
log::info!("Forward (add={enable}) incoming {protocol} connections for {host_ip}:{host_port} to {guest_ip}:{guest_port} int {net_interface}");
|
||||
|
||||
// Rule 1
|
||||
let cmd = Command::new(program)
|
||||
.arg(match enable {
|
||||
true => "-I",
|
||||
false => "-D",
|
||||
})
|
||||
.arg("FORWARD")
|
||||
.arg("-o")
|
||||
.arg(net_interface)
|
||||
.arg("-p")
|
||||
.arg(protocol)
|
||||
.arg("-d")
|
||||
.arg(guest_ip.to_string())
|
||||
.arg("--dport")
|
||||
.arg(guest_port.to_string())
|
||||
.arg("-j")
|
||||
.arg("ACCEPT")
|
||||
.status()?;
|
||||
check_cmd(cmd)?;
|
||||
|
||||
// Rule 2
|
||||
let cmd = Command::new(program)
|
||||
.arg("-t")
|
||||
.arg("nat")
|
||||
.arg(match enable {
|
||||
true => "-I",
|
||||
false => "-D",
|
||||
})
|
||||
.arg("PREROUTING")
|
||||
.arg("-p")
|
||||
.arg(protocol)
|
||||
.arg("-d")
|
||||
.arg(host_ip.to_string())
|
||||
.arg("--dport")
|
||||
.arg(host_port.to_string())
|
||||
.arg("-j")
|
||||
.arg("DNAT")
|
||||
.arg("--to")
|
||||
.arg(format!("{guest_ip}:{guest_port}"))
|
||||
.status()?;
|
||||
check_cmd(cmd)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
142
virtweb_backend/src/nat/nat_definition.rs
Normal file
142
virtweb_backend/src/nat/nat_definition.rs
Normal file
@@ -0,0 +1,142 @@
|
||||
use crate::constants;
|
||||
use crate::utils::net_utils;
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
enum NatDefError {
|
||||
#[error("Invalid nat definition: {0}")]
|
||||
InvalidNatDef(&'static str),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "lowercase")]
|
||||
pub enum NatSourceIP<IPv> {
|
||||
Interface { name: String },
|
||||
Ip { ip: IPv },
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub enum NatProtocol {
|
||||
TCP,
|
||||
UDP,
|
||||
Both,
|
||||
}
|
||||
|
||||
impl NatProtocol {
|
||||
pub fn has_tcp(&self) -> bool {
|
||||
!matches!(&self, NatProtocol::UDP)
|
||||
}
|
||||
|
||||
pub fn has_udp(&self) -> bool {
|
||||
!matches!(&self, NatProtocol::TCP)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "lowercase")]
|
||||
pub enum NatHostPort {
|
||||
Single { port: u16 },
|
||||
Range { start: u16, end: u16 },
|
||||
}
|
||||
|
||||
impl NatHostPort {
|
||||
pub fn as_seq(&self) -> Vec<u16> {
|
||||
match self {
|
||||
NatHostPort::Single { port } => vec![*port],
|
||||
NatHostPort::Range { start, end } => (*start..(*end + 1)).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Nat<IPv> {
|
||||
pub protocol: NatProtocol,
|
||||
pub host_ip: NatSourceIP<IPv>,
|
||||
pub host_port: NatHostPort,
|
||||
pub guest_ip: IPv,
|
||||
pub guest_port: u16,
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
impl<IPv> Nat<IPv> {
|
||||
pub fn check(&self) -> anyhow::Result<()> {
|
||||
if let NatSourceIP::Interface { name } = &self.host_ip {
|
||||
if !net_utils::is_net_interface_name_valid(name) {
|
||||
return Err(NatDefError::InvalidNatDef("Invalid nat interface name!").into());
|
||||
}
|
||||
}
|
||||
|
||||
if let NatHostPort::Range { start, end } = &self.host_port {
|
||||
if *start == 0 {
|
||||
return Err(NatDefError::InvalidNatDef("Invalid start range!").into());
|
||||
}
|
||||
|
||||
if start > end {
|
||||
return Err(NatDefError::InvalidNatDef("Invalid port range!").into());
|
||||
}
|
||||
|
||||
if u16::MAX - (end - start) < self.guest_port {
|
||||
return Err(NatDefError::InvalidNatDef("Guest port is too high!").into());
|
||||
}
|
||||
}
|
||||
|
||||
if self.guest_port == 0 {
|
||||
return Err(NatDefError::InvalidNatDef("Invalid guest port!").into());
|
||||
}
|
||||
|
||||
if let Some(comment) = &self.comment {
|
||||
if comment.len() > constants::NET_NAT_COMMENT_MAX_SIZE {
|
||||
return Err(NatDefError::InvalidNatDef("Comment is too large!").into());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Nat<Ipv4Addr> {
|
||||
pub fn generalize(&self) -> Nat<IpAddr> {
|
||||
Nat {
|
||||
protocol: self.protocol,
|
||||
host_ip: match &self.host_ip {
|
||||
NatSourceIP::Ip { ip } => NatSourceIP::Ip {
|
||||
ip: IpAddr::V4(*ip),
|
||||
},
|
||||
NatSourceIP::Interface { name } => NatSourceIP::Interface {
|
||||
name: name.to_string(),
|
||||
},
|
||||
},
|
||||
host_port: self.host_port.clone(),
|
||||
guest_ip: IpAddr::V4(self.guest_ip),
|
||||
guest_port: self.guest_port,
|
||||
comment: self.comment.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Nat<Ipv6Addr> {
|
||||
pub fn generalize(&self) -> Nat<IpAddr> {
|
||||
Nat {
|
||||
protocol: self.protocol,
|
||||
host_ip: match &self.host_ip {
|
||||
NatSourceIP::Ip { ip } => NatSourceIP::Ip {
|
||||
ip: IpAddr::V6(*ip),
|
||||
},
|
||||
NatSourceIP::Interface { name } => NatSourceIP::Interface {
|
||||
name: name.to_string(),
|
||||
},
|
||||
},
|
||||
host_port: self.host_port.clone(),
|
||||
guest_ip: IpAddr::V6(self.guest_ip),
|
||||
guest_port: self.guest_port,
|
||||
comment: self.comment.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default)]
|
||||
pub struct NetNat {
|
||||
pub interface: String,
|
||||
pub ipv4: Option<Vec<Nat<Ipv4Addr>>>,
|
||||
pub ipv6: Option<Vec<Nat<Ipv6Addr>>>,
|
||||
}
|
||||
29
virtweb_backend/src/nat/nat_hook.rs
Normal file
29
virtweb_backend/src/nat/nat_hook.rs
Normal file
@@ -0,0 +1,29 @@
|
||||
use crate::app_config::AppConfig;
|
||||
use crate::constants;
|
||||
use std::path::Path;
|
||||
|
||||
/// Check out whether NAT hook has been installed or not
|
||||
pub fn is_installed() -> anyhow::Result<bool> {
|
||||
let hook_file = Path::new(constants::NAT_HOOK_PATH);
|
||||
|
||||
if !hook_file.exists() {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let exe = std::env::current_exe()?;
|
||||
let hook_content = std::fs::read_to_string(hook_file)?;
|
||||
|
||||
Ok(hook_content.contains(exe.to_string_lossy().as_ref()))
|
||||
}
|
||||
|
||||
/// Get nat hook expected content
|
||||
pub fn hook_content() -> anyhow::Result<String> {
|
||||
let exe = std::env::current_exe()?;
|
||||
|
||||
Ok(format!(
|
||||
"#!/bin/bash\n\
|
||||
NAT_MODE=1 {} --storage {} --network-name \"$1\" --operation \"$2\" --sub-operation \"$3\"",
|
||||
exe.to_string_lossy(),
|
||||
AppConfig::get().storage
|
||||
))
|
||||
}
|
||||
61
virtweb_backend/src/nat/nat_lib.rs
Normal file
61
virtweb_backend/src/nat/nat_lib.rs
Normal file
@@ -0,0 +1,61 @@
|
||||
use crate::app_config::AppConfig;
|
||||
use crate::libvirt_rest_structures::net::{NetworkInfo, NetworkName};
|
||||
use crate::nat::nat_definition::NetNat;
|
||||
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
enum NatLibError {
|
||||
#[error("Could not save nat definition, because network bridge name was not specified!")]
|
||||
MissingNetworkBridgeName,
|
||||
}
|
||||
|
||||
/// Save nat definition
|
||||
pub fn save_nat_def(net: &NetworkInfo) -> anyhow::Result<()> {
|
||||
let nat = match net.has_nat_def() {
|
||||
true => NetNat {
|
||||
interface: net
|
||||
.bridge_name
|
||||
.as_ref()
|
||||
.ok_or(NatLibError::MissingNetworkBridgeName)?
|
||||
.to_string(),
|
||||
ipv4: net
|
||||
.ip_v4
|
||||
.as_ref()
|
||||
.map(|i| i.nat.clone())
|
||||
.unwrap_or_default(),
|
||||
ipv6: net
|
||||
.ip_v6
|
||||
.as_ref()
|
||||
.map(|i| i.nat.clone())
|
||||
.unwrap_or_default(),
|
||||
},
|
||||
false => NetNat::default(),
|
||||
};
|
||||
|
||||
let json = serde_json::to_string(&nat)?;
|
||||
|
||||
std::fs::write(AppConfig::get().net_nat_path(&net.name), json)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove nat definition, if existing
|
||||
pub fn remove_nat_def(name: &NetworkName) -> anyhow::Result<()> {
|
||||
let nat_file = AppConfig::get().net_nat_path(name);
|
||||
if nat_file.exists() {
|
||||
std::fs::remove_file(nat_file)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Load nat definition, if available
|
||||
pub fn load_nat_def(name: &NetworkName) -> anyhow::Result<NetNat> {
|
||||
let nat_file = AppConfig::get().net_nat_path(name);
|
||||
if !nat_file.exists() {
|
||||
return Ok(NetNat::default());
|
||||
}
|
||||
|
||||
let file = std::fs::read_to_string(nat_file)?;
|
||||
|
||||
Ok(serde_json::from_str(&file)?)
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
use nix::sys::socket::{AddressFamily, SockaddrLike};
|
||||
use std::collections::HashMap;
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
use std::str::FromStr;
|
||||
use sysinfo::Networks;
|
||||
|
||||
pub fn extract_ipv4(ip: IpAddr) -> Ipv4Addr {
|
||||
match ip {
|
||||
@@ -32,7 +35,7 @@ pub fn is_ipv4_mask_valid(mask: u8) -> bool {
|
||||
}
|
||||
|
||||
pub fn is_ipv6_mask_valid(mask: u8) -> bool {
|
||||
mask <= 64
|
||||
mask <= 128
|
||||
}
|
||||
|
||||
pub fn is_mask_valid(ipv: usize, mask: u8) -> bool {
|
||||
@@ -47,10 +50,97 @@ pub fn is_mac_address_valid<D: AsRef<str>>(mac: D) -> bool {
|
||||
lazy_regex::regex!("^([a-fA-F0-9]{2}[:-]){5}[a-fA-F0-9]{2}$").is_match(mac.as_ref())
|
||||
}
|
||||
|
||||
pub fn is_net_interface_name_valid<D: AsRef<str>>(int: D) -> bool {
|
||||
lazy_regex::regex!("^[a-zA-Z0-9]+$").is_match(int.as_ref())
|
||||
}
|
||||
|
||||
/// Get the list of available network interfaces
|
||||
pub fn net_list() -> Vec<String> {
|
||||
let mut networks = Networks::new();
|
||||
networks.refresh_list();
|
||||
|
||||
networks
|
||||
.list()
|
||||
.iter()
|
||||
.map(|n| n.0.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
|
||||
/// Get the list of available network interfaces associated with their IP address
|
||||
pub fn net_list_and_ips() -> anyhow::Result<HashMap<String, Vec<IpAddr>>> {
|
||||
let addrs = nix::ifaddrs::getifaddrs().unwrap();
|
||||
|
||||
let mut res = HashMap::new();
|
||||
|
||||
for ifaddr in addrs {
|
||||
let address = match ifaddr.address {
|
||||
Some(address) => address,
|
||||
None => {
|
||||
log::debug!(
|
||||
"Interface {} has an unsupported address family",
|
||||
ifaddr.interface_name
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let addr_str = match address.family() {
|
||||
Some(AddressFamily::Inet) => {
|
||||
let address = address.to_string();
|
||||
address
|
||||
.split_once(':')
|
||||
.map(|a| a.0)
|
||||
.unwrap_or(&address)
|
||||
.to_string()
|
||||
}
|
||||
Some(AddressFamily::Inet6) => {
|
||||
let address = address.to_string();
|
||||
let address = address
|
||||
.split_once(']')
|
||||
.map(|a| a.0)
|
||||
.unwrap_or(&address)
|
||||
.to_string();
|
||||
|
||||
let address = address
|
||||
.split_once('%')
|
||||
.map(|a| a.0)
|
||||
.unwrap_or(&address)
|
||||
.to_string();
|
||||
|
||||
address.strip_prefix('[').unwrap_or(&address).to_string()
|
||||
}
|
||||
_ => {
|
||||
log::debug!(
|
||||
"Interface {} has an unsupported address family {:?}",
|
||||
ifaddr.interface_name,
|
||||
address.family()
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
log::debug!(
|
||||
"Process ip {addr_str} for interface {}",
|
||||
ifaddr.interface_name
|
||||
);
|
||||
|
||||
let ip = IpAddr::from_str(&addr_str)?;
|
||||
|
||||
if !res.contains_key(&ifaddr.interface_name) {
|
||||
res.insert(ifaddr.interface_name.to_string(), Vec::with_capacity(1));
|
||||
}
|
||||
|
||||
res.get_mut(&ifaddr.interface_name).unwrap().push(ip);
|
||||
}
|
||||
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::utils::net_utils::{
|
||||
is_ipv4_address_valid, is_ipv6_address_valid, is_mac_address_valid, is_mask_valid,
|
||||
is_net_interface_name_valid,
|
||||
};
|
||||
|
||||
#[test]
|
||||
@@ -79,6 +169,7 @@ mod tests {
|
||||
assert!(is_ipv6_address_valid("fe80::"));
|
||||
assert!(is_ipv6_address_valid("fe80:dd::"));
|
||||
assert!(is_ipv6_address_valid("00:00:00:00:00::"));
|
||||
assert!(is_ipv6_address_valid("0:0:0:0:0:0:0:0"));
|
||||
|
||||
assert!(!is_ipv6_address_valid("tata"));
|
||||
assert!(!is_ipv6_address_valid("2.56.58.156"));
|
||||
@@ -93,6 +184,17 @@ mod tests {
|
||||
assert!(is_mask_valid(6, 34));
|
||||
|
||||
assert!(!is_mask_valid(4, 34));
|
||||
assert!(!is_mask_valid(6, 69));
|
||||
assert!(is_mask_valid(6, 69));
|
||||
assert!(is_mask_valid(6, 128));
|
||||
assert!(!is_mask_valid(6, 129));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_net_interface_name_valid() {
|
||||
assert!(is_net_interface_name_valid("eth0"));
|
||||
assert!(is_net_interface_name_valid("enp0s25"));
|
||||
|
||||
assert!(!is_net_interface_name_valid("enp0s25 "));
|
||||
assert!(!is_net_interface_name_valid("@enp0s25 "));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,7 +102,8 @@ sudo systemctl start virtweb
|
||||
|
||||
You should now be able to create VMs!
|
||||
|
||||
### Manual port forwarding without a LibVirt HOOK
|
||||
|
||||
## Configure port forwarding
|
||||
* Allow ip forwarding in the kernel: edit `/etc/sysctl.conf` and uncomment the following line:
|
||||
|
||||
```
|
||||
@@ -115,85 +116,34 @@ net.ipv4.ip_forward=1
|
||||
sudo sysctl -p /etc/sysctl.conf
|
||||
```
|
||||
|
||||
* Create the following IPTables rules:
|
||||
* Configure apparmore service. Create or update a file named `/etc/apparmor.d/local/usr.sbin.libvirtd` with the following content:
|
||||
|
||||
```
|
||||
UP_DEV=$(ip a | grep "192.168.1." -B 2 | head -n 1 | cut -d ':' -f 2 |
|
||||
tr -d ' ')
|
||||
LOCAL_DEV=$(ip a | grep "192.168.25." -B 2 | head -n 1 | cut -d ':' -f 2 | tr -d ' ')
|
||||
echo "$UP_DEV -> $LOCAL_DEV"
|
||||
|
||||
GUEST_IP=192.168.25.189
|
||||
HOST_PORT=8085
|
||||
GUEST_PORT=8085
|
||||
|
||||
# connections from outside
|
||||
sudo iptables -I FORWARD -o $LOCAL_DEV -d $GUEST_IP -j ACCEPT
|
||||
sudo iptables -t nat -I PREROUTING -p tcp --dport $HOST_PORT -j DNAT --to $GUEST_IP:$GUEST_PORT
|
||||
/usr/local/bin/virtweb_backend ux,
|
||||
```
|
||||
|
||||
* Theses rules can be persisted using `iptables-save` then, or using a libvirt hook.
|
||||
* Update Apparmor configuration:
|
||||
|
||||
|
||||
### Manual port forwarding with a LibVirt HOOK
|
||||
* Allow ip forwarding in the kernel: edit `/etc/sysctl.conf` and uncomment the following line:
|
||||
|
||||
```
|
||||
net.ipv4.ip_forward=1
|
||||
```bash
|
||||
sudo apparmor_parser -r /etc/apparmor.d/usr.sbin.libvirtd
|
||||
```
|
||||
|
||||
* To reload `sysctl` without reboot:
|
||||
|
||||
```
|
||||
sudo sysctl -p /etc/sysctl.conf
|
||||
```
|
||||
|
||||
* Get the following information, using the web ui or `virsh`:
|
||||
* The name of the target guest
|
||||
* The IP and port of the guest who will receive the connection
|
||||
* The port of the host that will be forwarded to the guest
|
||||
|
||||
* Stop the guest if its running, either using `virsh` or from the web ui
|
||||
|
||||
* Create or append the following content to the file `/etc/libvirt/hooks/qemu`:
|
||||
* Create VirtWeb hook. Set the following content inside `/etc/libvirt/hooks/network`:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
|
||||
# IMPORTANT: Change the "VM NAME" string to match your actual VM Name.
|
||||
# In order to create rules to other VMs, just duplicate the below block and configure
|
||||
# it accordingly.
|
||||
if [ "${1}" = "VM NAME" ]; then
|
||||
|
||||
# Update the following variables to fit your setup
|
||||
GUEST_IP=
|
||||
GUEST_PORT=
|
||||
HOST_PORT=
|
||||
|
||||
if [ "${2}" = "stopped" ] || [ "${2}" = "reconnect" ]; then
|
||||
/sbin/iptables -D FORWARD -o virbr0 -p tcp -d $GUEST_IP --dport $GUEST_PORT -j ACCEPT
|
||||
/sbin/iptables -t nat -D PREROUTING -p tcp --dport $HOST_PORT -j DNAT --to $GUEST_IP:$GUEST_PORT
|
||||
fi
|
||||
if [ "${2}" = "start" ] || [ "${2}" = "reconnect" ]; then
|
||||
/sbin/iptables -I FORWARD -o virbr0 -p tcp -d $GUEST_IP --dport $GUEST_PORT -j ACCEPT
|
||||
/sbin/iptables -t nat -I PREROUTING -p tcp --dport $HOST_PORT -j DNAT --to $GUEST_IP:$GUEST_PORT
|
||||
fi
|
||||
fi
|
||||
NAT_MODE=1 /usr/local/bin/virtweb_backend --storage /home/virtweb/storage --network-name "$1" --operation "$2" --sub-operation "$3"
|
||||
```
|
||||
|
||||
* Make the hook executable:
|
||||
* Make the script executable:
|
||||
|
||||
```bash
|
||||
sudo chmod +x /etc/libvirt/hooks/qemu
|
||||
sudo chmod +x /etc/libvirt/hooks/network
|
||||
```
|
||||
|
||||
* Restart the `libvirtd` service:
|
||||
* Restart `libvirtd` and `VirtWeb`:
|
||||
|
||||
```bash
|
||||
sudo systemctl restart libvirtd.service
|
||||
```
|
||||
|
||||
* Start the guest
|
||||
|
||||
|
||||
> Note: this guide is based on https://wiki.libvirt.org/Networking.html
|
||||
sudo systemctl restart libvirtd
|
||||
sudo systemctl restart virtweb
|
||||
```
|
||||
5146
virtweb_frontend/package-lock.json
generated
5146
virtweb_frontend/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -13,10 +13,28 @@ export interface DHCPConfig {
|
||||
hosts: DHCPHost[];
|
||||
}
|
||||
|
||||
export type NatSource =
|
||||
| { type: "interface"; name: string }
|
||||
| { type: "ip"; ip: string };
|
||||
|
||||
export type NatHostPort =
|
||||
| { type: "single"; port: number }
|
||||
| { type: "range"; start: number; end: number };
|
||||
|
||||
export interface NatEntry {
|
||||
protocol: "TCP" | "UDP" | "Both";
|
||||
host_ip: NatSource;
|
||||
host_port: NatHostPort;
|
||||
guest_ip: string;
|
||||
guest_port: number;
|
||||
comment?: string;
|
||||
}
|
||||
|
||||
export interface IpConfig {
|
||||
bridge_address: string;
|
||||
prefix: number;
|
||||
dhcp?: DHCPConfig;
|
||||
nat?: NatEntry[];
|
||||
}
|
||||
|
||||
export interface NetworkInfo {
|
||||
|
||||
@@ -21,6 +21,7 @@ export interface ServerConstraints {
|
||||
disk_size: LenConstraint;
|
||||
net_name_size: LenConstraint;
|
||||
net_title_size: LenConstraint;
|
||||
net_nat_comment_size: LenConstraint;
|
||||
dhcp_reservation_host_name: LenConstraint;
|
||||
nwfilter_name_size: LenConstraint;
|
||||
nwfilter_comment_size: LenConstraint;
|
||||
@@ -38,6 +39,9 @@ let config: ServerConfig | null = null;
|
||||
export interface ServerSystemInfo {
|
||||
hypervisor: HypervisorInfo;
|
||||
system: SystemInfo;
|
||||
components: SysComponent;
|
||||
disks: DiskInfo[];
|
||||
networks: NetworkInfo[];
|
||||
}
|
||||
|
||||
interface HypervisorInfo {
|
||||
@@ -76,10 +80,6 @@ interface SystemInfo {
|
||||
total_swap: number;
|
||||
free_swap: number;
|
||||
used_swap: number;
|
||||
components: SysComponent;
|
||||
users: [];
|
||||
disks: DiskInfo[];
|
||||
networks: NetworkInfo[];
|
||||
uptime: number;
|
||||
boot_time: number;
|
||||
load_average: SysLoadAverage;
|
||||
@@ -147,6 +147,12 @@ interface SysLoadAverage {
|
||||
fifteen: number;
|
||||
}
|
||||
|
||||
export interface NetworkHookStatus {
|
||||
installed: boolean;
|
||||
content: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export class ServerApi {
|
||||
/**
|
||||
* Get server configuration
|
||||
@@ -180,6 +186,18 @@ export class ServerApi {
|
||||
).data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get network hook status
|
||||
*/
|
||||
static async NetworkHookStatus(): Promise<NetworkHookStatus> {
|
||||
return (
|
||||
await APIClient.exec({
|
||||
method: "GET",
|
||||
uri: "/server/network_hook_status",
|
||||
})
|
||||
).data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get host supported vCPUs configurations
|
||||
*/
|
||||
|
||||
@@ -19,6 +19,7 @@ import { RouterLink } from "../widgets/RouterLink";
|
||||
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
|
||||
import { NetworkStatusWidget } from "../widgets/net/NetworkStatusWidget";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { NetworkHookStatusWidget } from "../widgets/net/NetworkHookStatusWidget";
|
||||
|
||||
export function NetworksListRoute(): React.ReactElement {
|
||||
const [list, setList] = React.useState<NetworkInfo[] | undefined>();
|
||||
@@ -54,6 +55,8 @@ function NetworksListRouteInner(p: {
|
||||
</RouterLink>
|
||||
}
|
||||
>
|
||||
<NetworkHookStatusWidget hiddenIfInstalled />
|
||||
|
||||
<TableContainer component={Paper}>
|
||||
<Table>
|
||||
<TableHead>
|
||||
|
||||
@@ -51,7 +51,7 @@ export function SysInfoRoute(): React.ReactElement {
|
||||
export function SysInfoRouteInner(p: {
|
||||
info: ServerSystemInfo;
|
||||
}): React.ReactElement {
|
||||
const sumDiskUsage = p.info.system.disks.reduce(
|
||||
const sumDiskUsage = p.info.disks.reduce(
|
||||
(prev, disk) => {
|
||||
return {
|
||||
used: prev.used + disk.total_space - disk.available_space,
|
||||
@@ -227,8 +227,8 @@ export function SysInfoRouteInner(p: {
|
||||
]}
|
||||
/>
|
||||
|
||||
<DiskDetailsTable disks={p.info.system.disks} />
|
||||
<NetworksDetailsTable networks={p.info.system.networks} />
|
||||
<DiskDetailsTable disks={p.info.disks} />
|
||||
<NetworksDetailsTable networks={p.info.networks} />
|
||||
</VirtWebRouteContainer>
|
||||
);
|
||||
}
|
||||
|
||||
30
virtweb_frontend/src/widgets/CopyToClipboard.tsx
Normal file
30
virtweb_frontend/src/widgets/CopyToClipboard.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import { ButtonBase } from "@mui/material";
|
||||
import { PropsWithChildren } from "react";
|
||||
import { useSnackbar } from "../hooks/providers/SnackbarProvider";
|
||||
|
||||
export function CopyToClipboard(
|
||||
p: PropsWithChildren<{ content: string }>
|
||||
): React.ReactElement {
|
||||
const snackbar = useSnackbar();
|
||||
|
||||
const copy = () => {
|
||||
navigator.clipboard.writeText(p.content);
|
||||
snackbar(`${p.content} copied to clipboard.`);
|
||||
};
|
||||
|
||||
return (
|
||||
<ButtonBase
|
||||
onClick={copy}
|
||||
style={{
|
||||
display: "inline-block",
|
||||
alignItems: "unset",
|
||||
textAlign: "unset",
|
||||
position: "relative",
|
||||
padding: "0px",
|
||||
}}
|
||||
disableRipple
|
||||
>
|
||||
{p.children}
|
||||
</ButtonBase>
|
||||
);
|
||||
}
|
||||
@@ -2,10 +2,14 @@ import { Grid, Paper, Typography } from "@mui/material";
|
||||
import React, { PropsWithChildren } from "react";
|
||||
|
||||
export function EditSection(
|
||||
p: { title?: string; actions?: React.ReactElement } & PropsWithChildren
|
||||
p: {
|
||||
title?: string;
|
||||
actions?: React.ReactElement;
|
||||
fullWidth?: boolean;
|
||||
} & PropsWithChildren
|
||||
): React.ReactElement {
|
||||
return (
|
||||
<Grid item sm={12} md={6}>
|
||||
<Grid item sm={12} md={p.fullWidth ? 12 : 6}>
|
||||
<Paper style={{ margin: "10px", padding: "10px" }}>
|
||||
{(p.title || p.actions) && (
|
||||
<span
|
||||
|
||||
@@ -128,6 +128,6 @@ function sanitizeMask(version: 4 | 6, mask?: string): number | undefined {
|
||||
if (version === 4) {
|
||||
return value < 0 || value > 32 ? 32 : value;
|
||||
} else {
|
||||
return value < 0 || value > 64 ? 64 : value;
|
||||
return value < 0 || value > 128 ? 128 : value;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,12 +4,14 @@ import DeleteIcon from "@mui/icons-material/Delete";
|
||||
import {
|
||||
Avatar,
|
||||
Button,
|
||||
Grid,
|
||||
IconButton,
|
||||
ListItem,
|
||||
ListItemAvatar,
|
||||
ListItemText,
|
||||
Paper,
|
||||
Tooltip,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { DHCPConfig, DHCPHost } from "../../api/NetworksApi";
|
||||
import { ServerApi } from "../../api/ServerApi";
|
||||
@@ -35,21 +37,29 @@ export function NetDHCPHostReservations(p: {
|
||||
|
||||
return (
|
||||
<>
|
||||
{p.dhcp.hosts.map((h, num) => (
|
||||
<HostReservationWidget
|
||||
key={num}
|
||||
{...p}
|
||||
onChange={() => {
|
||||
p.onChange?.(p.dhcp);
|
||||
}}
|
||||
host={h}
|
||||
onRemove={() => {
|
||||
p.dhcp.hosts.splice(num, 1);
|
||||
p.onChange?.(p.dhcp);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
|
||||
<Grid container>
|
||||
{p.dhcp.hosts.map((h, num) => (
|
||||
<Grid key={num} sm={12} md={6} item style={{ padding: "10px" }}>
|
||||
<HostReservationWidget
|
||||
key={num}
|
||||
{...p}
|
||||
onChange={() => {
|
||||
p.onChange?.(p.dhcp);
|
||||
}}
|
||||
host={h}
|
||||
onRemove={() => {
|
||||
p.dhcp.hosts.splice(num, 1);
|
||||
p.onChange?.(p.dhcp);
|
||||
}}
|
||||
/>
|
||||
</Grid>
|
||||
))}
|
||||
</Grid>
|
||||
{p.dhcp.hosts.length === 0 && (
|
||||
<Typography style={{ textAlign: "center" }}>
|
||||
You have not set any DHCP host reservations.
|
||||
</Typography>
|
||||
)}
|
||||
{p.editable && (
|
||||
<Button onClick={addHost}>Add new host reservation</Button>
|
||||
)}
|
||||
|
||||
311
virtweb_frontend/src/widgets/forms/NetNatConfiguration.tsx
Normal file
311
virtweb_frontend/src/widgets/forms/NetNatConfiguration.tsx
Normal file
@@ -0,0 +1,311 @@
|
||||
import DeleteIcon from "@mui/icons-material/Delete";
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Card,
|
||||
CardActions,
|
||||
CardContent,
|
||||
Grid,
|
||||
IconButton,
|
||||
Tooltip,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import React, { PropsWithChildren } from "react";
|
||||
import { NatEntry } from "../../api/NetworksApi";
|
||||
import { ServerApi } from "../../api/ServerApi";
|
||||
import { useConfirm } from "../../hooks/providers/ConfirmDialogProvider";
|
||||
import { IPInput } from "./IPInput";
|
||||
import { PortInput } from "./PortInput";
|
||||
import { RadioGroupInput } from "./RadioGroupInput";
|
||||
import { SelectInput } from "./SelectInput";
|
||||
import { TextInput } from "./TextInput";
|
||||
|
||||
export function NetNatConfiguration(p: {
|
||||
editable: boolean;
|
||||
nat: NatEntry[];
|
||||
nicsList: string[];
|
||||
onChange?: (nat: NatEntry[]) => void;
|
||||
version: 4 | 6;
|
||||
}): React.ReactElement {
|
||||
const confirm = useConfirm();
|
||||
|
||||
const addEntry = () => {
|
||||
p.nat.push({
|
||||
host_ip: {
|
||||
type: "ip",
|
||||
ip: p.version === 4 ? "10.0.0.1" : "fd00::",
|
||||
},
|
||||
host_port: { type: "single", port: 80 },
|
||||
guest_ip: p.version === 4 ? "10.0.0.100" : "fd00::",
|
||||
guest_port: 10,
|
||||
protocol: "TCP",
|
||||
});
|
||||
p.onChange?.(p.nat);
|
||||
};
|
||||
|
||||
const onDelete = async (idx: number) => {
|
||||
if (!(await confirm("Do you really want to delete this entry?"))) return;
|
||||
|
||||
p.nat.splice(idx, 1);
|
||||
p.onChange?.(p.nat);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{p.nat.map((e, num) => (
|
||||
<NatEntryForm
|
||||
key={num}
|
||||
{...p}
|
||||
entry={e}
|
||||
onChange={() => p.onChange?.(p.nat)}
|
||||
onDelete={() => onDelete(num)}
|
||||
/>
|
||||
))}
|
||||
|
||||
{p.nat.length === 0 && (
|
||||
<Typography style={{ textAlign: "center" }}>
|
||||
You have not set any NAT entry yet.
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
{p.editable && <Button onClick={addEntry}>Add a new entry</Button>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function NatEntryForm(p: {
|
||||
editable: boolean;
|
||||
version: 4 | 6;
|
||||
entry: NatEntry;
|
||||
onChange?: () => void;
|
||||
onDelete: () => void;
|
||||
nicsList: string[];
|
||||
}): React.ReactElement {
|
||||
const guestPortEnd =
|
||||
p.entry.host_port.type === "range"
|
||||
? p.entry.host_port.end - p.entry.host_port.start + p.entry.guest_port
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<Card style={{ margin: "30px" }} elevation={3}>
|
||||
<CardContent>
|
||||
<Grid container>
|
||||
<NATEntryProp>
|
||||
<SelectInput
|
||||
{...p}
|
||||
label="Protocol"
|
||||
options={[
|
||||
{ value: "TCP" },
|
||||
{ value: "UDP" },
|
||||
{ label: "TCP & UDP", value: "Both" },
|
||||
]}
|
||||
value={p.entry.protocol}
|
||||
onValueChange={(v) => {
|
||||
p.entry.protocol = v as any;
|
||||
p.onChange?.();
|
||||
}}
|
||||
/>
|
||||
</NATEntryProp>
|
||||
<NATEntryProp>
|
||||
<TextInput
|
||||
{...p}
|
||||
label="Comment"
|
||||
value={p.entry.comment}
|
||||
onValueChange={(v) => {
|
||||
p.entry.comment = v;
|
||||
p.onChange?.();
|
||||
}}
|
||||
size={ServerApi.Config.constraints.net_nat_comment_size}
|
||||
/>
|
||||
</NATEntryProp>
|
||||
|
||||
{/* Host conf */}
|
||||
<NATEntryProp label="Host configuration">
|
||||
<SelectInput
|
||||
{...p}
|
||||
label="Host IP address specification"
|
||||
options={[
|
||||
{
|
||||
label: "Specific IP",
|
||||
value: "ip",
|
||||
description: "Use a pre-defined IP address",
|
||||
},
|
||||
{
|
||||
label: "Network interface",
|
||||
value: "interface",
|
||||
description:
|
||||
"Use active IP addresses on the selected network interface during network startup to determine host adddress",
|
||||
},
|
||||
]}
|
||||
value={p.entry.host_ip.type}
|
||||
onValueChange={(v) => {
|
||||
p.entry.host_ip.type = v as any;
|
||||
p.onChange?.();
|
||||
}}
|
||||
/>
|
||||
|
||||
{p.entry.host_ip.type === "ip" && (
|
||||
<IPInput
|
||||
{...p}
|
||||
label="Host IP address"
|
||||
value={p.entry.host_ip.ip}
|
||||
onValueChange={(v) => {
|
||||
if (p.entry.host_ip.type === "ip") p.entry.host_ip.ip = v!;
|
||||
p.onChange?.();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{p.entry.host_ip.type === "interface" && (
|
||||
<>
|
||||
{p.editable && (
|
||||
<Alert severity="warning" style={{ margin: "10px 0px" }}>
|
||||
Warning! All IP addresses may not be inferred on reboot due
|
||||
to the fact that the network hook might be executed before
|
||||
the network interfaces are fully configured. This might lead
|
||||
to incomplete ports exposition!
|
||||
</Alert>
|
||||
)}
|
||||
<SelectInput
|
||||
{...p}
|
||||
label="Network interface"
|
||||
value={p.entry.host_ip.name}
|
||||
options={p.nicsList.map((n) => {
|
||||
return {
|
||||
value: n,
|
||||
};
|
||||
})}
|
||||
onValueChange={(v) => {
|
||||
if (p.entry.host_ip.type === "interface")
|
||||
p.entry.host_ip.name = v!;
|
||||
p.onChange?.();
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</NATEntryProp>
|
||||
|
||||
<NATEntryProp label="Target guest configuration">
|
||||
<IPInput
|
||||
{...p}
|
||||
label="Guest IP"
|
||||
value={p.entry.guest_ip}
|
||||
onValueChange={(v) => {
|
||||
p.entry.guest_ip = v!;
|
||||
p.onChange?.();
|
||||
}}
|
||||
/>
|
||||
</NATEntryProp>
|
||||
|
||||
<NATEntryProp>
|
||||
<RadioGroupInput
|
||||
{...p}
|
||||
options={[
|
||||
{ label: "Single port", value: "single" },
|
||||
{ label: "Range of ports", value: "range" },
|
||||
]}
|
||||
value={p.entry.host_port.type}
|
||||
onValueChange={(v) => {
|
||||
p.entry.host_port.type = v as any;
|
||||
p.onChange?.();
|
||||
}}
|
||||
/>
|
||||
|
||||
{p.entry.host_port.type === "single" && (
|
||||
<PortInput
|
||||
{...p}
|
||||
label="Host port"
|
||||
value={p.entry.host_port.port}
|
||||
onChange={(v) => {
|
||||
if (p.entry.host_port.type === "single")
|
||||
p.entry.host_port.port = v!;
|
||||
p.onChange?.();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{p.entry.host_port.type === "range" && (
|
||||
<div style={{ display: "flex" }}>
|
||||
<PortInput
|
||||
{...p}
|
||||
label="Host port start"
|
||||
value={p.entry.host_port.start}
|
||||
onChange={(v) => {
|
||||
if (p.entry.host_port.type === "range")
|
||||
p.entry.host_port.start = v!;
|
||||
p.onChange?.();
|
||||
}}
|
||||
/>
|
||||
<PortSpacer />
|
||||
<PortInput
|
||||
{...p}
|
||||
label="Host port end"
|
||||
value={p.entry.host_port.end}
|
||||
onChange={(v) => {
|
||||
if (p.entry.host_port.type === "range")
|
||||
p.entry.host_port.end = v!;
|
||||
p.onChange?.();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</NATEntryProp>
|
||||
|
||||
<NATEntryProp>
|
||||
<div style={{ display: "flex", height: "100%", alignItems: "end" }}>
|
||||
<PortInput
|
||||
{...p}
|
||||
label={`Guest port ${guestPortEnd ? "start" : ""}`}
|
||||
value={p.entry.guest_port}
|
||||
onChange={(v) => {
|
||||
p.entry.guest_port = v!;
|
||||
p.onChange?.();
|
||||
}}
|
||||
/>
|
||||
{guestPortEnd && <PortSpacer />}
|
||||
{guestPortEnd && (
|
||||
<PortInput
|
||||
editable={false}
|
||||
label={`Guest port end`}
|
||||
value={guestPortEnd}
|
||||
onChange={(v) => {
|
||||
p.entry.guest_port = v!;
|
||||
p.onChange?.();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</NATEntryProp>
|
||||
</Grid>
|
||||
</CardContent>
|
||||
<CardActions>
|
||||
{p.editable && (
|
||||
<Tooltip title="Remove the entry">
|
||||
<IconButton color="error" onClick={p.onDelete}>
|
||||
<DeleteIcon />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
</CardActions>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function NATEntryProp(
|
||||
p: PropsWithChildren<{ label?: string }>
|
||||
): React.ReactElement {
|
||||
return (
|
||||
<Grid item sm={12} md={6} style={{ padding: "20px" }}>
|
||||
{p.label && (
|
||||
<Typography variant="h6" style={{ marginBottom: "10px" }}>
|
||||
{p.label}
|
||||
</Typography>
|
||||
)}
|
||||
{p.children}
|
||||
</Grid>
|
||||
);
|
||||
}
|
||||
|
||||
function PortSpacer(): React.ReactElement {
|
||||
return <span style={{ width: "20px" }}></span>;
|
||||
}
|
||||
@@ -14,6 +14,7 @@ export function PortInput(p: {
|
||||
onValueChange={(v) => {
|
||||
p.onChange?.(sanitizePort(v));
|
||||
}}
|
||||
checkValue={(v) => Number(v) <= 65535}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
40
virtweb_frontend/src/widgets/forms/RadioGroupInput.tsx
Normal file
40
virtweb_frontend/src/widgets/forms/RadioGroupInput.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
import {
|
||||
RadioGroup,
|
||||
FormControlLabel,
|
||||
Radio,
|
||||
FormControl,
|
||||
FormLabel,
|
||||
} from "@mui/material";
|
||||
|
||||
interface RadioGroupOption {
|
||||
label: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export function RadioGroupInput(p: {
|
||||
editable: boolean;
|
||||
label?: string;
|
||||
options: RadioGroupOption[];
|
||||
value: string;
|
||||
onValueChange: (v: string) => void;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<FormControl>
|
||||
{p.label && <FormLabel>{p.label}</FormLabel>}
|
||||
<RadioGroup
|
||||
row
|
||||
value={p.value}
|
||||
onChange={(_ev, v) => p.onValueChange?.(v)}
|
||||
>
|
||||
{p.options.map((o) => (
|
||||
<FormControlLabel
|
||||
disabled={!p.editable}
|
||||
value={o.value}
|
||||
control={<Radio />}
|
||||
label={o.label}
|
||||
/>
|
||||
))}
|
||||
</RadioGroup>
|
||||
</FormControl>
|
||||
);
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import { TextInput } from "./TextInput";
|
||||
|
||||
export interface SelectOption {
|
||||
value?: string;
|
||||
label: string;
|
||||
label?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
@@ -23,9 +23,10 @@ export function SelectInput(p: {
|
||||
if (!p.editable && !p.value) return <></>;
|
||||
|
||||
if (!p.editable) {
|
||||
const value = p.options.find((o) => o.value === p.value)?.label;
|
||||
const value = p.options.find((o) => o.value === p.value)?.label ?? p.value;
|
||||
return <TextInput label={p.label} editable={p.editable} value={value} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<FormControl fullWidth variant="standard" style={{ marginBottom: "15px" }}>
|
||||
<InputLabel>{p.label}</InputLabel>
|
||||
@@ -41,7 +42,7 @@ export function SelectInput(p: {
|
||||
style={{ fontStyle: e.value === undefined ? "italic" : undefined }}
|
||||
>
|
||||
<div>
|
||||
{e.label}
|
||||
{e.label ?? e.value}
|
||||
{e.description && (
|
||||
<Typography
|
||||
component={"div"}
|
||||
|
||||
@@ -68,15 +68,13 @@ export function VMSelectIsoInput(p: {
|
||||
p.onChange(p.attachedISOs);
|
||||
}
|
||||
}}
|
||||
options={[
|
||||
{ label: "None", value: undefined },
|
||||
...p.isoList.map((i) => {
|
||||
options={p.isoList.map((i) => {
|
||||
return {
|
||||
label: `${i.filename} ${filesize(i.size)}`,
|
||||
value: i.filename,
|
||||
};
|
||||
}),
|
||||
]}
|
||||
})
|
||||
}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -8,13 +8,14 @@ import { useConfirm } from "../../hooks/providers/ConfirmDialogProvider";
|
||||
import { useSnackbar } from "../../hooks/providers/SnackbarProvider";
|
||||
import { AsyncWidget } from "../AsyncWidget";
|
||||
import { TabsWidget } from "../TabsWidget";
|
||||
import { XMLAsyncWidget } from "../XMLWidget";
|
||||
import { EditSection } from "../forms/EditSection";
|
||||
import { IPInput } from "../forms/IPInput";
|
||||
import { NetDHCPHostReservations } from "../forms/NetDHCPHostReservations";
|
||||
import { NetNatConfiguration } from "../forms/NetNatConfiguration";
|
||||
import { ResAutostartInput } from "../forms/ResAutostartInput";
|
||||
import { SelectInput } from "../forms/SelectInput";
|
||||
import { TextInput } from "../forms/TextInput";
|
||||
import { NetDHCPHostReservations } from "../forms/NetDHCPHostReservations";
|
||||
import { XMLAsyncWidget } from "../XMLWidget";
|
||||
|
||||
interface DetailsProps {
|
||||
net: NetworkInfo;
|
||||
@@ -223,7 +224,7 @@ function NetworkDetailsTabGeneral(p: DetailsInnerProps): React.ReactElement {
|
||||
function NetworkDetailsTabIPv4(p: DetailsInnerProps): React.ReactElement {
|
||||
return (
|
||||
<IPSection
|
||||
editable={p.editable}
|
||||
{...p}
|
||||
config={p.net.ip_v4}
|
||||
onChange={(c) => {
|
||||
p.net.ip_v4 = c;
|
||||
@@ -237,7 +238,7 @@ function NetworkDetailsTabIPv4(p: DetailsInnerProps): React.ReactElement {
|
||||
function NetworkDetailsTabIPv6(p: DetailsInnerProps): React.ReactElement {
|
||||
return (
|
||||
<IPSection
|
||||
editable={p.editable}
|
||||
{...p}
|
||||
config={p.net.ip_v6}
|
||||
onChange={(c) => {
|
||||
p.net.ip_v6 = c;
|
||||
@@ -253,6 +254,7 @@ function IPSection(p: {
|
||||
config?: IpConfig;
|
||||
onChange: (c: IpConfig | undefined) => void;
|
||||
version: 4 | 6;
|
||||
nicsList: string[];
|
||||
}): React.ReactElement {
|
||||
const confirm = useConfirm();
|
||||
|
||||
@@ -260,7 +262,7 @@ function IPSection(p: {
|
||||
if (!!p.config) {
|
||||
if (
|
||||
!(await confirm(
|
||||
`Do you really want to disable IPv${p.version} on this network?`
|
||||
`Do you really want to disable IPv${p.version} on this network? Specific configuration will be deleted!`
|
||||
))
|
||||
)
|
||||
return;
|
||||
@@ -275,8 +277,8 @@ function IPSection(p: {
|
||||
});
|
||||
};
|
||||
|
||||
const toggleDHCP = (v: boolean) => {
|
||||
if (v)
|
||||
const toggleDHCP = async (v: boolean) => {
|
||||
if (v) {
|
||||
p.config!.dhcp =
|
||||
p.version === 4
|
||||
? {
|
||||
@@ -285,7 +287,32 @@ function IPSection(p: {
|
||||
hosts: [],
|
||||
}
|
||||
: { start: "fd00::100", end: "fd00::f00", hosts: [] };
|
||||
else p.config!.dhcp = undefined;
|
||||
} else {
|
||||
if (
|
||||
!(await confirm(
|
||||
`Do you really want to disable DHCPv${p.version} on this network? Specific configuration will be deleted!`
|
||||
))
|
||||
)
|
||||
return;
|
||||
p.config!.dhcp = undefined;
|
||||
}
|
||||
|
||||
p.onChange?.(p.config);
|
||||
};
|
||||
|
||||
const toggleNAT = async (v: boolean) => {
|
||||
if (v) {
|
||||
p.config!.nat = [];
|
||||
} else {
|
||||
if (
|
||||
(p.config?.nat?.length ?? 0 > 0) &&
|
||||
!(await confirm(
|
||||
`Do you really want to disable IPv${p.version} NAT port forwarding on this network? Specific configuration will be deleted!`
|
||||
))
|
||||
)
|
||||
return;
|
||||
p.config!.nat = undefined;
|
||||
}
|
||||
|
||||
p.onChange?.(p.config);
|
||||
};
|
||||
@@ -373,7 +400,7 @@ function IPSection(p: {
|
||||
)}
|
||||
|
||||
{p.config?.dhcp && (p.editable || p.config.dhcp.hosts.length > 0) && (
|
||||
<EditSection title="DHCP hosts reservations">
|
||||
<EditSection title="DHCP hosts reservations" fullWidth>
|
||||
<NetDHCPHostReservations
|
||||
{...p}
|
||||
dhcp={p.config.dhcp}
|
||||
@@ -384,6 +411,31 @@ function IPSection(p: {
|
||||
/>
|
||||
</EditSection>
|
||||
)}
|
||||
|
||||
{p.config && (p.editable || p.config.nat) && (
|
||||
<EditSection
|
||||
title={`NAT v${p.version} ports redirection`}
|
||||
fullWidth
|
||||
actions={
|
||||
<Checkbox
|
||||
disabled={!p.editable}
|
||||
checked={!!p.config.nat}
|
||||
onChange={(_ev, val) => toggleNAT(val)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{p.config.nat && (
|
||||
<NetNatConfiguration
|
||||
{...p}
|
||||
nat={p.config.nat}
|
||||
onChange={(n) => {
|
||||
p.config!.nat = n;
|
||||
p.onChange?.(p.config);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</EditSection>
|
||||
)}
|
||||
</Grid>
|
||||
);
|
||||
}
|
||||
|
||||
110
virtweb_frontend/src/widgets/net/NetworkHookStatusWidget.tsx
Normal file
110
virtweb_frontend/src/widgets/net/NetworkHookStatusWidget.tsx
Normal file
@@ -0,0 +1,110 @@
|
||||
import { Alert } from "@mui/material";
|
||||
import React, { PropsWithChildren } from "react";
|
||||
import { NetworkHookStatus, ServerApi } from "../../api/ServerApi";
|
||||
import { AsyncWidget } from "../AsyncWidget";
|
||||
import { CopyToClipboard } from "../CopyToClipboard";
|
||||
|
||||
export function NetworkHookStatusWidget(p: {
|
||||
hiddenIfInstalled: boolean;
|
||||
}): React.ReactElement {
|
||||
const [status, setStatus] = React.useState<NetworkHookStatus | undefined>();
|
||||
|
||||
const load = async () => {
|
||||
setStatus(await ServerApi.NetworkHookStatus());
|
||||
};
|
||||
|
||||
return (
|
||||
<AsyncWidget
|
||||
loadKey={1}
|
||||
errMsg="Failed to get network status!"
|
||||
ready={!!status}
|
||||
load={load}
|
||||
build={() => <NetworkHookStatusWidgetInner {...p} status={status!} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function NetworkHookStatusWidgetInner(p: {
|
||||
status: NetworkHookStatus;
|
||||
hiddenIfInstalled: boolean;
|
||||
}): React.ReactElement {
|
||||
if (p.status.installed && p.hiddenIfInstalled) return <></>;
|
||||
if (p.status.installed)
|
||||
return (
|
||||
<Alert
|
||||
variant="outlined"
|
||||
severity="success"
|
||||
style={{ margin: "20px 0px" }}
|
||||
>
|
||||
The network hook has been installed on this system.
|
||||
</Alert>
|
||||
);
|
||||
|
||||
const makeExecutable = `chmod +x ${p.status.path}`;
|
||||
|
||||
return (
|
||||
<Alert variant="outlined" severity="warning" style={{ margin: "20px 0px" }}>
|
||||
The network hook has not been detected on this system. It must be
|
||||
installed in order to expose ports from virtual machines through NAT on
|
||||
the network.
|
||||
<br />
|
||||
<br />
|
||||
In order to install it, please create a file named
|
||||
<CopyToClipboard content={p.status.path}>
|
||||
<InlineCode>{p.status.path}</InlineCode> with the following
|
||||
</CopyToClipboard>
|
||||
content:
|
||||
<br />
|
||||
<CopyToClipboard content={p.status.content}>
|
||||
<CodeBlock>{p.status.content}</CodeBlock>
|
||||
</CopyToClipboard>
|
||||
<br />
|
||||
Make sure that the created file is executable :
|
||||
<br />
|
||||
<CopyToClipboard content={makeExecutable}>
|
||||
<CodeBlock>{makeExecutable}</CodeBlock>
|
||||
</CopyToClipboard>
|
||||
<br />
|
||||
You will need then to restart both <InlineCode>
|
||||
libvirtd
|
||||
</InlineCode> and <InlineCode>VirtWeb</InlineCode>.
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
function InlineCode(p: PropsWithChildren): React.ReactElement {
|
||||
return (
|
||||
<code
|
||||
style={{
|
||||
display: "inline-block",
|
||||
backgroundColor: "black",
|
||||
color: "white",
|
||||
wordBreak: "break-all",
|
||||
wordWrap: "break-word",
|
||||
whiteSpace: "pre-wrap",
|
||||
padding: "0px 7px",
|
||||
borderRadius: "5px",
|
||||
}}
|
||||
>
|
||||
{p.children}
|
||||
</code>
|
||||
);
|
||||
}
|
||||
|
||||
function CodeBlock(p: PropsWithChildren): React.ReactElement {
|
||||
return (
|
||||
<pre
|
||||
style={{
|
||||
backgroundColor: "black",
|
||||
color: "white",
|
||||
wordBreak: "break-all",
|
||||
wordWrap: "break-word",
|
||||
whiteSpace: "pre-wrap",
|
||||
padding: "10px",
|
||||
borderRadius: "5px",
|
||||
}}
|
||||
>
|
||||
{p.children}
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user