Compare commits

...

96 Commits

Author SHA1 Message Date
wenjie
a8d6d61034 Merge pull request #131 from S33G/feature/mocked-authentication-for-dev
Mocked NanoKVM Login Page for Development
2024-11-15 10:38:23 +08:00
wj-xiao
a0f0699cdc update i18n: add loginButtonText 2024-11-15 10:35:49 +08:00
wenjie
97b9929374 Merge pull request #133 from S33G/improve-login-button-text
Improve login button text
2024-11-15 10:17:54 +08:00
wj-xiao
74a303bd5c support h264 2024-11-06 18:43:16 +08:00
wenjie
b7afc27f44 Merge pull request #132 from S33G/fix-login-title
Fix login title font
2024-11-06 14:30:38 +08:00
wenjie
a3cda13eea Merge pull request #129 from S33G/patch-1
Improve English locales
2024-11-06 14:24:45 +08:00
s33g
fdb7e5cfd0 Improve login button text 2024-11-05 23:57:24 +00:00
s33g
ed5621cfdd Fix login title 2024-11-05 23:51:32 +00:00
seeg
d923c82afb Update en.ts 2024-11-05 23:48:07 +00:00
s33g
7e976e069f Add mocks to remove the need for a physical device 2024-11-05 23:28:02 +00:00
seeg
33d7b7b259 Improve English locales
Improved a few English locale's to slightly improve the user experience
2024-11-05 21:26:36 +00:00
wenjie
42afe86e16 Merge pull request #123 from albertxiao/main
Add indonesia language support
2024-11-04 15:47:34 +08:00
Albert Xiao
a97903bbf0 Add indonesia language support 2024-11-02 01:23:51 +07:00
wenjie
285fc53784 Merge pull request #112 from stypr/patch-1
Prevent malicious file download on tailscale
2024-10-21 09:50:59 +08:00
stypr
cbb371fb78 Update tailscale.go to prevent malicious file download
If the network is compromised and `cdn.sipeed.com` is redirected to attacker's domain, malicious file can be deployed onto NanoKVM since it's transferred over https. It would be nice to just keep this as https since CDN already supports https at the moment.
2024-10-20 20:05:12 +09:00
Caize Wu
bcfa09b03e Update README.md 2024-10-18 10:02:25 +08:00
wj-xiao
df69d50ff0 Some optimizations
- refactor config
- fix updating lib
- fix resting hid
- optimize the update process
2024-10-17 11:56:42 +08:00
wenjie
888d0db5fa Merge pull request #108 from click0/main
Russian translation corrected and add Ukrainian language support.
2024-10-16 14:57:27 +08:00
wenjie
4b7a7d68eb Merge pull request #107 from Civil/refactoring
Slightly refactor nanokvm code
2024-10-16 14:57:11 +08:00
vlad11
9776508b53 Add Ukrainian language support.
Signed-off-by: vlad11 <admin@support.od.ua>
2024-10-15 21:42:38 +03:00
vlad11
2ad607c64d Russian translation corrected.
Signed-off-by: vlad11 <admin@support.od.ua>
2024-10-15 21:27:36 +03:00
wenjie
1f1341659e Merge pull request #106 from zucht/main
Add Dutch language support
2024-10-14 09:55:35 +08:00
Vladimir Smirnov
a58227910b Slightly refactor nanokvm code
* Add ability to properly configure logrus (e.x. specify output file)
 * Make the code slightly more ideomatic (sort imports, etc)
 * Replace some of the shell calls with equivalent native code
 * Fix update process
 * Improve error handling (handle 2 previously unhandled errors)
 * Add locking for HID operations and make a HID-operations struct a singleton
2024-10-13 18:41:04 +02:00
zucht
d775371fe0 Add Dutch language support 2024-10-13 18:27:08 +02:00
zucht
5ac348a75b Add Dutch language support 2024-10-13 18:26:30 +02:00
wj-xiao
726cd915cc sort languages 2024-10-10 10:24:00 +08:00
wenjie
342ed33fe7 Merge pull request #96 from Amplificator/main
Add Danish language support
2024-10-10 10:02:25 +08:00
wenjie
ca9f71d145 Merge pull request #95 from masa23/add_japanese
Add Japanese language support
2024-10-10 10:02:04 +08:00
wenjie
1f0d3b82c3 Merge branch 'main' into add_japanese 2024-10-10 10:01:51 +08:00
wenjie
079be103ec Merge pull request #93 from czipis/main
Add Czech language support
2024-10-10 10:01:21 +08:00
Martin L. R.
b78df7908f Add Danish language support 2024-10-09 22:14:25 +02:00
czipis
fcb61d257b fix missing export 2024-10-09 16:03:58 +02:00
Masa23
2796296418 Add Japanese language support 2024-10-09 20:59:51 +09:00
czipis
9f83291a8d fix typo 2024-10-09 12:56:52 +02:00
czipis
8ae4e48857 Add Czech language support 2024-10-09 09:58:01 +02:00
wj-xiao
dc10e492df update package micromatch 2024-10-08 17:38:53 +08:00
wj-xiao
49a04da35a update packages 2024-10-08 17:30:49 +08:00
wenjie
082a29a671 Create LICENSE 2024-10-08 17:16:19 +08:00
wj-xiao
3b2e142657 create server 2024-10-08 17:00:18 +08:00
wj-xiao
2f7cdf78c5 refactor some api and language key 2024-10-08 16:15:11 +08:00
wenjie
611ceae7da Merge pull request #81 from alekitopi/main
Add Spanish language support
2024-10-08 09:52:17 +08:00
Alejandro Q
600f86da29 Removed typo 2024-10-03 18:16:39 +02:00
Alejandro Q
637b9af964 Add Spanish language support 2024-10-03 18:03:44 +02:00
wenjie
e82271a6b9 Merge pull request #70 from skidoodle/main
Add Hungarian language support
2024-09-29 09:43:54 +08:00
wenjie
629b0ba39d Merge branch 'main' into main 2024-09-29 09:43:47 +08:00
wenjie
a693eaf212 Merge pull request #69 from ptrinh/patch-2
Add Vietnamese language support
2024-09-29 09:42:36 +08:00
wenjie
3365459d97 Merge pull request #68 from ptrinh/patch-1
Add Vietnamese translation
2024-09-29 09:42:22 +08:00
BuGu
088ee2ec7a Merge branch 'main' of https://github.com/sipeed/NanoKVM 2024-09-27 18:39:02 +08:00
BuGu
82932e5ba8 Update README.md 2024-09-27 18:38:34 +08:00
BuGu
3df064f39e Update README_ZH.md 2024-09-27 18:38:03 +08:00
skidoodle
cf0f63d69a Add Hungarian language support 2024-09-26 23:07:17 +02:00
P Trinh
69c72bc236 Add Vietnamese language support 2024-09-27 00:47:05 +08:00
P Trinh
e8b49238d3 Add Vietnamese translation 2024-09-27 00:43:13 +08:00
wj-xiao
cfe8172364 Optimize some code
- add support for right alt
- show message when image mounting failed
- rename virtual-usb to virtual-disk
- update mjpeg stream url
2024-09-25 10:34:11 +08:00
wenjie
46c41ff414 Merge pull request #65 from SuperKali/main
Add support for Italian language
2024-09-25 09:41:30 +08:00
SuperKali
f6e03d0abc Add support for Italian language 2024-09-24 07:46:46 +00:00
wenjie
a976f677ad Merge pull request #64 from matu6968/main
Add Polish language to frontend (fix translation issues if found)
2024-09-24 10:04:02 +08:00
wenjie
bed1b39ed7 Merge branch 'main' into main 2024-09-24 10:03:47 +08:00
wenjie
95584d5f68 Merge pull request #60 from junglemusic/main
Fixed the wording of some german translations and added entry to actually choose the "de" option.
2024-09-24 10:00:52 +08:00
matik
ef898bf8a6 fix tiny translation error 2024-09-23 20:45:15 +02:00
matu6968
063ce2ad33 add polish language support (excuse me for poor translation if any found) 2024-09-23 20:38:50 +02:00
matu6968
1474330ded add polish language support (excuse me for poor translation if any found) 2024-09-23 20:37:31 +02:00
Caize Wu
21972e4c62 Update README.md 2024-09-23 11:33:45 +08:00
junglemusic
cf56403f86 Update de.ts to fix wording
Fixed some wording for a few entries. Also the const = de {} string in the first line.
2024-09-21 07:20:39 +02:00
junglemusic
68806308c0 Update languages.ts to include German translation 2024-09-21 07:06:45 +02:00
wenjie
34bd10c1e4 Merge pull request #48 from junglemusic/main
Create de.ts
2024-09-18 09:51:35 +08:00
junglemusic
254a3103a3 Create de.ts
added german translation
2024-09-13 19:57:00 +02:00
BuGu
5ad6327999 Merge branch 'main' of https://github.com/sipeed/NanoKVM 2024-09-10 11:06:23 +08:00
BuGu
a0ff551c53 Update readme 2024-09-10 11:06:18 +08:00
wj-xiao
f02b9ce599 refactor desktop page 2024-09-09 17:27:55 +08:00
wj-xiao
e34f085976 update menu
- update frame detect icons
- rename mouse translation
- support pasting from local to remote
2024-09-06 10:54:53 +08:00
wenjie
eb772ae33d Merge pull request #39 from polyzium/main
Implement fit to window
2024-09-06 09:59:43 +08:00
polyzium
6f83b756c2 Implement fit to window
Implements the feature as per #20
(https://github.com/sipeed/NanoKVM/issues/20#issue-2486746749)
2024-09-05 19:55:19 +03:00
wenjie
81dc0e0f71 Merge pull request #30 from lonerkim/translation
Translation
2024-09-02 13:52:19 +08:00
lonerkim
666ace3d3b Create ko.ts 2024-09-01 01:17:53 +09:00
lonerkim
853d568828 Update languages.ts 2024-09-01 00:58:06 +09:00
wj-xiao
462b3427f5 update virtual keyboard 2024-08-30 15:16:43 +08:00
wj-xiao
618498f7b0 update menu
- refactor tailscale
- update terminal icon
- update virtual devices icon
- rename some files
2024-08-30 10:47:06 +08:00
wj-xiao
aded40445b Support developing in local 2024-08-27 15:40:42 +08:00
wj-xiao
ef84874b99 update web README.md 2024-08-26 16:16:18 +08:00
wj-xiao
9c336dbda4 optimizing i18n and language setting 2024-08-26 14:15:35 +08:00
wenjie
b017338f05 Merge pull request #15 from polyzium/main
Quality of life changes
2024-08-26 10:30:26 +08:00
polyzium
5275952819 Fix font in the keyboard header 2024-08-23 17:28:50 +03:00
polyzium
62e8ab2ac8 Translate "Keyboard" in the kbd header bar 2024-08-23 17:28:50 +03:00
polyzium
655227e270 Add generic 104 key layout for virtual kbd 2024-08-23 17:28:50 +03:00
polyzium
8b413344e0 Add Russian language 2024-08-23 17:28:50 +03:00
BuGu
60b4df58f1 update readme 2024-08-22 15:40:52 +08:00
wj-xiao
8067a0e348 fix getting image mount status 2024-08-22 15:13:47 +08:00
wj-xiao
ea39c024ac - update axios to 1.7.4
- update menu bar: add tips on how to upload image
- optimizing i18n code
2024-08-22 14:54:07 +08:00
wenjie
aae370fc2b Merge pull request #10 from Stoufiler/add-fr-language
Add french language, use switch case instead of if's, correct one typo
2024-08-19 10:16:35 +08:00
Stoufiler
74a8c9ee42 Add french language, use switch case instead of if's, correct one typo 2024-08-17 20:12:55 +02:00
Caize Wu
dddf3de8db Update README_ZH.md 2024-08-09 20:22:41 +08:00
Caize Wu
4c4aa4270e Update README.md 2024-08-09 20:21:23 +08:00
wj-xiao
a21159aaff create web 2024-08-09 19:45:45 +08:00
Z2Z-GuGu
1e3c131e0d Update readme doc 2024-07-08 10:21:13 +08:00
Z2Z-GuGu
a037767f77 update readme 2024-07-03 19:00:01 +08:00
231 changed files with 23010 additions and 8 deletions

19
.gitignore vendored Normal file
View File

@@ -0,0 +1,19 @@
*.log
pnpm-debug.log*
web/node_modules
web/dist
web/web
.DS_Store
*.local
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
.idea
.vscode
NanoKVM-Server

674
LICENSE Normal file
View File

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

View File

@@ -17,6 +17,15 @@ English | [中文](./README_ZH.md)
> Your NanoKVM Power by RISC-V !
> If you have any issues or suggestions, creating issue here, or tell us with [MaixHub Discussion](https://maixhub.com/discussion/nanokvm).
## Opensource & Contribution & Shipping
The star is coming to 2K! We will organize and opensource backend source code in Mid October!(and it is also the time all preoreders (before 10.1) ship out)
### Update 10.18
We have opensourced the backend code in 10.8, and thank you for Civil PR it immediately, we will give you newest NanoKVM-PCIe as a reward!
The mid-Oct batch is starting testing and packaging, most order before 10.1 will ship out next and next next week.
The aliexpress shipping date is change to Dec since 10.1, it is a conservative delivery time. the order in Oct. should send out during 11.15~12.15.
## Introduction
@@ -36,15 +45,16 @@ The NanoKVM Full is a full version with a sophisticated case and complete access
| Video encoding | MJPEG, H264(developing) | MJPEG, H264(developing) | MJPEG, H264 |
| Video delay | 90~230ms | 90~230ms | 100~230ms |
| UEFI/BIOS | ✓ | ✓ | ✓ |
| Keyboard and Mouse<br>Virtual HID | ✓ | ✓ | ✓ |
| USB storage <br> Virtual CD-ROM | ✓ | ✓ | ✓ |
| Virtual HID | ✓ | ✓ | ✓ |
| Virtual CD-ROM | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ |
| Wake-on-LAN | ✓ | ✓ | ✓ |
| ETH | 100M/10M | 100M/10M | 1000M/100M/10M |
| ATX power control | None,Users can connect by their own | USB interface IO control board | RJ-45 interface IO control board |
| OLED | None,Users can connect by their own | 128x64 0.96" white | 128x32 0.91" white |
| UART | 2 | 2 | 1 |
| TF Card | None | ✓ | ✓ |
| Expansion | None | WiFi or PoE | WiFi/LTE |
| Expansion | None | PoE | WiFi/LTE |
| Power consumption | 0.2A@5V | 0.2A@5V | Peak 2.6A@5V |
| Power input | PC USB can be powered | PC USB or auxiliary power supply | DC 5V 3A power supply is required |
| Cooling | Silent fanless | Silent fanless | Fan cooling |
@@ -60,9 +70,18 @@ The NanoKVM Lite is constructed by the LicheeRV Nano and HDMItoCSI board, and th
The NanoKVM image is built on LicheeRV Nano SDK and MaixCDK, and is compatible with materials that use the LicheeRV Nano, opposite the KVM software cannot be used with the LicheeRV Nano or other SG2002 products. If you would like to build an HDMI input application on LicheeRV Nano or MaixCam, please contact us for technical support.
+ [HDMItoCSI Schematic](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_B_30131.pdf)
Note: Out of the 256MB memory in SG2002, 105MB is currently allocated for the multimedia subsystem, which NanoKVM will use for video image acquisition and processing
+ [NanoKVM-A Schematic](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_A_30111.pdf)
+ [NanoKVM-B Schematic](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_HDMI_MIPI_31011.pdf)
+ [NanoKVM img](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
## Where to buy
* [Aliexpress(global except USA&Russia)](https://www.aliexpress.com/item/1005007369816019.html)
* [淘宝](https://item.taobao.com/item.htm?id=811206560480)
* [Preorder (anyother country that not support in Aliexpress or Taobao)](https://sipeed.com/nanokvm)
## Community

View File

@@ -36,15 +36,16 @@ NanoKVM Full 为完整版配置,带精致外壳和完整配件,内置开机
| 视频编码 | MJPEG, H264(developing) | MJPEG, H264(developing) | MJPEG, H264 |
| 视频延迟 | 90~230ms | 90~230ms | 100~230ms |
| UEFI/BIOS | ✓ | ✓ | ✓ |
| 模拟USB键鼠 <br>Virtual HID | ✓ | ✓ | ✓ |
| 模拟USB存储 <br> Virtual CD-ROM | ✓ | ✓ | ✓ |
| 模拟USB键鼠 | ✓ | ✓ | ✓ |
| 模拟USB存储 | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ |
| Wake-on-LAN | ✓ | ✓ | ✓ |
| ETH | 100M/10M | 100M/10M | 1000M/100M/10M |
| ATX电源控制 | 无,用户可自行连接 | USB接口IO控制板 | RJ45接口IO控制板 |
| OLED显示 | 无,用户可自行扩展 | 128x64 0.96" white | 128x32 0.91" white |
| 外接串口 | 2路 | 2路 | 1路 |
| TF卡 | 无,用户自备 | 有,开机即用 | 有 |
| 扩展配件 | 无 | WiFi 或 PoE | WiFi/LTE |
| 扩展配件 | 无 | PoE | WiFi/LTE |
| 功耗 | 0.2A@5V | 0.2A@5V | Peak 2.6A@5V |
| 电源输入 | PC USB即可供电 | PC USB即可供电 <br> 也支持额外辅助供电 | 需要DC 5V 3A供电 |
| 散热 | 静音无风扇 | 静音无风扇 | 需要风扇主动散热 |
@@ -60,9 +61,18 @@ NanoKVM Lite 由 LicheeRV Nano E 和 HDMItoCSI 小板构成,NanoKVM FULL 在 N
NanoKVM 镜像在LicheeRV Nano SDK 和 MaixCDK 基础上构建,可以兼容使用 LicheeRV Nano 的资料,反之LicheeRV Nano 或其他 SG2002 产品无法使用KVM软件。如果您想在 LicheeRV Nano 或 MaixCam 上构建 HDMI输入相关应用,请与我们联系,以获得技术支持。
+ [HDMItoCSI 板原理图](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_B_30131.pdf)
注: SG2002的256MB内存中, 目前划分105MB用于多媒体子系统, NanoKVM会在视频图像采集和处理中使用这部分内存.
+ [NanoKVM-A 原理图](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_A_30111.pdf)
+ [NanoKVM-B 原理图](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_HDMI_MIPI_31011.pdf)
+ [NanoKVM 镜像下载](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
## 购买渠道
* [Aliexpress(全球,除了美国和俄罗斯)](https://www.aliexpress.com/item/1005007369816019.html)
* [淘宝](https://item.taobao.com/item.htm?id=811206560480)
* [Preorder (其它不支持淘宝和速卖通的国家)](https://sipeed.com/nanokvm)
## 社区

31
server/README.md Normal file
View File

@@ -0,0 +1,31 @@
# NanoKVM Server
The code of NanoKVM backend server. For more documentation, please refer to [Wiki](https://wiki.sipeed.com/nanokvm).
## Structure
```shell
server
├── config // server config
├── logger // server log
├── main.go
├── middleware // server middleware
├── proto // api request and response arguments
├── router // api routes
├── service // api handlers
└── utils // utils functions
```
## Development
The configuration file path is `/etc/kvm/server.yaml`. There are two configurable options:
- `log: error`: log level, default is `error`. Too many logs may affect service performance, it is recommended to use the `error` level in production environment.
- `authentication: enable`: Whether to enable authentication, default is `enable`. Logging in is required after each service restart, use `disable` will skip the authentication check and don't need to log in again. Please delete this configuration for production environments!
## Deployment
Work in progress.
The project requires CGO. It must be compiled on Linux with a toolchain installed. More details will be added later.

30
server/README_ZH.md Normal file
View File

@@ -0,0 +1,30 @@
# NanoKVM Server
NanoKVM 后端服务的代码。更多文档请参考 [Wiki](https://wiki.sipeed.com/nanokvm) 。
## 目录结构
```shell
server
├── config // 服务配置
├── logger // 服务日志
├── main.go
├── middleware // 中间件
├── proto // api 请求响应参数
├── router // api 路由
├── service // api 处理逻辑
└── utils // 工具函数
```
## 开发
配置文件路径为 `/etc/kvm/server.yaml`。有两个可配置的选项:
- `log: error`:日志等级,默认为 `error`。日志过多可能会影响服务性能,生产环境中建议使用 `error` 等级。
- `authentication: enable`:是否启用鉴权,默认开启。服务每次重启后都需要重新登录,将该选项设为 `disable` 会跳过鉴权检查,可以不用重复登录。生产环境请删除该条配置!
## 部署
待完善。
项目中使用了 CGO,需要使用 Linux 并安装工具链后才能编译。这部分内容会晚一点更新。

148
server/common/cgo.go Normal file
View File

@@ -0,0 +1,148 @@
package common
/*
#cgo CFLAGS: -I../include
#cgo LDFLAGS: -L../dl_lib -lkvm
#include "kvm_vision.h"
*/
import "C"
import (
"NanoKVM-Server/config"
"strings"
"sync"
"unsafe"
log "github.com/sirupsen/logrus"
)
var (
kvmVision *KvmVision
kvmVisionOnce sync.Once
)
type KvmVision struct {
mutex sync.Mutex
}
func GetKvmVision() *KvmVision {
kvmVisionOnce.Do(func() {
kvmVision = &KvmVision{}
conf := config.GetInstance()
logLevel := strings.ToLower(conf.Logger.Level)
logEnable := C.uint8_t(0)
if logLevel == "debug" {
logEnable = C.uint8_t(1)
}
C.kvmv_init(logEnable)
log.Debugf("kvm vision initialized")
})
return kvmVision
}
func (k *KvmVision) ReadMjpeg(width uint16, height uint16, quality uint16) (data []byte, result int) {
k.mutex.Lock()
defer k.mutex.Unlock()
var (
kvmData *C.uint8_t
dataSize C.uint32_t
)
result = int(C.kvmv_read_img(
C.uint16_t(width),
C.uint16_t(height),
C.uint8_t(0),
C.uint16_t(quality),
&kvmData,
&dataSize,
))
if result < 0 {
log.Errorf("failed to read kvm image: %v", result)
return
}
defer C.free_kvmv_data(&kvmData)
data = C.GoBytes(unsafe.Pointer(kvmData), C.int(dataSize))
log.Debugf("read kvm image: %v", result)
return
}
func (k *KvmVision) ReadH264(width uint16, height uint16, bitRate uint16) (data []byte, sps []byte, pps []byte, result int) {
k.mutex.Lock()
defer k.mutex.Unlock()
var (
kvmData *C.uint8_t
dataSize C.uint32_t
)
result = int(C.kvmv_read_img(
C.uint16_t(width),
C.uint16_t(height),
C.uint8_t(1),
C.uint16_t(bitRate),
&kvmData,
&dataSize,
))
if result < 0 {
log.Errorf("failed to read kvm image: %v", result)
return
}
defer C.free_kvmv_data(&kvmData)
data = C.GoBytes(unsafe.Pointer(kvmData), C.int(dataSize))
if result == 3 {
sps, _ = k.ReadH264SPS()
pps, _ = k.ReadH264PPS()
}
log.Debugf("read kvm image: %v", result)
return
}
func (k *KvmVision) ReadH264SPS() ([]byte, int) {
var (
kvmData *C.uint8_t
dataSize C.uint32_t
)
result := C.kvmv_get_sps_frame(&kvmData, &dataSize)
if result < 0 {
log.Errorf("failed to read sps: %v", result)
return nil, int(result)
}
data := C.GoBytes(unsafe.Pointer(kvmData), C.int(dataSize))
return data, int(result)
}
func (k *KvmVision) ReadH264PPS() ([]byte, int) {
var (
kvmData *C.uint8_t
dataSize C.uint32_t
)
result := C.kvmv_get_pps_frame(&kvmData, &dataSize)
if result < 0 {
log.Errorf("failed to read pps: %v", result)
return nil, int(result)
}
data := C.GoBytes(unsafe.Pointer(kvmData), C.int(dataSize))
return data, int(result)
}
func (k *KvmVision) Close() {
k.mutex.Lock()
defer k.mutex.Unlock()
C.kvmv_deinit()
log.Debugf("stop kvm vision...")
}

85
server/common/screen.go Normal file
View File

@@ -0,0 +1,85 @@
package common
import "sync"
type Screen struct {
Width uint16
Height uint16
FPS int
Quality uint16
BitRate uint16
}
var (
screen *Screen
screenOnce sync.Once
)
// ResolutionMap height to width
var ResolutionMap = map[uint16]uint16{
1080: 1920,
720: 1280,
600: 800,
480: 640,
0: 0,
}
var QualityMap = map[uint16]bool{
100: true,
80: true,
60: true,
50: true,
}
var BitRateMap = map[uint16]bool{
5000: true,
3000: true,
2000: true,
1000: true,
}
func GetScreen() *Screen {
screenOnce.Do(func() {
screen = &Screen{
Width: 0,
Height: 0,
Quality: 80,
FPS: 30,
BitRate: 3000,
}
})
return screen
}
func SetScreen(key string, value int) {
switch key {
case "resolution":
height := uint16(value)
if width, ok := ResolutionMap[height]; ok {
screen.Width = width
screen.Height = height
}
case "quality":
if value > 100 {
screen.BitRate = uint16(value)
} else {
screen.Quality = uint16(value)
}
case "fps":
screen.FPS = validateFPS(value)
}
}
func validateFPS(fps int) int {
if fps > 60 {
return 60
}
if fps < 10 {
return 10
}
return fps
}

143
server/config/config.go Normal file
View File

@@ -0,0 +1,143 @@
package config
import (
"bytes"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"log"
"os"
"sync"
"time"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
)
var (
config Config
once sync.Once
)
func GetInstance() *Config {
once.Do(initialize)
return &config
}
func initialize() {
if err := readByFile(); err != nil {
if errors.As(err, &viper.ConfigFileNotFoundError{}) {
create()
}
if err = readByDefault(); err != nil {
log.Fatalf("Failed to read default configuration!")
}
log.Println("using default configuration")
}
if err := validate(); err != nil {
log.Fatalf("Failed to validate configuration!")
}
if err := viper.Unmarshal(&config); err != nil {
log.Fatalf("Failed to parse configuration: %s", err)
}
if config.Authentication == "disable" {
log.Println("NOTICE: Authentication is disabled! Please ensure your service is secure!")
}
if config.SecretKey == "" {
config.SecretKey = generateRandomString()
}
config.Hardware = getHardware()
log.Println("config loaded successfully")
}
func readByFile() error {
viper.SetConfigName("server")
viper.SetConfigType("yaml")
viper.AddConfigPath("/etc/kvm/")
return viper.ReadInConfig()
}
func readByDefault() error {
data, err := yaml.Marshal(defaultConfig)
if err != nil {
log.Printf("failed to marshal default config: %s", err)
return err
}
return viper.ReadConfig(bytes.NewBuffer(data))
}
// Create configuration file.
func create() {
var (
file *os.File
data []byte
err error
)
_ = os.MkdirAll("/etc/kvm", 0o644)
file, err = os.OpenFile("/etc/kvm/server.yaml", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil {
log.Printf("open config failed: %s", err)
return
}
defer func() {
_ = file.Close()
}()
if data, err = yaml.Marshal(defaultConfig); err != nil {
log.Printf("failed to marshal default config: %s", err)
return
}
if _, err = file.Write(data); err != nil {
log.Printf("failed to save config: %s", err)
return
}
if err = file.Sync(); err != nil {
log.Printf("failed to sync config: %s", err)
return
}
log.Println("create file /etc/kvm/server.yaml with default configuration")
}
// Validate the configuration. This is to ensure compatibility with earlier versions.
func validate() error {
if viper.GetInt("port.http") > 0 && viper.GetInt("port.https") > 0 {
return nil
}
_ = os.Remove("/etc/kvm/server.yaml")
log.Println("delete empty configuration file")
create()
return readByDefault()
}
// Generate random string for secret key.
func generateRandomString() string {
b := make([]byte, 64)
_, err := rand.Read(b)
if err != nil {
currentTime := time.Now().UnixNano()
timeString := fmt.Sprintf("%d", currentTime)
return fmt.Sprintf("%064s", timeString)
}
return base64.URLEncoding.EncodeToString(b)
}

18
server/config/default.go Normal file
View File

@@ -0,0 +1,18 @@
package config
var defaultConfig = &Config{
Protocol: "http",
Port: Port{
Http: 80,
Https: 443,
},
Cert: Cert{
Crt: "server.crt",
Key: "server.key",
},
Logger: Logger{
Level: "info",
File: "stdout",
},
Authentication: "enable",
}

70
server/config/hardware.go Normal file
View File

@@ -0,0 +1,70 @@
package config
import (
"os"
"strings"
log "github.com/sirupsen/logrus"
)
type HWVersion int
const (
HWVersionAlpha HWVersion = iota
HWVersionBeta
)
const (
hwVersionFile = "/etc/kvm/hw"
gpioPower = "/sys/class/gpio/gpio503/value"
gpioPowerLED = "/sys/class/gpio/gpio504/value"
gpioResetAlpha = "/sys/class/gpio/gpio507/value"
gpioHDDLedAlpha = "/sys/class/gpio/gpio505/value"
gpioResetBeta = "/sys/class/gpio/gpio505/value"
)
func (h HWVersion) String() string {
switch h {
case HWVersionAlpha:
return "Alpha"
case HWVersionBeta:
return "Beta"
default:
return "Unknown"
}
}
func getHwVersion() HWVersion {
content, err := os.ReadFile(hwVersionFile)
if err == nil {
version := strings.ReplaceAll(string(content), "\n", "")
if version == "beta" {
return HWVersionBeta
}
}
return HWVersionAlpha
}
func getHardware() Hardware {
h := Hardware{}
h.Version = getHwVersion()
h.GPIOPower = gpioPower
h.GPIOPowerLED = gpioPowerLED
switch h.Version {
case HWVersionAlpha:
h.GPIOHDDLed = gpioHDDLedAlpha
h.GPIOReset = gpioResetAlpha
case HWVersionBeta:
h.GPIOReset = gpioResetBeta
default:
log.Fatalf("Unsupported hardware version: %s", h.Version)
}
return h
}

35
server/config/types.go Normal file
View File

@@ -0,0 +1,35 @@
package config
type Config struct {
Protocol string `yaml:"proto"`
Port Port `yaml:"port"`
Cert Cert `yaml:"cert"`
Logger Logger `yaml:"logger"`
Authentication string `yaml:"authentication"`
SecretKey string `yaml:"secretKey"`
Hardware Hardware `yaml:"-"`
}
type Logger struct {
Level string `yaml:"level"`
File string `yaml:"file"`
}
type Port struct {
Http int `yaml:"http"`
Https int `yaml:"https"`
}
type Cert struct {
Crt string `yaml:"crt"`
Key string `yaml:"key"`
}
type Hardware struct {
Version HWVersion `yaml:"-"`
GPIOReset string `yaml:"-"`
GPIOPower string `yaml:"-"`
GPIOPowerLED string `yaml:"-"`
GPIOHDDLed string `yaml:"-"`
}

BIN
server/dl_lib/libkvm.so Normal file

Binary file not shown.

78
server/go.mod Normal file
View File

@@ -0,0 +1,78 @@
module NanoKVM-Server
go 1.22.1
require (
github.com/gin-gonic/contrib v0.0.0-20240508051311-c1c6bf0061b0
github.com/gin-gonic/gin v1.10.0
github.com/go-playground/validator/v10 v10.20.0
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/gorilla/websocket v1.5.3
github.com/mervick/aes-everywhere/go/aes256 v0.0.0-20240803013625-6759956693c0
github.com/pion/webrtc/v4 v4.0.1
github.com/rs/cors/wrapper/gin v0.0.0-20240830163046-1084d89a1692
github.com/sirupsen/logrus v1.9.3
github.com/spf13/viper v1.19.0
github.com/unrolled/secure v1.15.0
golang.org/x/crypto v0.28.0
gopkg.in/yaml.v3 v3.0.1
)
require (
github.com/bytedance/sonic v1.11.6 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/pion/datachannel v1.5.9 // indirect
github.com/pion/dtls/v3 v3.0.3 // indirect
github.com/pion/ice/v4 v4.0.2 // indirect
github.com/pion/interceptor v0.1.37 // indirect
github.com/pion/logging v0.2.2 // indirect
github.com/pion/mdns/v2 v2.0.7 // indirect
github.com/pion/randutil v0.1.0 // indirect
github.com/pion/rtcp v1.2.14 // indirect
github.com/pion/rtp v1.8.9 // indirect
github.com/pion/sctp v1.8.33 // indirect
github.com/pion/sdp/v3 v3.0.9 // indirect
github.com/pion/srtp/v3 v3.0.4 // indirect
github.com/pion/stun/v3 v3.0.0 // indirect
github.com/pion/transport/v3 v3.0.7 // indirect
github.com/pion/turn/v4 v4.0.0 // indirect
github.com/rs/cors v1.11.0 // indirect
github.com/sagikazarmark/locafero v0.4.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.11.0 // indirect
github.com/spf13/cast v1.6.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
github.com/wlynxg/anet v0.0.3 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/net v0.29.0 // indirect
golang.org/x/sys v0.26.0 // indirect
golang.org/x/text v0.19.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
)

185
server/go.sum Normal file
View File

@@ -0,0 +1,185 @@
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/contrib v0.0.0-20240508051311-c1c6bf0061b0 h1:EUFmvQ8ffefnSAmaUZd9HZYZSw9w/bFjp3FiNaJ5WmE=
github.com/gin-gonic/contrib v0.0.0-20240508051311-c1c6bf0061b0/go.mod h1:iqneQ2Df3omzIVTkIfn7c1acsVnMGiSLn4XF5Blh3Yg=
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mervick/aes-everywhere/go/aes256 v0.0.0-20240803013625-6759956693c0 h1:IfWxTv9SQWw2Vw48Y2CZvVam1WeDBASWnlvNL8QwyQs=
github.com/mervick/aes-everywhere/go/aes256 v0.0.0-20240803013625-6759956693c0/go.mod h1:Eb5RMoo9kOQra/2uRiUTGP+LfNuM13Vqm7y7P34+KKo=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pion/datachannel v1.5.9 h1:LpIWAOYPyDrXtU+BW7X0Yt/vGtYxtXQ8ql7dFfYUVZA=
github.com/pion/datachannel v1.5.9/go.mod h1:kDUuk4CU4Uxp82NH4LQZbISULkX/HtzKa4P7ldf9izE=
github.com/pion/dtls/v3 v3.0.3 h1:j5ajZbQwff7Z8k3pE3S+rQ4STvKvXUdKsi/07ka+OWM=
github.com/pion/dtls/v3 v3.0.3/go.mod h1:weOTUyIV4z0bQaVzKe8kpaP17+us3yAuiQsEAG1STMU=
github.com/pion/ice/v4 v4.0.2 h1:1JhBRX8iQLi0+TfcavTjPjI6GO41MFn4CeTBX+Y9h5s=
github.com/pion/ice/v4 v4.0.2/go.mod h1:DCdqyzgtsDNYN6/3U8044j3U7qsJ9KFJC92VnOWHvXg=
github.com/pion/interceptor v0.1.37 h1:aRA8Zpab/wE7/c0O3fh1PqY0AJI3fCSEM5lRWJVorwI=
github.com/pion/interceptor v0.1.37/go.mod h1:JzxbJ4umVTlZAf+/utHzNesY8tmRkM2lVmkS82TTj8Y=
github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY=
github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms=
github.com/pion/mdns/v2 v2.0.7 h1:c9kM8ewCgjslaAmicYMFQIde2H9/lrZpjBkN8VwoVtM=
github.com/pion/mdns/v2 v2.0.7/go.mod h1:vAdSYNAT0Jy3Ru0zl2YiW3Rm/fJCwIeM0nToenfOJKA=
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
github.com/pion/rtcp v1.2.14 h1:KCkGV3vJ+4DAJmvP0vaQShsb0xkRfWkO540Gy102KyE=
github.com/pion/rtcp v1.2.14/go.mod h1:sn6qjxvnwyAkkPzPULIbVqSKI5Dv54Rv7VG0kNxh9L4=
github.com/pion/rtp v1.8.9 h1:E2HX740TZKaqdcPmf4pw6ZZuG8u5RlMMt+l3dxeu6Wk=
github.com/pion/rtp v1.8.9/go.mod h1:pBGHaFt/yW7bf1jjWAoUjpSNoDnw98KTMg+jWWvziqU=
github.com/pion/sctp v1.8.33 h1:dSE4wX6uTJBcNm8+YlMg7lw1wqyKHggsP5uKbdj+NZw=
github.com/pion/sctp v1.8.33/go.mod h1:beTnqSzewI53KWoG3nqB282oDMGrhNxBdb+JZnkCwRM=
github.com/pion/sdp/v3 v3.0.9 h1:pX++dCHoHUwq43kuwf3PyJfHlwIj4hXA7Vrifiq0IJY=
github.com/pion/sdp/v3 v3.0.9/go.mod h1:B5xmvENq5IXJimIO4zfp6LAe1fD9N+kFv+V/1lOdz8M=
github.com/pion/srtp/v3 v3.0.4 h1:2Z6vDVxzrX3UHEgrUyIGM4rRouoC7v+NiF1IHtp9B5M=
github.com/pion/srtp/v3 v3.0.4/go.mod h1:1Jx3FwDoxpRaTh1oRV8A/6G1BnFL+QI82eK4ms8EEJQ=
github.com/pion/stun/v3 v3.0.0 h1:4h1gwhWLWuZWOJIJR9s2ferRO+W3zA/b6ijOI6mKzUw=
github.com/pion/stun/v3 v3.0.0/go.mod h1:HvCN8txt8mwi4FBvS3EmDghW6aQJ24T+y+1TKjB5jyU=
github.com/pion/transport/v3 v3.0.7 h1:iRbMH05BzSNwhILHoBoAPxoB9xQgOaJk+591KC9P1o0=
github.com/pion/transport/v3 v3.0.7/go.mod h1:YleKiTZ4vqNxVwh77Z0zytYi7rXHl7j6uPLGhhz9rwo=
github.com/pion/turn/v4 v4.0.0 h1:qxplo3Rxa9Yg1xXDxxH8xaqcyGUtbHYw4QSCvmFWvhM=
github.com/pion/turn/v4 v4.0.0/go.mod h1:MuPDkm15nYSklKpN8vWJ9W2M0PlyQZqYt1McGuxG7mA=
github.com/pion/webrtc/v4 v4.0.1 h1:6Unwc6JzoTsjxetcAIoWH81RUM4K5dBc1BbJGcF9WVE=
github.com/pion/webrtc/v4 v4.0.1/go.mod h1:SfNn8CcFxR6OUVjLXVslAQ3a3994JhyE3Hw1jAuqEto=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rs/cors v1.11.0 h1:0B9GE/r9Bc2UxRMMtymBkHTenPkHDv0CW4Y98GBY+po=
github.com/rs/cors v1.11.0/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
github.com/rs/cors/wrapper/gin v0.0.0-20240830163046-1084d89a1692 h1:lwzJgPw5Y6pvC8mwbedX9HfdywUKcpNdcviftZsb1uY=
github.com/rs/cors/wrapper/gin v0.0.0-20240830163046-1084d89a1692/go.mod h1:742Ialb8SOs5yB2PqRDzFcyND3280PoaS5/wcKQUQKE=
github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ=
github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4=
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI=
github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
github.com/unrolled/secure v1.15.0 h1:q7x+pdp8jAHnbzxu6UheP8fRlG/rwYTb8TPuQ3rn9Og=
github.com/unrolled/secure v1.15.0/go.mod h1:BmF5hyM6tXczk3MpQkFf1hpKSRqCyhqcbiQtiAF7+40=
github.com/wlynxg/anet v0.0.3 h1:PvR53psxFXstc12jelG6f1Lv4MWqE0tI76/hHGjh9rg=
github.com/wlynxg/anet v0.0.3/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw=
golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo=
golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.25.0 h1:WtHI/ltw4NvSUig5KARz9h521QvRC8RmF/cuYqifU24=
golang.org/x/term v0.25.0/go.mod h1:RPyXicDX+6vLxogjjRxjgD2TKtmAO6NZBsBRfrOLu7M=
golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM=
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

View File

@@ -0,0 +1,59 @@
#ifndef KVM_VISION_H_
#define KVM_VISION_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <fcntl.h> /* low-level i/o */
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <pthread.h>
#define IMG_BUFFER_FULL -3
#define IMG_VENC_ERROR -2
#define IMG_NOT_EXIST -1
#define IMG_MJPEG_TYPE 0
#define IMG_H264_TYPE_SPS 1
#define IMG_H264_TYPE_PPS 2
#define IMG_H264_TYPE_IF 3
#define IMG_H264_TYPE_PF 4
void kvmv_init(uint8_t _debug_info_en);
/**********************************************************************************
* @name kvmv_read_img
* @author Sipeed BuGu
* @date 2024/10/25
* @version R1.0
* @brief Acquire the encoded image with auto init
* @param _width @input: Output image width
* @param _height @input: Output image height
* @param _type @input: Encode type
* @param _qlty @input: MJPEG: (50-100) | H264: (500-10000)
* @param _pp_kvm_data @output: Encode data
* @param _p_kvmv_data_size @output: Encode data size
* @return
-3: img buffer full
-2: VENC Error
-1: No images were acquired
0: Acquire MJPEG encoded images
1: Acquire H264 encoded images(SPS)
2: Acquire H264 encoded images(PPS)
3: Acquire H264 encoded images(I)
4: Acquire H264 encoded images(P)
**********************************************************************************/
int kvmv_read_img(uint16_t _width, uint16_t _height, uint8_t _type, uint16_t _qlty, uint8_t** _pp_kvm_data, uint32_t* _p_kvmv_data_size);
int kvmv_get_sps_frame(uint8_t** _pp_kvm_data, uint32_t* _p_kvmv_data_size);
int kvmv_get_pps_frame(uint8_t** _pp_kvm_data, uint32_t* _p_kvmv_data_size);
int free_kvmv_data(uint8_t ** _pp_kvm_data);
void free_all_kvmv_data();
void set_h264_gop(uint8_t _gop);
void kvmv_deinit();
#ifdef __cplusplus
}
#endif
#endif // KVM_VISION_H_

View File

@@ -0,0 +1,42 @@
package logger
import (
"bytes"
"fmt"
"path/filepath"
"github.com/sirupsen/logrus"
)
type formatter struct{}
func (f *formatter) Format(entry *logrus.Entry) ([]byte, error) {
var (
text string
buffer *bytes.Buffer
)
if entry.Buffer != nil {
buffer = entry.Buffer
} else {
buffer = &bytes.Buffer{}
}
now := entry.Time.Format("2006-01-02 15:04:05")
if entry.HasCaller() {
fileName := filepath.Base(entry.Caller.File)
text = fmt.Sprintf(
"[%s] [%s] [%s:%d] %s\n",
now, entry.Level, fileName, entry.Caller.Line, entry.Message,
)
} else {
text = fmt.Sprintf(
"[%s] [%s] %s \n",
now, entry.Level, entry.Message,
)
}
buffer.WriteString(text)
return buffer.Bytes(), nil
}

51
server/logger/logger.go Normal file
View File

@@ -0,0 +1,51 @@
package logger
import (
"os"
"path/filepath"
"NanoKVM-Server/config"
"github.com/sirupsen/logrus"
)
func openLogFile(filename string) (*os.File, error) {
absPath, err := filepath.Abs(filename)
if err != nil {
return nil, err
}
file, err := os.OpenFile(absPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
if err != nil {
return nil, err
}
return file, nil
}
func Init() {
conf := config.GetInstance()
level, err := logrus.ParseLevel(conf.Logger.Level)
if err != nil {
level = logrus.ErrorLevel
}
logrus.SetLevel(level)
if conf.Logger.File == "" || conf.Logger.File == "stdout" {
logrus.SetOutput(os.Stdout)
} else {
fh, err := openLogFile(conf.Logger.File)
if err != nil {
logrus.Error("open log file failed:", err)
logrus.SetOutput(os.Stdout)
} else {
logrus.SetOutput(fh)
}
}
logrus.SetReportCaller(true)
logrus.SetFormatter(&formatter{})
logrus.Info("logger set success")
}

79
server/main.go Normal file
View File

@@ -0,0 +1,79 @@
package main
import (
"NanoKVM-Server/common"
"NanoKVM-Server/config"
"NanoKVM-Server/logger"
"NanoKVM-Server/middleware"
"NanoKVM-Server/router"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/gin-gonic/gin"
cors "github.com/rs/cors/wrapper/gin"
)
func main() {
initialize()
defer dispose()
signalHandler()
gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.Use(gin.Recovery())
r.Use(cors.AllowAll())
router.Init(r)
run(r)
}
func initialize() {
logger.Init()
_ = common.GetScreen()
_ = common.GetKvmVision()
}
func run(r *gin.Engine) {
conf := config.GetInstance()
httpAddr := fmt.Sprintf(":%d", conf.Port.Http)
httpsAddr := fmt.Sprintf(":%d", conf.Port.Https)
if conf.Protocol == "https" {
r.Use(middleware.Tls())
go func() {
if err := r.Run(httpAddr); err != nil {
panic("start http server failed")
}
}()
if err := r.RunTLS(httpsAddr, conf.Cert.Crt, conf.Cert.Key); err != nil {
panic("start https server failed")
}
} else {
if err := r.Run(httpAddr); err != nil {
panic("start http server failed")
}
}
}
func dispose() {
common.GetKvmVision().Close()
}
func signalHandler() {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
go func() {
sig := <-sigChan
fmt.Printf("\nReceived signal: %v\n", sig)
dispose()
os.Exit(0)
}()
}

78
server/middleware/jwt.go Normal file
View File

@@ -0,0 +1,78 @@
package middleware
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/config"
)
type Token struct {
Username string `json:"username"`
jwt.RegisteredClaims
}
const (
ExpireDuration = 31 * 24 * time.Hour
)
func CheckToken() gin.HandlerFunc {
return func(c *gin.Context) {
conf := config.GetInstance()
if conf.Authentication == "disable" {
c.Next()
return
}
cookie, err := c.Cookie("nano-kvm-token")
if err == nil {
_, err = ParseJWT(cookie)
if err == nil {
c.Next()
return
}
}
c.JSON(http.StatusUnauthorized, "unauthorized")
c.Abort()
}
}
func GenerateJWT(username string) (string, error) {
conf := config.GetInstance()
claims := Token{
Username: username,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(ExpireDuration)),
},
}
t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return t.SignedString([]byte(conf.SecretKey))
}
func ParseJWT(jwtToken string) (*Token, error) {
conf := config.GetInstance()
t, err := jwt.ParseWithClaims(jwtToken, &Token{}, func(token *jwt.Token) (interface{}, error) {
secretKey := conf.SecretKey
return []byte(secretKey), nil
})
if err != nil {
log.Debugf("parse jwt error: %s", err)
return nil, err
}
if claims, ok := t.Claims.(*Token); ok && t.Valid {
return claims, nil
} else {
return nil, err
}
}

26
server/middleware/tls.go Normal file
View File

@@ -0,0 +1,26 @@
package middleware
import (
"github.com/gin-gonic/gin"
"github.com/unrolled/secure"
)
func Tls() gin.HandlerFunc {
secureMiddleware := secure.New(secure.Options{
SSLRedirect: true,
})
secureFunc := func(c *gin.Context) {
err := secureMiddleware.Process(c.Writer, c.Request)
if err != nil {
c.Abort()
return
}
if status := c.Writer.Status(); status > 300 && status < 399 {
c.Abort()
}
}
return secureFunc
}

View File

@@ -0,0 +1,10 @@
package proto
type GetVersionRsp struct {
Current string `json:"current"`
Latest string `json:"latest"`
}
type GetLibRsp struct {
Exist bool `json:"exist"`
}

19
server/proto/auth.go Normal file
View File

@@ -0,0 +1,19 @@
package proto
type LoginReq struct {
Username string `validate:"required"`
Password string `validate:"required"`
}
type LoginRsp struct {
Token string `json:"token"`
}
type ChangePasswordReq struct {
Username string `json:"username" validate:"required"`
Password string `json:"password" validate:"required"`
}
type IsPasswordUpdatedRsp struct {
IsUpdated bool `json:"isUpdated"`
}

33
server/proto/network.go Normal file
View File

@@ -0,0 +1,33 @@
package proto
type WakeOnLANReq struct {
Mac string `form:"mac" validate:"required"`
}
type GetMacRsp struct {
Macs []string `json:"macs"`
}
type DeleteMacReq struct {
Mac string `form:"mac" validate:"required"`
}
type GetTailscaleStatusRsp struct {
Status string `json:"status"` // notInstall | notLogin | stopped | running
Name string `json:"name"`
IP string `json:"ip"`
Account string `json:"account"`
}
type UpdateTailscaleStatusReq struct {
Command string // up | down
}
type UpdateTailscaleStatusRsp struct {
Status string `json:"status"` // stopped | running
}
type LoginTailscaleRsp struct {
Status string `json:"status"`
Url string `json:"url"`
}

49
server/proto/request.go Normal file
View File

@@ -0,0 +1,49 @@
package proto
import (
"os"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
log "github.com/sirupsen/logrus"
)
var env = os.Getenv(gin.EnvGinMode)
// ValidateRequest Validates request parameters.
func ValidateRequest(req interface{}) error {
validate := validator.New()
if err := validate.Struct(req); err != nil {
log.Errorf("validate request failed, err: %s", err)
return err
}
if env == "" || env == "debug" {
log.Debugf("request: %+v\n", req)
}
return nil
}
// ParseQueryRequest Validates GET requests.
func ParseQueryRequest(c *gin.Context, req interface{}) error {
var err error
if err = c.ShouldBindQuery(req); err != nil {
log.Errorf("parse request failed, err: %s", err)
return err
}
return ValidateRequest(req)
}
// ParseFormRequest Validates POST Requests.
func ParseFormRequest(c *gin.Context, req interface{}) error {
var err error
if err = c.ShouldBind(req); err != nil {
log.Errorf("parse request failed, err: %s", err)
return err
}
return ValidateRequest(req)
}

50
server/proto/response.go Normal file
View File

@@ -0,0 +1,50 @@
package proto
import (
"net/http"
"github.com/gin-gonic/gin"
)
type Response struct {
Code int `json:"code"` // Status code. 0-success, others-failure
Msg string `json:"msg"` // Status details
Data interface{} `json:"data"` // Returned data
}
func (r *Response) Ok() {
r.Code = 0
r.Msg = "success"
}
func (r *Response) OkWithData(data interface{}) {
r.Ok()
r.Data = data
}
func (r *Response) Err(code int, msg string) {
r.Code = code
r.Msg = msg
}
// OkRsp Successful response without data.
func (r *Response) OkRsp(c *gin.Context) {
r.Ok()
c.JSON(http.StatusOK, r)
}
// OkRspWithData Successful response with data.
func (r *Response) OkRspWithData(c *gin.Context, data interface{}) {
r.Ok()
r.Data = data
c.JSON(http.StatusOK, r)
}
// ErrRsp Failed response.
func (r *Response) ErrRsp(c *gin.Context, code int, msg string) {
r.Err(code, msg)
c.JSON(http.StatusOK, r)
}

13
server/proto/storage.go Normal file
View File

@@ -0,0 +1,13 @@
package proto
type GetImagesRsp struct {
Files []string `json:"files"`
}
type MountImageReq struct {
File string `json:"file" validate:"omitempty"`
}
type GetMountedImageRsp struct {
File string `json:"file"`
}

9
server/proto/stream.go Normal file
View File

@@ -0,0 +1,9 @@
package proto
type GetFrameDetectRsp struct {
Enabled bool `json:"enabled"`
}
type UpdateFrameDetectRsp struct {
Enabled bool `json:"enabled"`
}

58
server/proto/vm.go Normal file
View File

@@ -0,0 +1,58 @@
package proto
type GetInfoRsp struct {
Ip string `json:"ip"`
Mdns string `json:"mdns"`
Image string `json:"image"`
Application string `json:"application"`
DeviceKey string `json:"deviceKey"`
}
type SetGpioReq struct {
Type string `validate:"required"` // reset / power
Duration uint `validate:"omitempty"` // press time (unit: milliseconds)
}
type GetGpioRsp struct {
PWR bool `json:"pwr"` // power led
HDD bool `json:"hdd"` // hdd led
}
type SetScreenReq struct {
Type string `validate:"required"` // resolution / fps / quality
Value int `validate:"number"` // value
}
type GetScriptsRsp struct {
Files []string `json:"files"`
}
type UploadScriptRsp struct {
File string `json:"file"`
}
type RunScriptReq struct {
Name string `validate:"required"`
Type string `validate:"required"` // foreground | background
}
type RunScriptRsp struct {
Log string `json:"log"`
}
type DeleteScriptReq struct {
Name string `validate:"required"`
}
type GetVirtualDeviceRsp struct {
Network bool `json:"network"`
Disk bool `json:"disk"`
}
type UpdateVirtualDeviceReq struct {
Device string `validate:"required"`
}
type UpdateVirtualDeviceRsp struct {
On bool `json:"on"`
}

View File

@@ -0,0 +1,16 @@
package router
import (
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/application"
"github.com/gin-gonic/gin"
)
func applicationRouter(r *gin.Engine) {
service := application.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
api.GET("/application/version", service.GetVersion) // get application version
api.POST("/application/update", service.Update) // update application
}

19
server/router/auth.go Normal file
View File

@@ -0,0 +1,19 @@
package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/auth"
)
func authRouter(r *gin.Engine) {
service := auth.NewService()
r.POST("/api/auth/login", service.Login) // login
api := r.Group("/api").Use(middleware.CheckToken())
api.GET("/auth/password", service.IsPasswordUpdated) // is password updated
api.POST("/auth/password", service.ChangePassword) // change password
}

16
server/router/hid.go Normal file
View File

@@ -0,0 +1,16 @@
package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/hid"
)
func hidRouter(r *gin.Engine) {
service := hid.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
api.POST("/hid/reset", service.Reset) // reset hid
api.POST("/hid/paste", service.Paste) // paste
}

23
server/router/network.go Normal file
View File

@@ -0,0 +1,23 @@
package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/network"
)
func networkRouter(r *gin.Engine) {
service := network.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
api.POST("/network/wol", service.WakeOnLAN) // wake on lan
api.GET("/network/wol/mac", service.GetMac) // get mac list
api.DELETE("/network/wol/mac", service.DeleteMac) // delete mac
api.POST("/network/tailscale/install", service.InstallTailscale) // install tailscale
api.GET("/network/tailscale/status", service.GetTailscaleStatus) // get tailscale status
api.POST("/network/tailscale/status", service.UpdateTailscaleStatus) // update tailscale status
api.POST("/network/tailscale/login", service.LoginTailscale) // tailscale login
api.POST("/network/tailscale/logout", service.LogoutTailscale) // tailscale logout
}

40
server/router/router.go Normal file
View File

@@ -0,0 +1,40 @@
package router
import (
"fmt"
"os"
"path/filepath"
"github.com/gin-gonic/contrib/static"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
func Init(r *gin.Engine) {
web(r)
server(r)
log.Debugf("router init done")
}
func web(r *gin.Engine) {
execPath, err := os.Executable()
if err != nil {
panic("invalid executable path")
}
execDir := filepath.Dir(execPath)
webPath := fmt.Sprintf("%s/web", execDir)
r.Use(static.Serve("/", static.LocalFile(webPath, true)))
}
func server(r *gin.Engine) {
authRouter(r)
applicationRouter(r)
vmRouter(r)
streamRouter(r)
storageRouter(r)
networkRouter(r)
hidRouter(r)
wsRouter(r)
}

17
server/router/storage.go Normal file
View File

@@ -0,0 +1,17 @@
package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/storage"
)
func storageRouter(r *gin.Engine) {
service := storage.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
api.GET("/storage/image", service.GetImages) // get image list
api.GET("/storage/image/mounted", service.GetMountedImage) // get mounted image
api.POST("/storage/image/mount", service.MountImage) // mount image
}

20
server/router/stream.go Normal file
View File

@@ -0,0 +1,20 @@
package router
import (
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/stream/h264"
"NanoKVM-Server/service/stream/mjpeg"
"github.com/gin-gonic/gin"
)
func streamRouter(r *gin.Engine) {
api := r.Group("/api").Use(middleware.CheckToken())
api.GET("/stream/mjpeg", mjpeg.Connect) // mjpeg stream
api.GET("/stream/mjpeg/detect", mjpeg.GetFrameDetect) // get frame detect state
api.POST("/stream/mjpeg/detect", mjpeg.UpdateFrameDetect) // update frame detect state
api.POST("/stream/mjpeg/detect/stop", mjpeg.StopFrameDetect) // temporary stop frame detect
api.GET("/stream/h264", h264.Connect) // h264 stream
}

29
server/router/vm.go Normal file
View File

@@ -0,0 +1,29 @@
package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/vm"
)
func vmRouter(r *gin.Engine) {
service := vm.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
api.GET("/vm/info", service.GetInfo) // get device information
api.POST("/vm/gpio", service.SetGpio) // update gpio
api.GET("/vm/gpio", service.GetGpio) // get gpio
api.POST("/vm/screen", service.SetScreen) // update screen
api.GET("/vm/terminal", service.Terminal) // web terminal
api.GET("/vm/script", service.GetScripts) // get script
api.POST("/vm/script/upload", service.UploadScript) // upload script
api.POST("/vm/script/run", service.RunScript) // run script
api.DELETE("/vm/script", service.DeleteScript) // delete script
api.GET("/vm/device/virtual", service.GetVirtualDevice) // get virtual device
api.POST("/vm/device/virtual", service.UpdateVirtualDevice) // update virtual device
}

15
server/router/ws.go Normal file
View File

@@ -0,0 +1,15 @@
package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/ws"
)
func wsRouter(r *gin.Engine) {
service := ws.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
api.GET("/ws", service.Connect)
}

View File

@@ -0,0 +1,211 @@
package application
import (
"fmt"
"io"
"net/http"
"os"
"os/exec"
"strings"
"time"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/proto"
"NanoKVM-Server/utils"
)
const (
maxTries = 3
)
func (s *Service) GetVersion(c *gin.Context) {
var rsp proto.Response
log.Debugf("get version api triggered")
// current version
currentVersion := "1.0.0"
content, err := os.ReadFile(versionFile)
if err == nil {
currentVersion = strings.ReplaceAll(string(content), "\n", "")
}
log.Debugf("current version: %s", currentVersion)
// latest version
url := fmt.Sprintf("%s?now=%d", versionURL, time.Now().Unix())
resp, err := http.Get(url)
if err != nil {
log.Debugf("get latest version failed: %v", err)
rsp.ErrRsp(c, -2, "Unable to access sipeed.com. Please check your network.")
return
}
defer func() {
_ = resp.Body.Close()
}()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Errorf("read body failed: %v", err)
rsp.ErrRsp(c, -4, "read body failed")
return
}
if resp.StatusCode != http.StatusOK {
log.Errorf("server responded with status code: %d", resp.StatusCode)
rsp.ErrRsp(c, -3, fmt.Sprintf("get version failed, server returns status code: %d, body: %s", resp.StatusCode, string(body)))
return
}
latestVersion := strings.ReplaceAll(string(body), "\n", "")
rsp.OkRspWithData(c, &proto.GetVersionRsp{
Current: currentVersion,
Latest: latestVersion,
})
}
func (s *Service) Update(c *gin.Context) {
var rsp proto.Response
log.Debugf("update application api triggered")
if err := updateApp(); err != nil {
log.Debugf("update failed: %s", err)
rsp.ErrRsp(c, -1, fmt.Sprintf("update failed: %s", err))
return
}
rsp.OkRsp(c)
log.Debugf("update application success")
// Sleep for a second before restarting the device
time.Sleep(1 * time.Second)
_ = exec.Command("sh", "-c", "/etc/init.d/S95nanokvm restart").Run()
}
func updateApp() error {
log.Debugf("update application")
_ = os.RemoveAll(temporary)
_ = os.MkdirAll(temporary, 0o755)
defer func() {
_ = os.RemoveAll(temporary)
}()
if err := downloadLib(); err != nil {
log.Errorf("download lib failed: %s", err)
return err
}
if err := downloadApp(); err != nil {
log.Errorf("download app failed: %s", err)
return err
}
err := utils.MoveFile(temporary+"/"+libName, temporary+"/latest/kvm_system/dl_lib/"+libName) // move lib
if err != nil {
log.Errorf("rename lib failed: %s", err)
return err
}
// backup old version
err = os.RemoveAll(backup)
if err != nil {
log.Errorf("remove backup failed: %s", err)
return err
}
err = utils.MoveFilesRecursively(workspace, backup)
if err != nil {
log.Errorf("backuping old libraries failed: %s", err)
return err
}
// update
err = utils.MoveFilesRecursively(temporary+"/latest", workspace)
if err != nil {
log.Errorf("failed to move update back in place: %s", err)
return err
}
// modify permissions
err = utils.ChmodRecursively(workspace, 0o755)
if err != nil {
log.Errorf("chmod failed: %s", err)
return err
}
return nil
}
func downloadApp() error {
var err error
log.Debugf("downloading latest application...")
url := fmt.Sprintf("%s?now=%d", applicationURL, time.Now().Unix())
for i := range maxTries {
log.Debugf("attempt #%d/%d", i+1, maxTries)
if i > 0 {
time.Sleep(time.Second * 3) // wait for 3 seconds before retrying the download attempt
}
var req *http.Request
req, err = http.NewRequest("GET", url, nil)
if err != nil {
log.Errorf("new request err: %s", err)
continue
}
zipFile := temporary + "/latest.zip"
log.Debugf("update will be saved to: %s", zipFile)
err = utils.Download(req, zipFile)
if err != nil {
log.Errorf("downloading latest application failed, try again...")
continue
}
err = utils.Unzip(zipFile, temporary)
if err != nil {
log.Errorf("unzip app failed: %s", err)
continue
}
return nil
}
return err
}
func downloadLib() error {
log.Debugf("downloading libs...")
content, err := os.ReadFile("/device_key")
if err != nil {
log.Errorf("error reading device key: %s", err)
return err
}
deviceKey := strings.ReplaceAll(string(content), "\n", "")
for i := range maxTries {
log.Debugf("attempt #%d/%d", i+1, maxTries)
if i > 0 {
time.Sleep(time.Second * 3) // wait for 3 seconds before retrying the download attempt
}
var req *http.Request
url := fmt.Sprintf("%s?uid=%s", libURL, deviceKey)
req, err = http.NewRequest("GET", url, nil)
if err != nil {
log.Errorf("error creating new request: %s", err)
continue
}
req.Header.Set("token", "MaixVision2024")
target := fmt.Sprintf("%s/%s", temporary, libName)
err = utils.Download(req, target)
if err != nil {
log.Errorf("downloading lib failed: %s", err)
continue
}
return nil
}
return err
}

View File

@@ -0,0 +1,19 @@
package application
const (
versionURL = "https://cdn.sipeed.com/nanokvm/latest"
applicationURL = "https://cdn.sipeed.com/nanokvm/latest.zip"
libURL = "https://maixvision.sipeed.com/api/v1/nanokvm/encryption"
temporary = "/root/.kvmcache"
workspace = "/kvmapp"
backup = "/root/old"
libName = "libmaixcam_lib.so"
versionFile = "/kvmapp/version"
)
type Service struct{}
func NewService() *Service {
return &Service{}
}

View File

@@ -0,0 +1,79 @@
package auth
import (
"encoding/json"
"errors"
"os"
"path/filepath"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/utils"
)
const AccountFile = "/etc/kvm/pwd"
type Account struct {
Username string `json:"username"`
Password string `json:"password"`
}
func getAccount() (*Account, error) {
// use default account
if _, err := os.Stat(AccountFile); err != nil {
if errors.Is(err, os.ErrNotExist) {
return &Account{
Username: "admin",
Password: "admin",
}, nil
}
return nil, err
}
content, err := os.ReadFile(AccountFile)
if err != nil {
return nil, err
}
var account Account
err = json.Unmarshal(content, &account)
if err != nil {
log.Errorf("unmarshal account failed: %s", err)
return nil, err
}
password, err := utils.DecodeDecrypt(account.Password)
if err != nil {
return nil, err
}
account.Password = password
return &account, nil
}
func setAccount(username string, password string) error {
account, err := json.Marshal(&Account{
Username: username,
Password: password,
})
if err != nil {
log.Errorf("failed to marshal account information to json: %s", err)
return err
}
err = os.MkdirAll(filepath.Dir(AccountFile), 0o644)
if err != nil {
log.Errorf("create directory %s failed: %s", AccountFile, err)
return err
}
err = os.WriteFile(AccountFile, account, 0o644)
if err != nil {
log.Errorf("write password failed: %s", err)
return err
}
return nil
}

View File

@@ -0,0 +1,96 @@
package auth
import (
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/config"
"NanoKVM-Server/middleware"
"NanoKVM-Server/proto"
"NanoKVM-Server/utils"
)
func (s *Service) Login(c *gin.Context) {
var req proto.LoginReq
var rsp proto.Response
// authentication disabled
conf := config.GetInstance()
if conf.Authentication == "disable" {
rsp.OkRspWithData(c, &proto.LoginRsp{
Token: "disabled",
})
return
}
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid parameters")
return
}
passwordDecrypt, err := utils.DecodeDecrypt(req.Password)
if err != nil {
rsp.ErrRsp(c, -2, "decrypt password failed")
return
}
account, err := getAccount()
if err != nil {
rsp.ErrRsp(c, -3, "get account failed")
return
}
if req.Username != account.Username || passwordDecrypt != account.Password {
rsp.ErrRsp(c, -4, "invalid username or password")
return
}
token, err := middleware.GenerateJWT(req.Username)
if err != nil {
rsp.ErrRsp(c, -5, "generate token failed")
return
}
rsp.OkRspWithData(c, &proto.LoginRsp{
Token: token,
})
log.Debugf("login success, username: %s", req.Username)
}
func (s *Service) ChangePassword(c *gin.Context) {
var req proto.ChangePasswordReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid parameters")
return
}
if err := setAccount(req.Username, req.Password); err != nil {
rsp.ErrRsp(c, -2, "change password failed")
return
}
rsp.OkRsp(c)
log.Debugf("change password success, username: %s", req.Username)
}
func (s *Service) IsPasswordUpdated(c *gin.Context) {
var rsp proto.Response
account, err := getAccount()
if err != nil {
rsp.ErrRsp(c, -1, "failed to get password")
}
isUpdated := true
if account == nil || account.Password == "admin" {
isUpdated = false
}
rsp.OkRspWithData(c, &proto.IsPasswordUpdatedRsp{
IsUpdated: isUpdated,
})
log.Debugf("get password success")
}

View File

@@ -0,0 +1,7 @@
package auth
type Service struct{}
func NewService() *Service {
return &Service{}
}

View File

@@ -0,0 +1,29 @@
package hid
const (
MouseUp = iota
MouseDown
MouseMoveAbsolute
MouseMoveRelative
MouseScroll
)
const (
MouseLeft = 1
MouseRight = 2
MouseWheel = 3
)
const (
HidMouseLeft byte = 0x01
HidMouseRight byte = 0x02
HidMouseWheel byte = 0x04
)
const (
ModifierLCtrl byte = 0x01
ModifierLShift byte = 0x02
ModifierLAlt byte = 0x04
ModifierLGUI byte = 0x08
ModifierRAlt byte = 0x40
)

36
server/service/hid/hid.go Normal file
View File

@@ -0,0 +1,36 @@
package hid
import (
"os"
"sync"
)
var (
hid *Hid
hidOnce sync.Once
)
type Hid struct {
g0 *os.File
g1 *os.File
g2 *os.File
kbMutex sync.Mutex
mouseMutex sync.Mutex
}
func (h *Hid) Lock() {
h.kbMutex.Lock()
h.mouseMutex.Lock()
}
func (h *Hid) Unlock() {
h.kbMutex.Unlock()
h.mouseMutex.Unlock()
}
func GetHid() *Hid {
hidOnce.Do(func() {
hid = &Hid{}
})
return hid
}

View File

@@ -0,0 +1,47 @@
package hid
func (h *Hid) Keyboard(queue <-chan []int) {
for event := range queue {
h.kbMutex.Lock()
h.writeKeyboard(event)
h.kbMutex.Unlock()
}
}
func (h *Hid) writeKeyboard(event []int) {
var data []byte
if event[0] > 0 {
code := byte(event[0])
modifier := getModifier(event)
data = []byte{modifier, 0x00, code, 0x00, 0x00, 0x00, 0x00, 0x00}
} else {
data = []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
}
h.Write(h.g0, data)
}
func getModifier(event []int) byte {
var modifier byte = 0x00
if event[1] == 1 {
modifier |= ModifierLCtrl
}
if event[2] == 1 {
modifier |= ModifierLShift
}
if event[3] == 1 {
modifier |= ModifierLAlt
} else if event[3] == 2 {
modifier |= ModifierRAlt
}
if event[4] == 1 {
modifier |= ModifierLGUI
}
return modifier
}

102
server/service/hid/mouse.go Normal file
View File

@@ -0,0 +1,102 @@
package hid
import (
"encoding/binary"
"errors"
"os"
"time"
log "github.com/sirupsen/logrus"
)
func (h *Hid) Mouse(queue <-chan []int) {
for event := range queue {
h.mouseMutex.Lock()
switch event[0] {
case MouseDown:
h.mouseDown(event)
case MouseUp:
h.mouseUp()
case MouseMoveAbsolute:
h.mouseMoveAbsolute(event)
case MouseMoveRelative:
h.mouseMoveRelative(event)
case MouseScroll:
h.scroll(event)
default:
log.Debugf("invalid mouse event: %+v", event)
}
h.mouseMutex.Unlock()
}
}
func (h *Hid) mouseDown(event []int) {
var button byte
switch event[1] {
case MouseLeft:
button = HidMouseLeft
case MouseRight:
button = HidMouseRight
case MouseWheel:
button = HidMouseWheel
default:
log.Debugf("invalid mouse button: %+v", event)
return
}
data := []byte{button, 0, 0, 0}
h.writeWithTimeout(h.g1, data)
}
func (h *Hid) mouseUp() {
data := []byte{0, 0, 0, 0}
h.writeWithTimeout(h.g1, data)
}
func (h *Hid) scroll(event []int) {
direction := 0x01
if event[3] > 0 {
direction = -0x1
}
data := []byte{0, 0, 0, byte(direction)}
h.writeWithTimeout(h.g1, data)
}
func (h *Hid) mouseMoveAbsolute(event []int) {
x := make([]byte, 2)
y := make([]byte, 2)
binary.LittleEndian.PutUint16(x, uint16(event[2]))
binary.LittleEndian.PutUint16(y, uint16(event[3]))
data := []byte{0, x[0], x[1], y[0], y[1], 0}
h.writeWithTimeout(h.g2, data)
}
func (h *Hid) mouseMoveRelative(event []int) {
data := []byte{byte(event[1]), byte(event[2]), byte(event[3]), 0}
h.writeWithTimeout(h.g1, data)
}
func (h *Hid) writeWithTimeout(file *os.File, data []byte) {
deadline := time.Now().Add(8 * time.Millisecond)
_ = file.SetWriteDeadline(deadline)
_, err := file.Write(data)
if err != nil {
switch {
case errors.Is(err, os.ErrClosed):
log.Debugf("hid already closed, reopen it...")
h.OpenNoLock()
case errors.Is(err, os.ErrDeadlineExceeded):
log.Debugf("write to hid timeout")
default:
log.Errorf("write to hid failed: %s", err)
}
return
}
log.Debugf("write to hid: %+v", data)
}

View File

@@ -0,0 +1,73 @@
package hid
import (
"errors"
"os"
log "github.com/sirupsen/logrus"
)
func (h *Hid) OpenNoLock() {
var err error
h.CloseNoLock()
h.g0, err = os.OpenFile("/dev/hidg0", os.O_WRONLY, 0o666)
if err != nil {
log.Errorf("open /dev/hidg0 failed: %s", err)
}
h.g1, err = os.OpenFile("/dev/hidg1", os.O_WRONLY, 0o666)
if err != nil {
log.Errorf("open /dev/hidg1 failed: %s", err)
}
h.g2, err = os.OpenFile("/dev/hidg2", os.O_WRONLY, 0o666)
if err != nil {
log.Errorf("open /dev/hidg2 failed: %s", err)
}
}
func (h *Hid) Open() {
h.kbMutex.Lock()
defer h.kbMutex.Unlock()
h.mouseMutex.Lock()
defer h.mouseMutex.Unlock()
h.CloseNoLock()
h.OpenNoLock()
}
func (h *Hid) CloseNoLock() {
for _, file := range []*os.File{h.g0, h.g1, h.g2} {
if file != nil {
_ = file.Sync()
_ = file.Close()
}
}
}
func (h *Hid) Close() {
h.kbMutex.Lock()
defer h.kbMutex.Unlock()
h.mouseMutex.Lock()
defer h.mouseMutex.Unlock()
h.CloseNoLock()
}
func (h *Hid) Write(file *os.File, data []byte) {
_, err := file.Write(data)
if err != nil {
if errors.Is(err, os.ErrClosed) {
log.Debugf("hid already closed, reopen it...")
h.OpenNoLock()
} else {
log.Errorf("write to hid failed: %s", err)
}
return
}
log.Debugf("write to hid: %+v", data)
}

172
server/service/hid/paste.go Normal file
View File

@@ -0,0 +1,172 @@
package hid
import (
"time"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/proto"
)
type Char struct {
Modifiers int
Code int
}
type PasteReq struct {
Content string `form:"content" validate:"required"`
}
func (s *Service) Paste(c *gin.Context) {
var req PasteReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
if len(req.Content) > 1024 {
rsp.ErrRsp(c, -2, "")
return
}
s.hid.kbMutex.Lock()
for _, char := range req.Content {
key, ok := charMap[char]
if !ok {
log.Debugf("unknown key %c", char)
continue
}
keyDown := []byte{byte(key.Modifiers), 0x00, byte(key.Code), 0x00, 0x00, 0x00, 0x00, 0x00}
keyUp := []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
// only handle shift. Need to handle all modifiers?
if key.Modifiers > 0 {
keyShift := []byte{0x00, 0x00, byte(225), 0x00, 0x00, 0x00, 0x00, 0x00}
s.hid.Write(s.hid.g0, keyShift)
}
s.hid.Write(s.hid.g0, keyDown)
s.hid.Write(s.hid.g0, keyUp)
if key.Modifiers > 0 {
s.hid.Write(s.hid.g0, keyUp)
}
time.Sleep(50 * time.Millisecond)
}
s.hid.kbMutex.Unlock()
rsp.OkRsp(c)
log.Debugf("hid paste success, total %d", len(req.Content))
}
var charMap = map[rune]Char{
97: {0, 4}, // a
98: {0, 5}, // b
99: {0, 6}, // c
100: {0, 7}, // d
101: {0, 8}, // e
102: {0, 9}, // f
103: {0, 10}, // g
104: {0, 11}, // h
105: {0, 12}, // i
106: {0, 13}, // j
107: {0, 14}, // k
108: {0, 15}, // l
109: {0, 16}, // m
110: {0, 17}, // n
111: {0, 18}, // o
112: {0, 19}, // p
113: {0, 20}, // q
114: {0, 21}, // r
115: {0, 22}, // s
116: {0, 23}, // t
117: {0, 24}, // u
118: {0, 25}, // v
119: {0, 26}, // w
120: {0, 27}, // x
121: {0, 28}, // y
122: {0, 29}, // z
49: {0, 30}, // 1
50: {0, 31}, // 2
51: {0, 32}, // 3
52: {0, 33}, // 4
53: {0, 34}, // 5
54: {0, 35}, // 6
55: {0, 36}, // 7
56: {0, 37}, // 8
57: {0, 38}, // 9
48: {0, 39}, // 0
10: {0, 40}, // Enter
9: {0, 43}, // Tab
32: {0, 44}, // Space
45: {0, 45}, // -
61: {0, 46}, // =
91: {0, 47}, // [
93: {0, 48}, // ]
92: {0, 49}, // \
59: {0, 51}, // ;
39: {0, 52}, // '
96: {0, 53}, // `
44: {0, 54}, // ,
46: {0, 55}, // .
47: {0, 56}, // /
65: {2, 4}, // A
66: {2, 5}, // B
67: {2, 6}, // C
68: {2, 7}, // D
69: {2, 8}, // E
70: {2, 9}, // F
71: {2, 10}, // G
72: {2, 11}, // H
73: {2, 12}, // I
74: {2, 13}, // J
75: {2, 14}, // K
76: {2, 15}, // L
77: {2, 16}, // M
78: {2, 17}, // N
79: {2, 18}, // O
80: {2, 19}, // P
81: {2, 20}, // Q
82: {2, 21}, // R
83: {2, 22}, // S
84: {2, 23}, // T
85: {2, 24}, // U
86: {2, 25}, // V
87: {2, 26}, // W
88: {2, 27}, // X
89: {2, 28}, // Y
90: {2, 29}, // Z
33: {2, 30}, // !
64: {2, 31}, // @
35: {2, 32}, // #
36: {2, 33}, // $
37: {2, 34}, // %
94: {2, 35}, // ^
38: {2, 36}, // &
42: {2, 37}, // *
40: {2, 38}, // (
41: {2, 39}, // )
95: {2, 45}, // _
43: {2, 46}, // +
123: {2, 47}, // {
125: {2, 48}, // }
124: {2, 49}, // |
58: {2, 51}, // :
34: {2, 52}, // "
126: {2, 53}, // ~
60: {2, 54}, // <
62: {2, 55}, // >
63: {2, 56}, // ?
}

View File

@@ -0,0 +1,74 @@
package hid
import (
"NanoKVM-Server/proto"
"os"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
func (s *Service) Reset(c *gin.Context) {
var rsp proto.Response
s.hid.kbMutex.Lock()
defer s.hid.kbMutex.Unlock()
// reset USB
f, err := os.OpenFile("/sys/kernel/config/usb_gadget/g0/UDC", os.O_WRONLY, 0644)
if err != nil {
log.Errorf("open /sys/kernel/config/usb_gadget/g0/UDC failed: %s", err)
rsp.ErrRsp(c, -1, "open usb gadget file failed")
return
}
err = f.Truncate(0)
if err != nil {
_ = f.Close()
log.Errorf("truncate /sys/kernel/config/usb_gadget/g0/UDC failed: %s", err)
rsp.ErrRsp(c, -1, "truncate usb gadget file failed")
return
}
_, err = f.Seek(0, 0)
if err != nil {
_ = f.Close()
log.Errorf("seek to 0 failed: %s", err)
rsp.ErrRsp(c, -1, "seek to 0 in usb gadget file failed")
return
}
_, err = f.WriteString("\n")
if err != nil {
_ = f.Close()
log.Errorf("write to /sys/kernel/config/usb_gadget/g0/UDC failed: %s", err)
rsp.ErrRsp(c, -1, "write to usb gadget file failed")
return
}
_ = f.Close()
devices, err := os.ReadDir("/sys/class/udc/")
if err != nil {
log.Errorf("read udc directory failed: %s", err)
rsp.ErrRsp(c, -1, "read udc directory failed")
return
}
f, err = os.OpenFile("/sys/kernel/config/usb_gadget/g0/UDC", os.O_WRONLY, 0644)
if err != nil {
log.Errorf("open /sys/kernel/config/usb_gadget/g0/UDC failed: %s", err)
rsp.ErrRsp(c, -1, "open usb gadget file failed")
return
}
for _, device := range devices {
_, err = f.WriteString(device.Name() + "\n")
if err != nil {
_ = f.Close()
log.Errorf("write to /sys/kernel/config/usb_gadget/g0/UDC failed: %s", err)
rsp.ErrRsp(c, -1, "write to usb gadget file failed")
return
}
}
_ = f.Close()
rsp.OkRsp(c)
log.Debugf("reset hid success")
}

View File

@@ -0,0 +1,11 @@
package hid
type Service struct {
hid *Hid
}
func NewService() *Service {
return &Service{
hid: GetHid(),
}
}

View File

@@ -0,0 +1,7 @@
package network
type Service struct{}
func NewService() *Service {
return &Service{}
}

View File

@@ -0,0 +1,322 @@
package network
import (
"bufio"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
"regexp"
"strings"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/proto"
"NanoKVM-Server/utils"
)
const (
tailscalePath = "/usr/bin/tailscale"
tailscaledPath = "/usr/sbin/tailscaled"
backendStateRunning = "Running"
backendStateNeedsLogin = "NeedsLogin"
backendStateStopped = "Stopped"
responseStateRunning = "running"
responseStateNeedsLogin = "notLogin"
responseStateStopped = "stopped"
responseStateNotInstalled = "notInstall"
)
var backendToResponseStates = map[string]string{
backendStateRunning: responseStateRunning,
backendStateNeedsLogin: responseStateNeedsLogin,
backendStateStopped: responseStateStopped,
}
func stateToJson(state string) string {
if resp, ok := backendToResponseStates[state]; ok {
return resp
}
return ""
}
type TailscaleStatus struct {
BackendState string `json:"BackendState"`
Self struct {
HostName string `json:"HostName"`
TailscaleIPs []string `json:"TailscaleIPs"`
} `json:"Self"`
CurrentTailnet struct {
Name string `json:"Name"`
} `json:"CurrentTailnet"`
}
func (s *Service) InstallTailscale(c *gin.Context) {
var rsp proto.Response
if exist := isTailscaleExist(); exist {
rsp.OkRsp(c)
return
}
const (
downloadUrl = "https://cdn.sipeed.com/nanokvm/resources/tailscale_riscv64.zip"
workspace = "/root/.tailscale"
)
var (
zipFile = fmt.Sprintf("%s/tailscale_riscv64.zip", workspace)
tailscale = fmt.Sprintf("%s/tailscale_riscv64/tailscale", workspace)
tailscaled = fmt.Sprintf("%s/tailscale_riscv64/tailscaled", workspace)
)
// download
_ = os.MkdirAll(workspace, 0o755)
defer func() {
_ = os.RemoveAll(workspace)
}()
req, err := http.NewRequest("GET", downloadUrl, nil)
if err != nil {
log.Errorf("failed to create new request: %s", err)
rsp.ErrRsp(c, -1, "request failed")
return
}
err = utils.Download(req, zipFile)
if err != nil {
log.Errorf("download failed: %s", err)
rsp.ErrRsp(c, -2, "download failed")
return
}
// install
err = utils.Unzip(zipFile, workspace)
if err != nil {
log.Errorf("unzip failed: %s", err)
rsp.ErrRsp(c, -3, "unzip failed")
return
}
err = utils.MoveFile(tailscale, tailscalePath)
if err != nil {
log.Errorf("rename %s failed: %s", tailscale, err)
}
err = utils.MoveFile(tailscaled, tailscaledPath)
if err != nil {
log.Errorf("rename %s failed: %s", tailscaled, err)
}
_ = runTailscale()
rsp.OkRsp(c)
log.Debugf("install tailscaled success")
}
func (s *Service) LoginTailscale(c *gin.Context) {
var rsp proto.Response
status, err := getTailscaleStatus()
if err != nil {
_ = runTailscale()
status, err = getTailscaleStatus()
}
if err != nil {
rsp.ErrRsp(c, -1, "tailscale unknown status")
return
}
if status.BackendState == backendStateRunning {
rsp.OkRspWithData(c, &proto.LoginTailscaleRsp{
Status: responseStateRunning,
})
return
}
cmd := exec.Command("sh", "-c", "tailscale login --timeout=10m")
stderr, err := cmd.StderrPipe()
if err != nil {
rsp.ErrRsp(c, -2, "tailscale login failed")
return
}
defer func() {
_ = stderr.Close()
}()
go func() {
_ = cmd.Run()
}()
url := parseLoginUrl(stderr)
rsp.OkRspWithData(c, &proto.LoginTailscaleRsp{
Status: responseStateNeedsLogin,
Url: url,
})
log.Debugf("tailscale login url: %s", url)
}
func (s *Service) LogoutTailscale(c *gin.Context) {
var rsp proto.Response
cmd := exec.Command("sh", "-c", "tailscale logout")
err := cmd.Run()
if err != nil {
rsp.ErrRsp(c, -2, "tailscale logout failed")
return
}
rsp.OkRsp(c)
log.Debugf("tailscale logout success")
}
func (s *Service) GetTailscaleStatus(c *gin.Context) {
var rsp proto.Response
var data proto.GetTailscaleStatusRsp
if exist := isTailscaleExist(); !exist {
data.Status = responseStateNotInstalled
rsp.OkRspWithData(c, data)
return
}
status, err := getTailscaleStatus()
if err != nil {
data.Status = responseStateNeedsLogin
rsp.OkRspWithData(c, data)
return
}
data.Status = stateToJson(status.BackendState)
if data.Status == "" {
rsp.ErrRsp(c, -1, "unknown state")
return
}
for _, tailscaleIp := range status.Self.TailscaleIPs {
ip := net.ParseIP(tailscaleIp)
if ip != nil && ip.To4() != nil {
data.IP = ip.String()
}
}
data.Name = status.Self.HostName
data.Account = status.CurrentTailnet.Name
rsp.OkRspWithData(c, data)
log.Debugf("tailscale status: %s", data.Status)
}
func (s *Service) UpdateTailscaleStatus(c *gin.Context) {
var req proto.UpdateTailscaleStatusReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
command := fmt.Sprintf("tailscale %s", req.Command)
err := exec.Command("sh", "-c", command).Run()
if err != nil {
msg := fmt.Sprintf("tailscale %s failed", req.Command)
rsp.ErrRsp(c, -2, msg)
return
}
status, err := getTailscaleStatus()
if err != nil {
rsp.ErrRsp(c, -3, "get tailscale status failed")
return
}
data := &proto.UpdateTailscaleStatusRsp{}
switch status.BackendState {
case backendStateRunning:
data.Status = responseStateRunning
case backendStateStopped:
data.Status = responseStateStopped
default:
rsp.ErrRsp(c, -4, "unknown tailscale status")
return
}
rsp.OkRspWithData(c, data)
log.Debugf("tailscale %s success", req.Command)
}
func isTailscaleExist() bool {
_, err1 := os.Stat(tailscalePath)
_, err2 := os.Stat(tailscaledPath)
return err1 == nil && err2 == nil
}
func runTailscale() error {
for _, filePath := range []string{tailscalePath, tailscaledPath} {
if err := utils.EnsurePermission(filePath, 0o100); err != nil {
return err
}
}
err := exec.Command("sh", "-c", "/etc/init.d/S98tailscaled start").Run()
if err != nil {
return err
}
return nil
}
func getTailscaleStatus() (TailscaleStatus, error) {
var status TailscaleStatus
command := "tailscale status --json"
cmd := exec.Command("sh", "-c", command)
output, err := cmd.CombinedOutput()
if err != nil {
log.Debugf("get tailscale status failed: %s", err)
return status, err
}
// delete warning message
if str := string(output); !strings.HasPrefix(str, "{") {
index := strings.Index(str, "{")
if index != -1 {
output = []byte(str[index:])
}
}
err = json.Unmarshal(output, &status)
if err != nil {
log.Debugf("unmarshal tailscale status failed: %s", err)
return status, err
}
return status, nil
}
func parseLoginUrl(r io.Reader) string {
reader := bufio.NewReader(r)
for {
line, err := reader.ReadString('\n')
if err != nil {
log.Errorf("reading line failed: %s", err)
return ""
}
if strings.Contains(line, "https") {
reg := regexp.MustCompile(`\s+`)
return reg.ReplaceAllString(line, "")
}
}
}

View File

@@ -0,0 +1,141 @@
package network
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/proto"
)
const (
WolHistory = "/etc/kvm/cache/wol"
)
func (s *Service) WakeOnLAN(c *gin.Context) {
var req proto.WakeOnLANReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
command := fmt.Sprintf("ether-wake %s", req.Mac)
cmd := exec.Command("sh", "-c", command)
output, err := cmd.CombinedOutput()
if err != nil {
log.Errorf("wake on lan failed: %s", err)
rsp.ErrRsp(c, -2, string(output))
return
}
go saveMac(req.Mac)
rsp.OkRsp(c)
log.Debugf("wake on lan %s success", req.Mac)
}
func (s *Service) GetMac(c *gin.Context) {
var rsp proto.Response
content, err := os.ReadFile(WolHistory)
if err != nil {
rsp.ErrRsp(c, -2, "open file error")
return
}
macs := strings.Split(string(content), "\n")
data := &proto.GetMacRsp{
Macs: macs,
}
rsp.OkRspWithData(c, data)
}
func (s *Service) DeleteMac(c *gin.Context) {
var req proto.DeleteMacReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
content, err := os.ReadFile(WolHistory)
if err != nil {
log.Errorf("open %s failed: %s", WolHistory, err)
rsp.ErrRsp(c, -2, "read failed")
return
}
macs := strings.Split(string(content), "\n")
var newMacs []string
for _, mac := range macs {
if req.Mac != mac {
newMacs = append(newMacs, mac)
}
}
data := strings.Join(newMacs, "\n")
err = os.WriteFile(WolHistory, []byte(data), 0o644)
if err != nil {
log.Errorf("write %s failed: %s", WolHistory, err)
rsp.ErrRsp(c, -3, "write failed")
return
}
rsp.OkRsp(c)
log.Debugf("delete mac %s success", req.Mac)
}
func saveMac(mac string) {
if isMacExist(mac) {
return
}
err := os.MkdirAll(filepath.Dir(WolHistory), 0o644)
if err != nil {
log.Errorf("create dir failed: %s", err)
return
}
file, err := os.OpenFile(WolHistory, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
log.Errorf("open %s failed: %s", WolHistory, err)
return
}
defer func() {
_ = file.Close()
}()
content := fmt.Sprintf("%s\n", mac)
_, err = file.WriteString(content)
if err != nil {
log.Errorf("write %s failed: %s", WolHistory, err)
return
}
}
func isMacExist(mac string) bool {
content, err := os.ReadFile(WolHistory)
if err != nil {
return false
}
macs := strings.Split(string(content), "\n")
for _, item := range macs {
if mac == item {
return true
}
}
return false
}

View File

@@ -0,0 +1,108 @@
package storage
import (
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/proto"
)
const (
imageDirectory = "/data"
imageNone = "/dev/mmcblk0p3"
mountDevice = "/sys/kernel/config/usb_gadget/g0/functions/mass_storage.disk0/lun.0/file"
)
func (s *Service) GetImages(c *gin.Context) {
var rsp proto.Response
var images []string
err := filepath.Walk(imageDirectory, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
name := strings.ToLower(info.Name())
if strings.HasSuffix(name, ".iso") || strings.HasSuffix(name, ".img") {
images = append(images, path)
}
}
return nil
})
if err != nil {
rsp.ErrRsp(c, -2, "get images failed")
return
}
rsp.OkRspWithData(c, &proto.GetImagesRsp{
Files: images,
})
log.Debugf("get images success, total %d", len(images))
}
func (s *Service) MountImage(c *gin.Context) {
var req proto.MountImageReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
image := req.File
if image == "" {
image = imageNone
}
// mount
if err := os.WriteFile(mountDevice, []byte(image), 0o666); err != nil {
log.Errorf("mount file %s failed: %s", image, err)
rsp.ErrRsp(c, -2, "mount image failed")
return
}
// reset usb
commands := []string{
"echo > /sys/kernel/config/usb_gadget/g0/UDC",
"ls /sys/class/udc/ | cat > /sys/kernel/config/usb_gadget/g0/UDC",
}
for _, command := range commands {
err := exec.Command("sh", "-c", command).Run()
if err != nil {
rsp.ErrRsp(c, -2, "execute command failed")
return
}
}
rsp.OkRsp(c)
log.Debugf("mount image %s success", req.File)
}
func (s *Service) GetMountedImage(c *gin.Context) {
var rsp proto.Response
content, err := os.ReadFile(mountDevice)
if err != nil {
rsp.ErrRsp(c, -2, "read failed")
return
}
image := strings.ReplaceAll(string(content), "\n", "")
if image == imageNone {
image = ""
}
data := &proto.GetMountedImageRsp{
File: image,
}
rsp.OkRspWithData(c, data)
}

View File

@@ -0,0 +1,7 @@
package storage
type Service struct{}
func NewService() *Service {
return &Service{}
}

View File

@@ -0,0 +1,63 @@
package stream
import (
"fmt"
"os"
"sync"
"sync/atomic"
"time"
log "github.com/sirupsen/logrus"
)
var (
counter *FrameRateCounter
counterOnce sync.Once
)
type FrameRateCounter struct {
frameCount int32
fps int32
mutex sync.Mutex
}
func GetFrameRateCounter() *FrameRateCounter {
counterOnce.Do(func() {
counter = &FrameRateCounter{}
go func() {
ticker := time.NewTicker(3 * time.Second)
defer ticker.Stop()
for range ticker.C {
counter.mutex.Lock()
currentCount := atomic.LoadInt32(&counter.frameCount)
counter.fps = currentCount / 3
atomic.StoreInt32(&counter.frameCount, 0)
counter.mutex.Unlock()
data := fmt.Sprintf("%d", counter.fps)
err := os.WriteFile("/kvmapp/kvm/now_fps", []byte(data), 0o666)
if err != nil {
log.Errorf("failed to wirte fps: %s", err)
}
}
}()
})
return counter
}
func (f *FrameRateCounter) Update() {
atomic.AddInt32(&f.frameCount, 1)
}
func (f *FrameRateCounter) GetFPS() int32 {
f.mutex.Lock()
defer f.mutex.Unlock()
return f.fps
}

View File

@@ -0,0 +1,173 @@
package h264
import (
"encoding/json"
"github.com/gorilla/websocket"
"github.com/pion/webrtc/v4"
log "github.com/sirupsen/logrus"
)
type Client struct {
ws *websocket.Conn
pc *webrtc.PeerConnection
}
type Message struct {
Event string `json:"event"`
Data string `json:"data"`
}
// add video track
func (c *Client) addTrack() {
videoTrack, err := webrtc.NewTrackLocalStaticSample(
webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeH264},
"video",
"pion",
)
if err != nil {
log.Errorf("failed to create video track: %s", err)
return
}
_, err = c.pc.AddTrack(videoTrack)
if err != nil {
log.Errorf("failed to add video track: %s", err)
return
}
mutex.Lock()
trackMap[c.ws] = videoTrack
mutex.Unlock()
}
// register callback events
func (c *Client) register() {
// new ICE candidate found
c.pc.OnICECandidate(func(candidate *webrtc.ICECandidate) {
if candidate == nil {
return
}
candidateByte, err := json.Marshal(candidate.ToJSON())
if err != nil {
log.Errorf("failed to marshal candidate: %s", err)
return
}
_ = c.sendMessage("candidate", string(candidateByte))
})
// ICE connection state has changed
c.pc.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) {
if state == webrtc.ICEConnectionStateConnected && !isSending {
mutex.Lock()
if !isSending {
// start sending h264 data
go send()
isSending = true
}
mutex.Unlock()
}
log.Debugf("ice connection state has changed to %s", state.String())
})
}
// read websocket message
func (c *Client) readMessage() {
message := &Message{}
for {
_, raw, err := c.ws.ReadMessage()
if err != nil {
mutex.Lock()
delete(trackMap, c.ws)
if len(trackMap) == 0 && isSending {
// stop sending when all websocket connections are closed
exitSig <- true
}
mutex.Unlock()
log.Debugf("failed to read message: %s", err)
return
}
if err := json.Unmarshal(raw, &message); err != nil {
log.Errorf("failed to unmarshal message: %s", err)
continue
}
log.Debugf("receive message event: %s", message.Event)
switch message.Event {
case "offer":
offer := webrtc.SessionDescription{}
if err := json.Unmarshal([]byte(message.Data), &offer); err != nil {
log.Errorf("failed to unmarshal offer message: %s", err)
return
}
if err := c.pc.SetRemoteDescription(offer); err != nil {
log.Errorf("failed to set remote description: %s", err)
return
}
answer, answerErr := c.pc.CreateAnswer(nil)
if answerErr != nil {
log.Errorf("failed to create answer: %s", answerErr)
return
}
if err := c.pc.SetLocalDescription(answer); err != nil {
log.Errorf("failed to set local description: %s", err)
return
}
answerByte, answerByteErr := json.Marshal(answer)
if answerByteErr != nil {
log.Errorf("failed to marshal answer: %s", answerByteErr)
return
}
_ = c.sendMessage("answer", string(answerByte))
case "candidate":
candidate := webrtc.ICECandidateInit{}
if err := json.Unmarshal([]byte(message.Data), &candidate); err != nil {
log.Errorf("failed to unmarshal candidate message: %s", err)
return
}
if err := c.pc.AddICECandidate(candidate); err != nil {
log.Errorf("failed to add ICE candidate: %s", err)
return
}
case "heartbeat":
_ = c.sendMessage("heartbeat", "")
default:
log.Debugf("unhandled message event: %s", message.Event)
}
}
}
// send websocket message
func (c *Client) sendMessage(event string, data string) error {
mutex.RLock()
defer mutex.RUnlock()
message := &Message{
Event: event,
Data: data,
}
if err := c.ws.WriteJSON(message); err != nil {
log.Errorf("failed to send message %s: %s", event, err)
return err
}
log.Debugf("send message %s", message.Event)
return nil
}

View File

@@ -0,0 +1,64 @@
package h264
import (
"net/http"
"sync"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/pion/webrtc/v4"
log "github.com/sirupsen/logrus"
)
var (
upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
trackMap = make(map[*websocket.Conn]*webrtc.TrackLocalStaticSample)
mutex = sync.RWMutex{}
isSending = false
exitSig = make(chan bool, 1)
)
func Connect(c *gin.Context) {
wsConn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Errorf("failed to create websocket: %s", err)
return
}
defer func() {
_ = wsConn.Close()
log.Debugf("h264 websocket disconnected")
}()
config := webrtc.Configuration{
ICEServers: []webrtc.ICEServer{
{
URLs: []string{"stun:stun.l.google.com:19302"},
},
},
}
peerConn, err := webrtc.NewPeerConnection(config)
if err != nil {
log.Errorf("failed to create PeerConnection: %s", err)
return
}
defer func() {
_ = peerConn.Close()
log.Debugf("PeerConnection disconnected")
}()
client := &Client{
ws: wsConn,
pc: peerConn,
}
client.addTrack()
client.register()
client.readMessage()
}

View File

@@ -0,0 +1,80 @@
package h264
import (
"NanoKVM-Server/common"
"NanoKVM-Server/service/stream"
"time"
"github.com/pion/webrtc/v4/pkg/media"
log "github.com/sirupsen/logrus"
)
func send() {
screen := common.GetScreen()
fps := screen.FPS
duration := time.Second / time.Duration(fps)
ticker := time.NewTicker(duration)
defer ticker.Stop()
vision := common.GetKvmVision()
for {
select {
case <-ticker.C:
height := screen.Height
width, ok := common.ResolutionMap[height]
if !ok {
width = 0
height = 0
}
bitRate := screen.BitRate
if _, ok := common.BitRateMap[bitRate]; !ok {
bitRate = 3000
}
data, sps, pps, result := vision.ReadH264(width, height, bitRate)
if result < 0 {
continue
}
if result == 3 {
writeSample(sps, duration)
writeSample(pps, duration)
}
writeSample(data, duration)
stream.GetFrameRateCounter().Update()
if screen.FPS != fps {
fps = screen.FPS
duration = time.Second / time.Duration(fps)
ticker.Reset(duration)
}
case <-exitSig:
mutex.Lock()
isSending = false
mutex.Unlock()
return
}
}
}
func writeSample(data []byte, duration time.Duration) {
sample := media.Sample{
Data: data,
Duration: duration,
}
mutex.RLock()
defer mutex.RUnlock()
for _, track := range trackMap {
if err := track.WriteSample(sample); err != nil {
log.Errorf("failed to send h264 data: %s", err)
}
}
log.Debugf("send h264 data: %d", len(data))
}

View File

@@ -0,0 +1,132 @@
package mjpeg
import (
"errors"
"os"
"time"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/proto"
)
const (
frameDetect = "/etc/kvm/frame_detact"
frameDetectTmp = "/etc/kvm/frame_detact_tmp"
)
type UpdateFrameDetectRsp struct {
Enabled bool `json:"enabled"`
}
func GetFrameDetect(c *gin.Context) {
var rsp proto.Response
isEnabled, err := isFrameDetectEnabled()
if err != nil {
rsp.ErrRsp(c, -1, "unknown frame detect status")
return
}
rsp.OkRspWithData(c, &proto.GetFrameDetectRsp{
Enabled: isEnabled,
})
log.Debugf("get frame detect success, enabled: %t", isEnabled)
}
func UpdateFrameDetect(c *gin.Context) {
var rsp proto.Response
isEnabled, err := isFrameDetectEnabled()
if err != nil {
rsp.ErrRsp(c, -1, "unknown frame status")
return
}
if isEnabled {
_ = os.Remove(frameDetect)
_ = os.Remove(frameDetectTmp)
} else {
file, err2 := os.OpenFile(frameDetect, os.O_CREATE|os.O_TRUNC, 0o644)
if err2 != nil {
rsp.ErrRsp(c, -3, "enable frame detect failed")
return
}
defer func() {
_ = file.Close()
}()
}
isEnabled, err = isFrameDetectEnabled()
if err != nil {
rsp.ErrRsp(c, -4, "unknown frame status")
return
}
rsp.OkRspWithData(c, &UpdateFrameDetectRsp{
Enabled: isEnabled,
})
log.Debugf("update frame detect success, enabled: %t", isEnabled)
}
func StopFrameDetect(c *gin.Context) {
var rsp proto.Response
exist, err := isFileExist(frameDetect)
if err != nil {
rsp.ErrRsp(c, -1, "unknown frame status")
return
}
if !exist {
rsp.OkRsp(c)
return
}
err = os.Rename(frameDetect, frameDetectTmp)
if err != nil {
rsp.ErrRsp(c, -2, "stop operation failed")
return
}
go func() {
time.Sleep(20 * time.Second)
_ = os.Rename(frameDetectTmp, frameDetect)
log.Debugf("frame detect started")
}()
rsp.OkRsp(c)
log.Debugf("frame detect stoped")
}
func isFrameDetectEnabled() (bool, error) {
exist, err := isFileExist(frameDetect)
if err != nil {
return false, err
}
if exist {
return true, nil
}
exist, err = isFileExist(frameDetectTmp)
if err != nil {
return false, err
}
return exist, nil
}
func isFileExist(name string) (bool, error) {
_, err := os.Stat(name)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, nil
}
return true, nil
}

View File

@@ -0,0 +1,111 @@
package mjpeg
import (
"NanoKVM-Server/common"
"NanoKVM-Server/service/stream"
"fmt"
"sync"
"time"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
var (
chanMap = make(map[*gin.Context]chan struct{})
mutex = sync.RWMutex{}
exitSig = make(chan bool, 1)
)
func Connect(c *gin.Context) {
c.Header("Content-Type", fmt.Sprintf("multipart/x-mixed-replace; boundary=frame"))
c.Header("Cache-Control", "no-cache")
c.Header("Connection", "keep-alive")
c.Header("Pragma", "no-cache")
mutex.Lock()
chanMap[c] = make(chan struct{}, 1)
if len(chanMap) == 1 {
go send()
}
mutex.Unlock()
<-chanMap[c]
mutex.Lock()
delete(chanMap, c)
if len(chanMap) == 0 {
exitSig <- true
}
mutex.Unlock()
}
func send() {
screen := common.GetScreen()
fps := screen.FPS
ticker := time.NewTicker(time.Second / time.Duration(fps))
defer ticker.Stop()
vision := common.GetKvmVision()
for {
select {
case <-ticker.C:
height := screen.Height
width, ok := common.ResolutionMap[height]
if !ok {
width = 0
height = 0
}
quality := screen.Quality
if _, ok := common.QualityMap[quality]; !ok {
quality = 80
}
data, result := vision.ReadMjpeg(width, height, quality)
if result < 0 {
continue
}
for c, ch := range chanMap {
if err := write(c, data); err != nil {
log.Debugf("failed to write mjpeg data: %s", err)
close(ch)
}
}
log.Debugf("send mjpeg data: %d", len(data))
stream.GetFrameRateCounter().Update()
if screen.FPS != fps {
fps = screen.FPS
ticker.Reset(time.Second / time.Duration(fps))
}
case <-exitSig:
return
}
}
}
func write(c *gin.Context, data []byte) (err error) {
if _, err = c.Writer.Write([]byte("--frame\r\n")); err != nil {
return
}
if _, err = c.Writer.Write([]byte("Content-Type: image/jpeg\r\n\r\n")); err != nil {
return
}
if _, err = c.Writer.Write(data); err != nil {
return
}
if _, err = c.Writer.Write([]byte("\r\n")); err != nil {
return
}
c.Writer.Flush()
return
}

113
server/service/vm/gpio.go Normal file
View File

@@ -0,0 +1,113 @@
package vm
import (
"fmt"
"os"
"strconv"
"time"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/config"
"NanoKVM-Server/proto"
)
func (s *Service) SetGpio(c *gin.Context) {
var req proto.SetGpioReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, fmt.Sprintf("invalid arguments: %s", err))
return
}
device := ""
switch req.Type {
case "power":
device = s.config.Hardware.GPIOPower
case "reset":
device = s.config.Hardware.GPIOReset
default:
rsp.ErrRsp(c, -2, fmt.Sprintf("invalid power event: %s", req.Type))
return
}
var duration time.Duration
if req.Duration > 0 {
duration = time.Duration(req.Duration) * time.Millisecond
} else {
duration = 800 * time.Millisecond
}
if err := writeGpio(device, duration); err != nil {
rsp.ErrRsp(c, -3, fmt.Sprintf("operation failed: %s", err))
return
}
log.Debugf("gpio %s set sucessfully", device)
rsp.OkRsp(c)
}
func (s *Service) GetGpio(c *gin.Context) {
var rsp proto.Response
pwr, err := readGpio(s.config.Hardware.GPIOPowerLED)
if err != nil {
rsp.ErrRsp(c, -2, fmt.Sprintf("failed to read power led: %s", err))
return
}
hdd := false
if s.config.Hardware.Version == config.HWVersionAlpha {
hdd, err = readGpio(s.config.Hardware.GPIOHDDLed)
if err != nil {
rsp.ErrRsp(c, -2, fmt.Sprintf("failed to read hdd led: %s", err))
return
}
}
data := &proto.GetGpioRsp{
PWR: pwr,
HDD: hdd,
}
rsp.OkRspWithData(c, data)
}
func writeGpio(device string, duration time.Duration) error {
if err := os.WriteFile(device, []byte("1"), 0o666); err != nil {
log.Errorf("write gpio %s failed: %s", device, err)
return err
}
time.Sleep(duration)
if err := os.WriteFile(device, []byte("0"), 0o666); err != nil {
log.Errorf("write gpio %s failed: %s", device, err)
return err
}
return nil
}
func readGpio(device string) (bool, error) {
content, err := os.ReadFile(device)
if err != nil {
log.Errorf("read gpio %s failed: %s", device, err)
return false, err
}
contentStr := string(content)
if len(contentStr) > 1 {
contentStr = contentStr[:len(contentStr)-1]
}
value, err := strconv.Atoi(contentStr)
if err != nil {
log.Errorf("invalid gpio content: %s", content)
return false, nil
}
return value == 0, nil
}

93
server/service/vm/info.go Normal file
View File

@@ -0,0 +1,93 @@
package vm
import (
"fmt"
"net"
"os"
"strings"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/proto"
)
var imageVersionMap = map[string]string{
"2024-06-23-20-59-2d2bfb.img": "v1.0.0",
"2024-07-23-20-18-587710.img": "v1.1.0",
"2024-08-08-19-44-bef2ca.img": "v1.2.0",
}
func (s *Service) GetInfo(c *gin.Context) {
var rsp proto.Response
data := &proto.GetInfoRsp{
Ip: getIp(),
Mdns: getMdns(),
Image: getImageVersion(),
Application: getApplicationVersion(),
DeviceKey: getDeviceKey(),
}
rsp.OkRspWithData(c, data)
log.Debug("get vm information success")
}
func getIp() string {
addressList, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, address := range addressList {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {
ip := ipnet.IP.String()
return ip
}
}
return ""
}
func getMdns() string {
content, err := os.ReadFile("/etc/hostname")
if err != nil {
return ""
}
mdns := strings.ReplaceAll(string(content), "\n", "")
return fmt.Sprintf("%s.local", mdns)
}
func getImageVersion() string {
content, err := os.ReadFile("/boot/ver")
if err != nil {
return ""
}
image := strings.ReplaceAll(string(content), "\n", "")
if version, ok := imageVersionMap[image]; ok {
return version
}
return image
}
func getApplicationVersion() string {
content, err := os.ReadFile("/kvmapp/version")
if err != nil {
return "1.0.0"
}
return strings.ReplaceAll(string(content), "\n", "")
}
func getDeviceKey() string {
content, err := os.ReadFile("/device_key")
if err != nil {
return ""
}
return strings.ReplaceAll(string(content), "\n", "")
}

View File

@@ -0,0 +1,56 @@
package vm
import (
"NanoKVM-Server/common"
"fmt"
"os"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/proto"
)
var screenFileMap = map[string]string{
"type": "/kvmapp/kvm/type",
"fps": "/kvmapp/kvm/fps",
"quality": "/kvmapp/kvm/qlty",
"resolution": "/kvmapp/kvm/res",
}
func (s *Service) SetScreen(c *gin.Context) {
var req proto.SetScreenReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
file, ok := screenFileMap[req.Type]
if !ok {
rsp.ErrRsp(c, -2, "invalid arguments")
return
}
data := fmt.Sprintf("%d", req.Value)
if req.Type == "type" {
if req.Value == 0 {
data = "mjpeg"
} else {
data = "h264"
}
}
err := os.WriteFile(file, []byte(data), 0o666)
if err != nil {
log.Errorf("write kvm %s failed: %s", file, err)
rsp.ErrRsp(c, -3, "update screen failed")
return
}
common.SetScreen(req.Type, req.Value)
log.Debugf("update screen: %+v", req)
rsp.OkRsp(c)
}

156
server/service/vm/script.go Normal file
View File

@@ -0,0 +1,156 @@
package vm
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/proto"
"NanoKVM-Server/utils"
)
const ScriptDirectory = "/etc/kvm/scripts"
func (s *Service) GetScripts(c *gin.Context) {
var rsp proto.Response
var files []string
err := filepath.Walk(ScriptDirectory, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && isScript(info.Name()) {
files = append(files, info.Name())
}
return nil
})
if err != nil {
log.Errorf("get scripts failed: %s", err)
rsp.ErrRsp(c, -1, "get scripts failed")
return
}
rsp.OkRspWithData(c, &proto.GetScriptsRsp{
Files: files,
})
log.Debugf("get scripts success")
}
func (s *Service) UploadScript(c *gin.Context) {
var rsp proto.Response
_, header, err := c.Request.FormFile("file")
if err != nil {
rsp.ErrRsp(c, -1, "bad request")
return
}
if !isScript(header.Filename) {
rsp.ErrRsp(c, -2, "invalid arguments")
return
}
if _, err = os.Stat(ScriptDirectory); err != nil {
_ = os.MkdirAll(ScriptDirectory, 0o755)
}
target := fmt.Sprintf("%s/%s", ScriptDirectory, header.Filename)
err = c.SaveUploadedFile(header, target)
if err != nil {
rsp.ErrRsp(c, -2, "save failed")
return
}
_ = utils.EnsurePermission(target, 0o100)
data := &proto.UploadScriptRsp{
File: header.Filename,
}
rsp.OkRspWithData(c, data)
log.Debugf("upload script %s success", header.Filename)
}
func (s *Service) RunScript(c *gin.Context) {
var req proto.RunScriptReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
command := fmt.Sprintf("%s/%s", ScriptDirectory, req.Name)
name := strings.ToLower(req.Name)
if strings.HasSuffix(name, ".py") {
command = fmt.Sprintf("python %s", command)
}
var output []byte
var err error
cmd := exec.Command("sh", "-c", command)
if req.Type == "foreground" {
output, err = cmd.CombinedOutput()
} else {
cmd.Stdout = nil
cmd.Stderr = nil
go func() {
err := cmd.Run()
if err != nil {
log.Errorf("run script %s in background failed: %s", req.Name, err)
}
}()
}
if err != nil {
log.Errorf("run script %s faile: %s", req.Name, err)
rsp.ErrRsp(c, -2, "run script failed")
return
}
rsp.OkRspWithData(c, &proto.RunScriptRsp{
Log: string(output),
})
log.Debugf("run script %s success", req.Name)
}
func (s *Service) DeleteScript(c *gin.Context) {
var req proto.DeleteScriptReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
file := fmt.Sprintf("%s/%s", ScriptDirectory, req.Name)
if err := os.Remove(file); err != nil {
log.Errorf("delete script %s failed: %s", file, err)
rsp.ErrRsp(c, -3, "delete failed")
return
}
rsp.OkRsp(c)
log.Debugf("delete script %s success", file)
}
func isScript(name string) bool {
nameLower := strings.ToLower(name)
if strings.HasSuffix(nameLower, ".sh") || strings.HasSuffix(nameLower, ".py") {
return true
}
return false
}

View File

@@ -0,0 +1,15 @@
package vm
import (
"NanoKVM-Server/config"
)
type Service struct {
config *config.Config
}
func NewService() *Service {
return &Service{
config: config.GetInstance(),
}
}

View File

@@ -0,0 +1,246 @@
package vm
import (
"encoding/json"
"io"
"net/http"
"os"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
"NanoKVM-Server/utils"
)
const (
messageWait = 10 * time.Second
maxMessageSize = 1024
)
type WindowSize struct {
Height int `json:"height"`
Width int `json:"width"`
}
type SshClient struct {
conn *websocket.Conn
addr string
user string
password string
client *ssh.Client
session *ssh.Session
sessionIn io.WriteCloser
sessionOut io.Reader
closeSig chan struct{}
}
var upgrader = websocket.Upgrader{
ReadBufferSize: maxMessageSize,
WriteBufferSize: maxMessageSize,
}
var terminalModes = ssh.TerminalModes{
ssh.ECHO: 1,
ssh.TTY_OP_ISPEED: 14400,
ssh.TTY_OP_OSPEED: 14400,
}
func (s *SshClient) getWindowSize() (size *WindowSize, err error) {
_ = s.conn.SetReadDeadline(time.Now().Add(messageWait))
msgType, msg, err := s.conn.ReadMessage()
if err != nil {
log.Errorf("ws read message failed: %s", err)
return
}
if msgType != websocket.BinaryMessage {
log.Errorf("ws message type is not binary")
return
}
size = new(WindowSize)
if err = json.Unmarshal(msg, size); err != nil {
log.Errorf("unmarshal ws message failed: %s", err)
return
}
return
}
func (s *SshClient) wsWrite() error {
defer func() {
s.closeSig <- struct{}{}
}()
data := make([]byte, maxMessageSize)
for {
time.Sleep(10 * time.Millisecond)
n, err := s.sessionOut.Read(data)
if err != nil {
return err
}
if n > 0 {
_ = s.conn.SetWriteDeadline(time.Now().Add(messageWait))
err = s.conn.WriteMessage(websocket.BinaryMessage, data[:n])
if err != nil {
log.Errorf("write ws message failed: %s", err)
return err
}
}
}
}
func (s *SshClient) wsRead() error {
defer func() {
s.closeSig <- struct{}{}
}()
var zeroTime time.Time
_ = s.conn.SetReadDeadline(zeroTime)
for {
msgType, connReader, err := s.conn.NextReader()
if err != nil {
return err
}
if msgType != websocket.BinaryMessage {
_, err = io.Copy(s.sessionIn, connReader)
if err != nil {
log.Errorf("copy ws message failed: %s", err)
return err
}
continue
}
data := make([]byte, maxMessageSize)
n, err := connReader.Read(data)
if err != nil {
log.Errorf("read ws message failed: %s", err)
return err
}
var size WindowSize
err = json.Unmarshal(data[:n], &size)
if err != nil {
log.Errorf("unmarshal ws message failed: %s", err)
return err
}
err = s.session.WindowChange(size.Height, size.Width)
if err != nil {
log.Errorf("ws window change failed: %s", err)
return err
}
}
}
func (s *SshClient) bridgeWSAndSSH() {
defer func() {
_ = s.conn.Close()
if r := recover(); r != nil {
log.Debugf("terminal recover: %s", r)
}
}()
size, err := s.getWindowSize()
if err != nil {
return
}
auth := ssh.Password(s.password)
config := &ssh.ClientConfig{
User: s.user,
Auth: []ssh.AuthMethod{auth},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
s.client, err = ssh.Dial("tcp", s.addr, config)
if err != nil {
// log.Errorf("init ssh failed: %s", err)
return
}
defer func() {
_ = s.client.Close()
}()
s.session, err = s.client.NewSession()
if err != nil {
log.Errorf("open ssh session failed: %s", err)
return
}
defer s.session.Close()
s.session.Stderr = os.Stderr
s.sessionOut, err = s.session.StdoutPipe()
if err != nil {
log.Errorf("open ssh session out failed: %s", err)
return
}
s.sessionIn, err = s.session.StdinPipe()
if err != nil {
log.Errorf("open ssh session in failed: %s", err)
return
}
defer func() {
_ = s.sessionIn.Close()
}()
if err = s.session.RequestPty("xterm", size.Height, size.Width, terminalModes); err != nil {
log.Errorf("oen session request pty failed: %s", err)
return
}
if err = s.session.Shell(); err != nil {
log.Errorf("open ssh shell failed: %s", err)
return
}
go func() {
_ = s.wsRead()
}()
go func() {
_ = s.wsWrite()
}()
<-s.closeSig
}
func (s *Service) Terminal(c *gin.Context) {
user := c.Query("u")
if user == "" {
user = "root"
}
password, _ := utils.Decrypt(c.Query("t"))
if password == "" {
password = "root"
}
upgrader.CheckOrigin = func(r *http.Request) bool {
return true
}
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Errorf("init websocket failed: %s", err)
return
}
sshClient := &SshClient{
conn: conn,
addr: "127.0.0.1:22",
user: user,
password: password,
closeSig: make(chan struct{}, 1),
}
go sshClient.bridgeWSAndSSH()
}

View File

@@ -0,0 +1,134 @@
package vm
import (
"errors"
"os"
"os/exec"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/proto"
"NanoKVM-Server/service/hid"
)
const (
virtualNetwork = "/boot/usb.rndis0"
virtualDisk = "/boot/usb.disk0"
)
var (
mountNetworkCommands = []string{
"touch /boot/usb.rndis0",
"/etc/init.d/S03usbdev stop",
"/etc/init.d/S03usbdev start",
}
unmountNetworkCommands = []string{
"/etc/init.d/S03usbdev stop",
"rm -rf /sys/kernel/config/usb_gadget/g0/configs/c.1/rndis.usb0",
"rm /boot/usb.rndis0",
"/etc/init.d/S03usbdev start",
}
mountDiskCommands = []string{
"touch /boot/usb.disk0",
"/etc/init.d/S03usbdev stop",
"/etc/init.d/S03usbdev start",
}
unmountDiskCommands = []string{
"/etc/init.d/S03usbdev stop",
"rm -rf /sys/kernel/config/usb_gadget/g0/configs/c.1/mass_storage.disk0",
"rm /boot/usb.disk0",
"/etc/init.d/S03usbdev start",
}
)
func (s *Service) GetVirtualDevice(c *gin.Context) {
var rsp proto.Response
network, _ := isDeviceExist(virtualNetwork)
disk, _ := isDeviceExist(virtualDisk)
rsp.OkRspWithData(c, &proto.GetVirtualDeviceRsp{
Network: network,
Disk: disk,
})
log.Debugf("get virtual device success")
}
func (s *Service) UpdateVirtualDevice(c *gin.Context) {
var req proto.UpdateVirtualDeviceReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid argument")
return
}
var device string
var commands []string
switch req.Device {
case "network":
device = virtualNetwork
exist, _ := isDeviceExist(device)
if !exist {
commands = mountNetworkCommands
} else {
commands = unmountNetworkCommands
}
case "disk":
device = virtualDisk
exist, _ := isDeviceExist(device)
if !exist {
commands = mountDiskCommands
} else {
commands = unmountDiskCommands
}
default:
rsp.ErrRsp(c, -2, "invalid arguments")
return
}
h := hid.GetHid()
h.Lock()
h.CloseNoLock()
defer func() {
h.OpenNoLock()
h.Unlock()
}()
for _, command := range commands {
err := exec.Command("sh", "-c", command).Run()
if err != nil {
rsp.ErrRsp(c, -3, "operation failed")
return
}
}
on, _ := isDeviceExist(device)
rsp.OkRspWithData(c, &proto.UpdateVirtualDeviceRsp{
On: on,
})
log.Debugf("update virtual device %s success", req.Device)
}
func isDeviceExist(device string) (bool, error) {
_, err := os.Stat(device)
if err == nil {
return true, nil
}
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
log.Errorf("check file %s err: %s", device, err)
return false, err
}

View File

@@ -0,0 +1,6 @@
package ws
type Stream struct {
Type string `json:"type"`
State int `json:"state"`
}

View File

@@ -0,0 +1,7 @@
package ws
type Service struct{}
func NewService() *Service {
return &Service{}
}

113
server/service/ws/ws.go Normal file
View File

@@ -0,0 +1,113 @@
package ws
import (
"encoding/json"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/service/hid"
)
const (
KeyboardEvent int = 1
MouseEvent int = 2
)
type WsClient struct {
conn *websocket.Conn
hid *hid.Hid
keyboard chan []int
mouse chan []int
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func (s *Service) Connect(c *gin.Context) {
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Errorf("create websocket failed: %s", err)
return
}
log.Debug("websocket connected")
client := &WsClient{
hid: hid.GetHid(),
conn: conn,
keyboard: make(chan []int, 200),
mouse: make(chan []int, 200),
}
go client.Start()
}
func (c *WsClient) Start() {
defer c.Clean()
c.hid.Open()
go c.hid.Keyboard(c.keyboard)
go c.hid.Mouse(c.mouse)
_ = c.Read()
}
func (c *WsClient) Read() error {
var zeroTime time.Time
_ = c.conn.SetReadDeadline(zeroTime)
for {
_, message, err := c.conn.ReadMessage()
if err != nil {
return err
}
log.Debugf("receive message: %s", message)
var event []int
err = json.Unmarshal(message, &event)
if err != nil {
log.Debugf("receive invalid message: %s", message)
continue
}
if event[0] == KeyboardEvent {
c.keyboard <- event[1:]
} else if event[0] == MouseEvent {
c.mouse <- event[1:]
}
}
}
func (c *WsClient) Write(message []byte) error {
_ = c.conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
return c.conn.WriteMessage(websocket.TextMessage, message)
}
func (c *WsClient) Clean() {
_ = c.conn.Close()
go clearQueue(c.keyboard)
close(c.keyboard)
go clearQueue(c.mouse)
close(c.mouse)
c.hid.Close()
log.Debug("websocket disconnected")
}
func clearQueue(queue chan []int) {
for range queue {
}
}

23
server/utils/chmod.go Normal file
View File

@@ -0,0 +1,23 @@
package utils
import (
"os"
"path/filepath"
)
func ChmodRecursively(path string, mode uint32) error {
return filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
err = os.Chmod(path, os.FileMode(mode))
if err != nil {
return err
}
}
return nil
})
}

36
server/utils/encrypt.go Normal file
View File

@@ -0,0 +1,36 @@
package utils
import (
"net/url"
"github.com/mervick/aes-everywhere/go/aes256"
log "github.com/sirupsen/logrus"
)
const EncryptSecretKey = "nanokvm-sipeed-2024"
func Decrypt(ciphertext string) (string, error) {
defer func() {
if err := recover(); err != nil {
log.Errorf("decrypt failed: %s", err)
}
}()
if ciphertext == "" {
return "", nil
}
decrypt := aes256.Decrypt(ciphertext, EncryptSecretKey)
return decrypt, nil
}
func DecodeDecrypt(ciphertext string) (string, error) {
decode, err := url.QueryUnescape(ciphertext)
if err != nil {
log.Errorf("decode ciphertext failed: %s", err)
return "", err
}
return Decrypt(decode)
}

56
server/utils/http.go Normal file
View File

@@ -0,0 +1,56 @@
package utils
import (
"errors"
"io"
"net/http"
"os"
"path/filepath"
log "github.com/sirupsen/logrus"
)
func Download(req *http.Request, target string) error {
log.Debugf("downloading %s to %s", req.URL.String(), target)
err := os.MkdirAll(filepath.Dir(target), 0o755)
if err != nil {
log.Errorf("create dir %s err: %s", filepath.Dir(target), err)
return err
}
out, err := os.OpenFile(target, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o755)
if err != nil {
log.Errorf("cannot create file '%s', error: %s", target, err)
return err
}
defer func() {
_ = out.Close()
}()
resp, err := (&http.Client{}).Do(req)
if err != nil {
log.Errorf("request error: %s", err)
return err
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
log.Errorf("request failed, status code: %d", resp.StatusCode)
return errors.New("update website is inaccessible right now")
}
contentType := resp.Header.Get("Content-Type")
if contentType != "application/octet-stream" && contentType != "application/zip" {
log.Debugf("unexpected content-type, it should be either octet-stream or zip, but got: %s", contentType)
return errors.New("unsupported content type")
}
_, err = io.Copy(out, resp.Body)
if err != nil {
log.Errorf("download file to %s err: %s", target, err)
return err
}
return nil
}

78
server/utils/move-file.go Normal file
View File

@@ -0,0 +1,78 @@
package utils
import (
"io"
"os"
"path/filepath"
"strings"
)
func MoveFile(src, dst string) error {
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
return err
}
err := os.Rename(src, dst)
if err != nil {
if strings.Contains(err.Error(), "invalid cross-device link") {
return MoveFileCrossFS(src, dst)
}
return err
}
return nil
}
func MoveFileCrossFS(src, dst string) error {
tmp := dst + ".tmp"
srcFile, err := os.Open(src)
if err != nil {
return err
}
tmpFile, err := os.Create(tmp)
if err != nil {
_ = srcFile.Close()
return err
}
_, err = io.Copy(tmpFile, srcFile)
if err != nil {
_ = srcFile.Close()
_ = tmpFile.Close()
return err
}
_ = srcFile.Close()
_ = tmpFile.Close()
fi, err := os.Stat(src)
if err != nil {
return err
}
err = os.Chmod(tmp, fi.Mode())
if err != nil {
return err
}
_ = os.Remove(src)
err = os.Rename(tmp, dst)
if err != nil {
return err
}
return nil
}
func MoveFilesRecursively(src, dst string) error {
return filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
fileName := strings.Replace(path, src, "", 1)
dstName := dst + fileName
fileInfo, err := os.Stat(path)
if err != nil {
return err
}
if fileInfo.IsDir() {
return os.MkdirAll(dstName, fileInfo.Mode())
}
return MoveFile(path, dstName)
})
}

View File

@@ -0,0 +1,48 @@
package utils
import "os"
func HasPermission(filePath string, perm os.FileMode) (bool, error) {
fileInfo, err := os.Stat(filePath)
if err != nil {
return false, err
}
mode := fileInfo.Mode().Perm()
if mode&perm == perm {
return true, nil
}
return false, nil
}
func AddPermission(filePath string, perm os.FileMode) error {
fileInfo, err := os.Stat(filePath)
if err != nil {
return err
}
mode := fileInfo.Mode() | perm
err = os.Chmod(filePath, mode)
if err != nil {
return err
}
return nil
}
func EnsurePermission(filePath string, perm os.FileMode) error {
hasPerm, err := HasPermission(filePath, perm)
if err != nil {
return err
}
if !hasPerm {
err = AddPermission(filePath, perm)
if err != nil {
return err
}
}
return nil
}

61
server/utils/unzip.go Normal file
View File

@@ -0,0 +1,61 @@
package utils
import (
"archive/zip"
"io"
"os"
"path/filepath"
)
func Unzip(filename string, dest string) error {
r, err := zip.OpenReader(filename)
if err != nil {
return err
}
defer func() {
_ = r.Close()
}()
for _, f := range r.File {
dstPath := filepath.Join(dest, filepath.Clean("/"+f.Name))
if f.FileInfo().IsDir() {
err = os.MkdirAll(dstPath, 0o755)
if err != nil {
return err
}
} else {
err = unzipFile(dstPath, f)
if err != nil {
return err
}
}
}
return nil
}
func unzipFile(dstPath string, f *zip.File) error {
err := os.MkdirAll(filepath.Dir(dstPath), 0o755)
if err != nil {
return err
}
out, err := os.OpenFile(dstPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
defer func() {
_ = out.Close()
}()
archivedFile, err := f.Open()
if err != nil {
return err
}
if _, err = io.Copy(out, archivedFile); err != nil {
return err
}
if err = os.Chmod(dstPath, f.Mode()); err != nil {
return err
}
return nil
}

9
web/.editorconfig Normal file
View File

@@ -0,0 +1,9 @@
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

3
web/.env.development Normal file
View File

@@ -0,0 +1,3 @@
VITE_SERVER_IP=192.168.1.1
VITE_SERVER_PORT=80
VITE_WITH_CREDENTIALS=false

20
web/.eslintrc.cjs Normal file
View File

@@ -0,0 +1,20 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
'prettier',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {
'@typescript-eslint/no-explicit-any': 'off',
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}

1
web/.prettierignore Normal file
View File

@@ -0,0 +1 @@
*.hbs

36
web/.prettierrc.yaml Normal file
View File

@@ -0,0 +1,36 @@
singleQuote: true
trailingComma: none
printWidth: 100
tabWidth: 2
bracketSpacing: true
importOrder:
- ^(react/(.*)$)|^(react$)
- ^(next/(.*)$)|^(next$)
- <THIRD_PARTY_MODULES>
- ''
- ^types$
- ^@/assets(.*)$
- ^@/api/(.*)$
- ^@/i18n/(.*)$
- ^@/types$
- ^@/lib/(.*)$
- ^@/jotai/(.*)$
- ^@/hooks/(.*)$
- ^@/components/(.*)$
- ^@/pages/(.*)$
- ^@/styles/(.*)$
- ''
- '^[./]'
importOrderSeparation: false
importOrderSortSpecifiers: true
importOrderBuiltinModulesToTop: true
importOrderParserPlugins:
- typescript
- jsx
- tsx
- decorators-legacy
importOrderMergeDuplicateImports: true
importOrderCombineTypeAndValueImports: true
plugins:
- '@ianvs/prettier-plugin-sort-imports'
- prettier-plugin-tailwindcss

58
web/README.md Normal file
View File

@@ -0,0 +1,58 @@
# NanoKVM Frontend
This is NanoKVM web project. For more documentation, please refer to the [Wiki](https://wiki.sipeed.com/nanokvm).
## Structure
```shell
src
├── api // backend api
├── assets // static resources
├── components // public components
├── i18n // language resources
├── jotai // Global jotai variables
├── lib // util libs
├── pages // web pages
│ ├── auth // login and password
│ ├── desktop // remote desktop
│ └── terminal // web terminal
├── router.tsx // routers
└── types // types
```
## Local Development
Due to CORS restrictions, authentication needs to be disabled during local development.
To develop authentication features, you need to build the project and test in NanoKVM.
1. Log in to NanoKVM via SSH: `ssh root@your-nanokvm-ip` (default password is root).
2. Open the configuration file `/etc/kvm/server.yaml/` and add `authentication: disable`. ⚠️CAUTION: This option disables all authentication and should NOT be enabled in production environment!
3. Restart the service: `/etc/init.d/S95nanokvm restart`.
4. Edit the `.env.development` file and change `VITE_SERVER_IP` to your NanoKVM IP address.
5. Run `pnpm dev` to start the server and visit http://localhost:3001/ in browser.
It's recommended to disable browser caching to avoid access issues during development:
1. Open the browser Developer Tools;
2. Go to the `Network` tab;
3. Check `Disable cache` option;
4. Refresh the page.
## Deployment
Build:
```shell
cd web
pnpm install
pnpm build
```
1. After the compilation is complete, the `dist` folder will be generated.
2. Rename the folder to `web`.
3. Upload `web` to `/kvmapp/server/` in NanoKVM.
4. Restart the service by executing `/etc/init.d/S95nanokvm restart` in NanoKVM.
Additionally, browser may have old version cache. If you can't open the page, try a force refresh or clear the cache.

59
web/README_ZH.md Normal file
View File

@@ -0,0 +1,59 @@
# NanoKVM 前端页面
NanoKVM 前端页面的代码。更多文档请参考 [Wiki](https://wiki.sipeed.com/nanokvm) 。
## 目录结构
```shell
src
├── api // 后端接口
├── assets // 资源文件
├── components // 公共组件
├── i18n // 多语言
├── jotai // 全局 jotai 变量
├── lib // lib
├── pages // 页面
│ ├── auth // 鉴权页面
│ ├── desktop // 远程桌面
│ └── terminal // 终端
├── router.tsx // 路由
└── types // 类型定义
```
## 本地开发
由于 CORS 的限制,在本地开发时,需要关闭鉴权功能。
如果想要开发鉴权相关的功能,需要编译后在 NanoKVM 中进行测试。
1. 通过 ssh 登录到 NanoKVM:`ssh root@your-nanokvm-ip`(默认密码为 root);
2. 修改配置文件 `/etc/kvm/server.yaml`,添加一行 `authentication: disable`。⚠️注意:该选项会禁用所有鉴权功能,生产环境请勿开启该选项!
3. 执行 `/etc/init.d/S95nanokvm restart` 重启服务。
4. 编辑 `.env.development` 文件,将 `VITE_SERVER_IP` 修改为你的 NanoKVM IP 地址。
5. 执行 `pnpm dev` 启动服务,然后在浏览器中访问 http://localhost:3001/ 。
建议在浏览器中禁用缓存,防止在开发过程中出现无法访问的情况。
1. 打开开发者工具;
2. 点击 `Network` 选项卡;
3. 勾选 `Disable cache` 选项;
4. 刷新页面。
## 部署
编译:
```shell
cd web
pnpm install
pnpm build
```
1. 编译完成后会生成 `dist` 文件夹;
2. 将该文件夹重命名为 `web`;
3. 将 `web` 文件夹上传到 NanoKVM 的 `/kvmapp/server/` 目录下;
4. 在 NanoKVM 中执行 `/etc/init.d/S95nanokvm restart` 重启服务。
注意:更新 web 目录后,浏览器可能会有缓存。如果遇到打不开页面的情况,请强制刷新或清空缓存。

13
web/index.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/sipeed.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>NanoKVM</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

69
web/package.json Normal file
View File

@@ -0,0 +1,69 @@
{
"name": "web",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"mocked": "vite --mode mocked",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"@ant-design/icons": "^5.3.7",
"@xterm/addon-attach": "^0.11.0",
"@xterm/addon-fit": "^0.10.0",
"@xterm/xterm": "^5.5.0",
"antd": "^5.19.2",
"axios": "^1.7.4",
"clsx": "^2.1.1",
"crypto-js": "^4.2.0",
"i18next": "^23.11.5",
"jotai": "^2.9.0",
"js-cookie": "^3.0.5",
"lucide-react": "^0.408.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-error-boundary": "^4.0.13",
"react-helmet-async": "^2.0.5",
"react-i18next": "^14.1.2",
"react-responsive": "^10.0.0",
"react-router-dom": "^6.23.1",
"react-simple-keyboard": "^3.7.124",
"semver": "^7.6.3",
"vaul": "^0.9.1",
"websocket": "^1.0.35"
},
"devDependencies": {
"@ianvs/prettier-plugin-sort-imports": "^4.2.1",
"@types/crypto-js": "^4.2.2",
"@types/js-cookie": "^3.0.6",
"@types/react": "^18.3.2",
"@types/react-dom": "^18.3.0",
"@types/semver": "^7.5.8",
"@types/websocket": "^1.0.10",
"@typescript-eslint/eslint-plugin": "^7.10.0",
"@typescript-eslint/parser": "^7.10.0",
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.19",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-react": "^7.34.1",
"eslint-plugin-react-hooks": "^4.6.2",
"eslint-plugin-react-refresh": "^0.4.7",
"msw": "^2.6.0",
"postcss": "^8.4.38",
"prettier": "^3.2.5",
"prettier-plugin-tailwindcss": "^0.5.14",
"tailwindcss": "^3.4.13",
"typescript": "^5.4.5",
"vite": "^5.4.8",
"vite-tsconfig-paths": "^4.3.2"
},
"msw": {
"workerDirectory": [
"public"
]
}
}

5329
web/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

6
web/postcss.config.js Normal file
View File

@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

View File

@@ -0,0 +1,293 @@
/* eslint-disable */
/* tslint:disable */
/**
* Mock Service Worker.
* @see https://github.com/mswjs/msw
* - Please do NOT modify this file.
* - Please do NOT serve this file on production.
*/
const PACKAGE_VERSION = '2.6.0'
const INTEGRITY_CHECKSUM = '07a8241b182f8a246a7cd39894799a9e'
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
const activeClientIds = new Set()
self.addEventListener('install', function () {
self.skipWaiting()
})
self.addEventListener('activate', function (event) {
event.waitUntil(self.clients.claim())
})
self.addEventListener('message', async function (event) {
const clientId = event.source.id
if (!clientId || !self.clients) {
return
}
const client = await self.clients.get(clientId)
if (!client) {
return
}
const allClients = await self.clients.matchAll({
type: 'window',
})
switch (event.data) {
case 'KEEPALIVE_REQUEST': {
sendToClient(client, {
type: 'KEEPALIVE_RESPONSE',
})
break
}
case 'INTEGRITY_CHECK_REQUEST': {
sendToClient(client, {
type: 'INTEGRITY_CHECK_RESPONSE',
payload: {
packageVersion: PACKAGE_VERSION,
checksum: INTEGRITY_CHECKSUM,
},
})
break
}
case 'MOCK_ACTIVATE': {
activeClientIds.add(clientId)
sendToClient(client, {
type: 'MOCKING_ENABLED',
payload: {
client: {
id: client.id,
frameType: client.frameType,
},
},
})
break
}
case 'MOCK_DEACTIVATE': {
activeClientIds.delete(clientId)
break
}
case 'CLIENT_CLOSED': {
activeClientIds.delete(clientId)
const remainingClients = allClients.filter((client) => {
return client.id !== clientId
})
// Unregister itself when there are no more clients
if (remainingClients.length === 0) {
self.registration.unregister()
}
break
}
}
})
self.addEventListener('fetch', function (event) {
const { request } = event
// Bypass navigation requests.
if (request.mode === 'navigate') {
return
}
// Opening the DevTools triggers the "only-if-cached" request
// that cannot be handled by the worker. Bypass such requests.
if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
return
}
// Bypass all requests when there are no active clients.
// Prevents the self-unregistered worked from handling requests
// after it's been deleted (still remains active until the next reload).
if (activeClientIds.size === 0) {
return
}
// Generate unique request ID.
const requestId = crypto.randomUUID()
event.respondWith(handleRequest(event, requestId))
})
async function handleRequest(event, requestId) {
const client = await resolveMainClient(event)
const response = await getResponse(event, client, requestId)
// Send back the response clone for the "response:*" life-cycle events.
// Ensure MSW is active and ready to handle the message, otherwise
// this message will pend indefinitely.
if (client && activeClientIds.has(client.id)) {
;(async function () {
const responseClone = response.clone()
sendToClient(
client,
{
type: 'RESPONSE',
payload: {
requestId,
isMockedResponse: IS_MOCKED_RESPONSE in response,
type: responseClone.type,
status: responseClone.status,
statusText: responseClone.statusText,
body: responseClone.body,
headers: Object.fromEntries(responseClone.headers.entries()),
},
},
[responseClone.body],
)
})()
}
return response
}
// Resolve the main client for the given event.
// Client that issues a request doesn't necessarily equal the client
// that registered the worker. It's with the latter the worker should
// communicate with during the response resolving phase.
async function resolveMainClient(event) {
const client = await self.clients.get(event.clientId)
if (activeClientIds.has(event.clientId)) {
return client
}
if (client?.frameType === 'top-level') {
return client
}
const allClients = await self.clients.matchAll({
type: 'window',
})
return allClients
.filter((client) => {
// Get only those clients that are currently visible.
return client.visibilityState === 'visible'
})
.find((client) => {
// Find the client ID that's recorded in the
// set of clients that have registered the worker.
return activeClientIds.has(client.id)
})
}
async function getResponse(event, client, requestId) {
const { request } = event
// Clone the request because it might've been already used
// (i.e. its body has been read and sent to the client).
const requestClone = request.clone()
function passthrough() {
const headers = Object.fromEntries(requestClone.headers.entries())
// Remove internal MSW request header so the passthrough request
// complies with any potential CORS preflight checks on the server.
// Some servers forbid unknown request headers.
delete headers['x-msw-intention']
return fetch(requestClone, { headers })
}
// Bypass mocking when the client is not active.
if (!client) {
return passthrough()
}
// Bypass initial page load requests (i.e. static assets).
// The absence of the immediate/parent client in the map of the active clients
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
// and is not ready to handle requests.
if (!activeClientIds.has(client.id)) {
return passthrough()
}
// Notify the client that a request has been intercepted.
const requestBuffer = await request.arrayBuffer()
const clientMessage = await sendToClient(
client,
{
type: 'REQUEST',
payload: {
id: requestId,
url: request.url,
mode: request.mode,
method: request.method,
headers: Object.fromEntries(request.headers.entries()),
cache: request.cache,
credentials: request.credentials,
destination: request.destination,
integrity: request.integrity,
redirect: request.redirect,
referrer: request.referrer,
referrerPolicy: request.referrerPolicy,
body: requestBuffer,
keepalive: request.keepalive,
},
},
[requestBuffer],
)
switch (clientMessage.type) {
case 'MOCK_RESPONSE': {
return respondWithMock(clientMessage.data)
}
case 'PASSTHROUGH': {
return passthrough()
}
}
return passthrough()
}
function sendToClient(client, message, transferrables = []) {
return new Promise((resolve, reject) => {
const channel = new MessageChannel()
channel.port1.onmessage = (event) => {
if (event.data && event.data.error) {
return reject(event.data.error)
}
resolve(event.data)
}
client.postMessage(
message,
[channel.port2].concat(transferrables.filter(Boolean)),
)
})
}
async function respondWithMock(response) {
// Setting response status code to 0 is a no-op.
// However, when responding with a "Response.error()", the produced Response
// instance will have status code set to 0. Since it's not possible to create
// a Response instance with status code 0, handle that use-case separately.
if (response.status === 0) {
return Response.error()
}
const mockedResponse = new Response(response.body, response)
Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
value: true,
enumerable: true,
})
return mockedResponse
}

BIN
web/public/sipeed.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -0,0 +1,15 @@
import { http } from '@/lib/http.ts';
// get application version
export function getVersion() {
return http.get('/api/application/version');
}
// update application to latest version
export function update() {
return http.request({
method: 'post',
url: '/api/application/update',
timeout: 15 * 60 * 1000
});
}

21
web/src/api/auth.ts Normal file
View File

@@ -0,0 +1,21 @@
import { http } from '@/lib/http';
export function login(username: string, password: string) {
const data = {
username,
password
};
return http.post('/api/auth/login', data);
}
export function changePassword(username: string, password: string) {
const data = {
username,
password
};
return http.post('/api/auth/password', data);
}
export function isPasswordUpdated() {
return http.get('/api/auth/password');
}

11
web/src/api/hid.ts Normal file
View File

@@ -0,0 +1,11 @@
import { http } from '@/lib/http.ts';
// paste
export function paste(content: string) {
return http.post('/api/hid/paste', { content });
}
// reset hid
export function reset() {
return http.post('/api/hid/reset');
}

47
web/src/api/network.ts Normal file
View File

@@ -0,0 +1,47 @@
import { http } from '@/lib/http.ts';
// wake on lan
export function wol(mac: string) {
const data = {
mac
};
return http.post('/api/network/wol', data);
}
// get wake-on-lan macs history
export function getWolMacs() {
return http.get('/api/network/wol/mac');
}
export function deleteWolMac(mac: string) {
return http.request({
method: 'delete',
url: '/api/network/wol/mac',
data: { mac }
});
}
// install tailscale
export function installTailscale() {
return http.post('/api/network/tailscale/install');
}
// get tailscale status
export function getTailscaleStatus() {
return http.get('/api/network/tailscale/status');
}
// update tailscale status
export function updateTailscaleStatus(command: 'up' | 'down') {
return http.post('/api/network/tailscale/status', { command });
}
// login tailscale
export function loginTailscale() {
return http.post('/api/network/tailscale/login');
}
// logout tailscale
export function logoutTailscale() {
return http.post('/api/network/tailscale/logout');
}

28
web/src/api/script.ts Normal file
View File

@@ -0,0 +1,28 @@
import { http } from '@/lib/http.ts';
export function uploadScript(formData: FormData) {
return http.request({
url: '/api/vm/script/upload',
method: 'post',
headers: {
'Content-Type': 'multipart/form-data'
},
data: formData
});
}
export function runScript(name: string, type: string) {
return http.post('/api/vm/script/run', { name, type });
}
export function getScripts() {
return http.get('/api/vm/script');
}
export function deleteScript(name: string) {
return http.request({
url: '/api/vm/script',
method: 'delete',
data: { name }
});
}

19
web/src/api/storage.ts Normal file
View File

@@ -0,0 +1,19 @@
import { http } from '@/lib/http.ts';
// get image list
export function getImages() {
return http.get('/api/storage/image');
}
// get mounted image
export function getMountedImage() {
return http.get('/api/storage/image/mounted');
}
// mount/unmount image
export function mountImage(file?: string) {
const data = {
file: file ? file : ''
};
return http.post('/api/storage/image/mount', data);
}

16
web/src/api/stream.ts Normal file
View File

@@ -0,0 +1,16 @@
import { http } from '@/lib/http.ts';
// get whether the frame detect is enabled
export function getFrameDetect() {
return http.get('/api/stream/mjpeg/detect');
}
// enable/disable frame detect
export function updateFrameDetect() {
return http.post('/api/stream/mjpeg/detect');
}
// pause frame detect for a while (prevent a black screen when opening the page for the first time)
export function stopFrameDetect() {
return http.post('/api/stream/mjpeg/detect/stop');
}

View File

@@ -0,0 +1,15 @@
import { http } from '@/lib/http.ts';
// get virtual devices status
export function getVirtualDevice() {
return http.get('/api/vm/device/virtual');
}
// mount/unmount virtual device
export function updateVirtualDevice(device: string) {
const data = {
device
};
return http.post('/api/vm/device/virtual', data);
}

29
web/src/api/vm.ts Normal file
View File

@@ -0,0 +1,29 @@
import { http } from '@/lib/http.ts';
// get NanoKVM information
export function getInfo() {
return http.get('/api/vm/info');
}
// set gpio value
export function setGpio(type: string, duration: number) {
const data = {
type,
duration
};
return http.post('/api/vm/gpio', data);
}
// get gpio value
export function getGpio() {
return http.get('/api/vm/gpio');
}
// update screen arguments
export function updateScreen(type: string, value: number) {
const data = {
type,
value
};
return http.post('/api/vm/screen', data);
}

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