Refactor: Rename NanoKVM to BatchuKVM and update server URL

This commit is contained in:
2025-12-09 20:35:38 +09:00
commit 8cf674c9e5
396 changed files with 54380 additions and 0 deletions

31
.gitignore vendored Normal file
View File

@@ -0,0 +1,31 @@
*.log
pnpm-debug.log*
web/node_modules
web/dist
web/web
.DS_Store
*.local
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
.idea
.vscode
NanoKVM-Server
support/sg2002/kvm_system/build
support/sg2002/kvm_system/dist
support/sg2002/kvm_system/CMakeLists.txt
support/sg2002/kvm_vision_test/build
support/sg2002/kvm_vision_test/dist
support/sg2002/kvm_vision_test/CMakeLists.txt
support/sg2002/additional/original
kvmapp/server/dl_lib
kvmapp/kvm_system/kvm_system

212
CHANGELOG.md Normal file
View File

@@ -0,0 +1,212 @@
## 2.3.0 [0e30a26](https://github.com/sipeed/NanoKVM/commit/0e30a26db42cbc08416662b49a88a5d16ad93424) (2025-11-26)
### Features
* Added an EDID editor in the terminal with a built-in 1080P EDID template
* Added German virtual keyboard and German clipboard support (thanks to [@Alexander-Ger-Reich](https://github.com/Alexander-Ger-Reich))
* Resetting the HID also resets the USB hardware
* Added support for deleting ISO images
### Refactoring & Improvements
* Video (H.264 WebRTC): Refactored the module to significantly reduce video latency
* Video (H.264 Direct): Refactored to optimize data transmission and support data parsing even when the page is in the background
* Video (MJPEG): Refactored and ensure correct data length transmission
* Added locking before resetting USB to prevent HID deadlock (thanks to [@scpcom](https://github.com/scpcom))
* Optimized HID writing logic
* Made HDMI toggle state persist across reboots (thanks to [@tpretz](https://github.com/tpretz))
* Enhanced the paste feature with browser clipboard API integration (thanks to [@patrickpilon](https://github.com/patrickpilon))
* Set the inquiry string for the virtual storage device (thanks to [@scpcom](https://github.com/scpcom))
* Hostname now updates `/etc/hosts` simultaneously and takes effect immediately (thanks to [@scpcom](https://github.com/scpcom))
* Improved compatibility for static IP configuration on Windows
* Optimized the web page title update logic
* Added a confirmation dialog when uninstalling Tailscale
* Improved UI for Clipboard, Image Mounting, and settings pages
### Bug Fixes
* Tailscale: Fixed an issue where Tailscale would turn the device into a router
* Tailscale: Fixed an issue where Tailscale would disable IPv6
* Tailscale: Added a swap memory option to prevent Tailscale Out-Of-Memory errors
* Tailscale: Fixed Tailscale accept-dns configuration (thanks to [@lazydba247](https://github.com/lazydba247))
* Fixed an issue where certain modifier keys were not recognized
* Fixed vertical mouse drift when the page is zoomed in or out
### Localization
* Update Korean translation (thanks to [@xenix4845](https://github.com/xenix4845))
* Update Traditional Chinese translation (thanks to [@protonchang](https://github.com/protonchang))
* Add Brazilian Portuguese translation (thanks to [@chiconws](https://github.com/chiconws) and [@Luccas-LF](https://github.com/Luccas-LF))
* Add Swedish translation (thanks to [@acidflash](https://github.com/acidflash))
* Add Catalan translation (thanks to [@Zagur](https://github.com/Zagur))
* Add Turkish translation (thanks to [@Keylem](https://github.com/Keylem))
### Security
* Implemented a delay after failed login attempts to mitigate brute-force attacks
* Upgraded dependencies to fix known security vulnerabilities
## 2.2.9 [c77981c](https://github.com/sipeed/NanoKVM/commit/c77981cc0ceebd8f6705b6c5d8c3cf4edf4f6717) (2025-06-13)
* fix(security): resolve parameter injection in serial port terminal
## 2.2.8 [01e28f1](https://github.com/sipeed/NanoKVM/commit/01e28f10ae8b581d484bb6077ddfe7bbe4e57919) (2025-05-22)
* feat: add AZERTY virtual keyboard Layout (thanks to [@felix068](https://github.com/felix068))
* feat: add support for enabling/disabling HDMI output (PCIe version only) (thanks to [@tpretz](https://github.com/tpretz))
* feat: add support for custom mouse wheel speed
* fix: prevent direct H.264 stream buffer overflow and replay issues
* perf: improve keyboard paste performance (thanks to [@ethanperrine](https://github.com/ethanperrine))
* Localization
* update Korean translation (thanks to [@kmw0410](https://github.com/kmw0410))
* update Ukrainian translation (thanks to [@arbdevml](https://github.com/arbdevml))
* update Russian translation (thanks to [@arbdevml](https://github.com/arbdevml))
## 2.2.7 [e18ec22](https://github.com/sipeed/NanoKVM/commit/e18ec2219d22886529575d1fdaad5c320e05f5b2) (2025-05-08)
* feat: add HTTPS support
* feat: support direct H.264 streaming over HTTP
* Localization
* update Russian translation (thanks to [polyzium](https://github.com/polyzium))
* update Dutch translation (thanks to [LeonStraathof](https://github.com/LeonStraathof))
* update Ukrainian translation (thanks to [click0](https://github.com/click0))
* update German translation (thanks to [3limin4tor](https://github.com/3limin4tor))
## 2.2.6 [c83dc55](https://github.com/sipeed/NanoKVM/commit/c83dc5565c9dbed22336661a8832edbd93a06d11) (2025-04-17)
* feat: add mouse jiggler to prevent system sleep
* feat: add support for swap memory
* feat: add support for customizing the device hostname
* feat: add support for customizing the web page title
* feat: add support for assigning custom names to Wake-on-LAN MAC addresses
* feat: add confirmation prompts for power operations
* feat: add logo to the login page (thanks to [S33G](https://github.com/S33G))
* fix: fix possible privacy issues with MIC drivers. [Repair Record](https://github.com/sipeed/NanoKVM/commit/f9244b36df090a05cd59ba11ea4fd01e9b638995)
* fix: fix iptables rule that could interfere with SSH connections (thanks to [scpcom](https://github.com/scpcom))
* fix: fix the static IP gateway configuration might not apply correctly (thanks to [xitation](https://github.com/xitation))
* perf: optimized OLED display handling and sleep logic
* perf: improve H.264 streaming reliability by adding a heartbeat mechanism
* perf: set the minimum screen size to 640x480
* perf: add display of both wired and wireless IPv4 addresses in the settings page
* perf: update the Thai language translations (thanks to [ChokunPlayZ](https://github.com/ChokunPlayZ))
* chore: bump axios to 1.8.4
* chore: bump golang.org/x/net to v0.39.0
* chore: bump github.com/golang-jwt/jwt/v5 to to v5.2.2
## 2.2.5 [3286cc2](https://github.com/sipeed/NanoKVM/commit/3286cc2f85a14133d65935cb476c833dcf151459) (2025-03-26)
* fix: server crash caused by MJPEG frame detection error
* feat: add HID-Only mode
* feat: support preview updates
* perf: improve image reading performance by optimizing screen parameters
## 2.2.4 [1bf986d](https://github.com/sipeed/NanoKVM/commit/1bf986d41b34d568c1ffee5df90ce61b6b08456b) (2025-03-21)
* fix: resolve USB initialization issue
* fix: correct abnormal updates in certain models
* perf: add version restrictions for production testing
## 2.2.3 [6ef83cb](https://github.com/sipeed/NanoKVM/commit/6ef83cb22fcd77f721d32c97c85d12f2bfc3035a) (2025-03-21)
* feat: add support for setting H.264 GOP
* fix: resolve deadlock caused by HDMI resolution errors
* perf: merge H.264 SPS and PPS into I-frame
* perf: refactor MJPEG frame detection
* perf: added more configuration options to the serial port terminal (thanks to [@mekaris](https://github.com/mekaris))
* perf: improve the `update-nanokvm.py` script (thanks to [@reishoku](https://github.com/reishoku))
* perf: disable mDNS by default in new products
* perf: update log timestamp to millisecond precision
* chore: bump Go to 1.23
* chore: bump `golang.org/x/net` to v0.37.0
## 2.2.2 [58d5ab2](https://github.com/sipeed/NanoKVM/commit/58d5ab2d37244b1e1a68b925a5c23c324c489ad3) (2025-03-11)
* feat: add watchdog for NanoKVM-Server
* feat: add support for UE chip
* feat: support system reboot
* feat: support enable/disable mDNS
* fix: resolve UE chip cannot start server
* perf: refactor automatic resolution detection
* perf: add output prompt for unsupported resolutions
* perf: add lock to kvmv_read_img
* perf: configurable VENC automatic recycling feature
* perf: add maximum limit for vi
* perf: add tooltips to menu bar (thanks to [@S33G](https://github.com/S33G))
* perf: menu bar is now draggable (thanks to [@forumi0721](https://github.com/forumi0721))
* perf: image list support auto-refresh (thanks to [@forumi0721](https://github.com/forumi0721))
* perf: update translations
## 2.2.1 [b5e48a0](https://github.com/sipeed/NanoKVM/commit/b5e48a07e82df3aedd60442342ae50b95684a697) (2025-02-21)
* fix: mounted image were not being detected correctly
* perf: add support for CD-ROM mode when mounting image (thanks to [@scpcom](https://github.com/scpcom))
* perf: add a loading state during login
* perf: add changelog link in settings
* perf: update translation and cleanup the code (thanks to [@ChokunPlayZ](https://github.com/ChokunPlayZ) [@Stoufiler](https://github.com/Stoufiler) [@polyzium](https://github.com/polyzium) [@Jonher937](https://github.com/Jonher937) [@S33G](https://github.com/S33G))
## 2.2.0 [0dbf8c0](https://github.com/sipeed/NanoKVM/commit/0dbf8c007f2d0183d0f0601c3da6d3c3fccd8b31) (2025-02-17)
NanoKVM [Image v1.4.0](https://github.com/sipeed/NanoKVM/releases/tag/v1.4.0) has been released!
> Please refer to the [wiki](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/system/introduction.html) for more details about the image and application.
* fix: improve password update notification logic (thanks to [@li20034](https://github.com/li20034))
* perf: increase update wait time to 10s (from 6s)
* perf: update Korean translation (thanks to [@forumi0721](https://github.com/forumi0721))
* perf: update Traditional Chinese translation (thanks to [@protonchang](https://github.com/protonchang))
* refactor: update `libkvm.so` and `libkvm_mmf.so` libraries
## 2.1.6 [6eb4a4e](https://github.com/sipeed/NanoKVM/commit/6eb4a4ea6254f465a47f9881d13934c686649061) (2025-02-14)
* feat: support downloading image from online URL (thanks to [@Itxaka](https://github.com/Itxaka))
* feat: add keyboard shortcut `Ctrl+Alt+Del` (thanks to [@CaffeeLake](https://github.com/CaffeeLake))
* fix: fix the CSRF issue
* perf: add an option to configure custom ICE servers (thanks to [@VMFortress](https://github.com/VMFortress))
* perf: removed unnecessary modifications to DNS configuration
* perf: add an SSH enable/disable toggle in the web UI
* perf: add a Tailscale enable/disable toggle in the web UI
* perf: download Tailscale installation package from the official source
* perf: automatic enable/disable GOMEMLIMIT on tailscale start/stop
* perf: add JWT configuration
* secretKey: customize secret key. If empty, generated a random 64-byte secret key by default
* refreshTokenDuration: customize token expiration time
* revokeTokensOnLogout: invalidate all JWT tokens on logout
* perf: implement secure password storage using bcrypt hashing
* perf: implement integrity checks for online updates
* refactor: refactor HDMI module and remove the dependency `libmaixcam_lib.so`
* refactor: web terminal use pty instead of SSH
* refactor: move Tailscale APIs from the `network` module to the `extensions` module
## 2.1.5 [85f6447](https://github.com/sipeed/NanoKVM/commit/85f6447a16cc2591c6459b7d3dfda4d4cb75e98c) (2025-01-14)
* feat: add HDMI reset for NanoKVM-PCIe
* fix: remove unnecessary lock acquisition during HID reset
* refactor: refactor Tailscale
## 2.1.4 [d7ca7c4](https://github.com/sipeed/NanoKVM/commit/d7ca7c453d821ad099bf79b463969419041279cb) (2025-01-10)
* feat: support configuring OLED sleep settings
* feat: support setting the `GOMEMLIMIT` environment variable
* fix: fix Wi-Fi configuration
* perf: password changes now update both the web user and the system root user
* perf: add MAC address verification for Wake-on-LAN
* refactor: a lot update to web UI
* refactor: refactor Tailscale
## 2.1.3 [26078fe](https://github.com/sipeed/NanoKVM/commit/26078fe46e43d4543d7b09901b4992e4fbe4f01f) (2024-12-27)
* feat: add API to retrieve Wi-Fi information
* fix: fix keyboard modifier keys
* fix: update keyboard and mouse HID codes
* fix: update hardware version information
## 2.1.2 [5a39562](https://github.com/sipeed/NanoKVM/commit/5a39562f2d32695933f4e7e86866136236cc9903) (2024-12-04)
* feat: add hardware version to configuration
* feat: add Wi-Fi configuration support for NanoKVM-PCIe
* perf: update web UI
* chore: add dependency libraries
## 2.1.1 [74a303b](https://github.com/sipeed/NanoKVM/commit/74a303bd5cbb58f9d8ddd81abaaf4919dbbfb71b) 2024-11-06
* feat: support h264

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>.

139
README.md Normal file
View File

@@ -0,0 +1,139 @@
NanoKVM
======
<div align="center">
![](https://wiki.sipeed.com/hardware/assets/NanoKVM/introduce/NanoKVM_3.png)
<h3>
<a href="https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html">🚀 Quick Start</a>
|
<a href="https://cn.dl.sipeed.com/shareURL/KVM/nanoKVM">🛠️ Hardware Details</a>
|
<a href="https://github.com/sipeed/NanoKVM/releases/latest">💾 Firmware Releases</a>
</h3>
English | [中文](./README_ZH.md) | [日本語](./README_JA.md) | [한국어](./README_KO.md)
</div>
## 🌟 What is NanoKVM?
NanoKVM is a series of compact, open-source IP-KVM devices. Built upon the LicheeRV Nano (RISC-V), NanoKVM allows you to remotely access and control computers as if you were sitting right in front of them perfect for managing servers, embedded systems, or any headless machine.
## 📦 Product Family
We offer several NanoKVM versions to suit your needs:
* **NanoKVM-Cube Lite:** A barebones kit for DIY enthusiasts and enterprise users needing bulk deployment.
* **NanoKVM-Cube Full:** A complete package with a sleek case, accessories, and a pre-flashed system SD card. Ready to use out-of-the-box, ideal for individual users.
* **NanoKVM-PCIe:** A unique form factor with a PCIe bracket for internal chassis mounting, drawing power directly from a PCIe slot. And add optional WiFi and PoE functions.
### 🚀 NanoKVM-Pro: The 4K Powerhouse
Based on popular demand, we've upgraded NanoKVM to the **NanoKVM-Pro**:
* **Resolution Upgrade:** From 1080P to stunning **4K@30fps / 2K@60fps**.
* **Network Upgrade:** Blazing fast **GbE + PoE + WiFi 6** (up from 100M Ethernet).
* **Latency Upgrade:** Encoder accelerated latency reduced from 100-150ms to **50-100ms**.
> The NanoKVM-Pro is now available for pre-sale! [Click here for product details](https://sipeed.com/nanokvm/pro).
<div align="center">
![NanoKVM Product Family](https://cdn.sipeed.com/public/nanokvm-products.jpg)
</div>
## 🛠️ Technical Specifications
| Product | NanoKVM-Pro | NanoKVM (Cube/PCIe) | GxxKVM | JxxKVM |
|------------------- |-------------------------------------- |---------------------------------- |----------------------------------- |------------------------------------ |
| Core | AX631 2xA53 1.5G | SG2002 1xC906 1.0G | RV1126 4xA7 1.5G | RV1106 1xA7 1.2G |
| Memory & Storage | 1G LPDDR4X + 32G eMMC | 256M DDR3 + 32G microSD | 1G DDR3 + 8G eMMc | 256M DDR3 + 16G eMMC |
| System | NanoKVM / PiKVM | NanoKVM | GxxKVM | JxxKVM |
| Resolution | 4K@30fps / 2K@60fps | 1080P@60fps | 4K@30fps / 2K@60fps | 1080P@60fps |
| HDMI Loopout | 4K loopout | x | x | x |
| Video Encoding | MJPEG / H.264 / H.265 | MJPEG / H264 | MJPEG / H264 | MJPEG / H264 |
| Audio Transmit | ✓ | x | ✓ | x |
| UEFI / BIOS | ✓ | ✓ | ✓ | ✓ |
| Emulated USB Keyboard & Mouse | ✓ | ✓ | ✓ | ✓ |
| Emulated USB ISO | ✓ | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ | x |
| Wake-on-LAN | ✓ | ✓ | ✓ | ✓ |
| Web Terminal | ✓ | ✓ | ✓ | ✓ |
| Serial Terminal | 3 channels | 2 channels | x | 1 channel |
| Custom Scripts | ✓ | ✓ | x | x |
| Storage | 32G eMMC 300MB/s | 32G MicroSD 12MB/s | 8G eMMC 120MB/s | 8G eMMC 60MB/s |
| Ethernet | 1000M | 100M | 1000M | 100M |
| PoE | Optional | Optional | x | x |
| WiFi | Optional WiFi6 | Optional WiFi6 | x | x |
| ATX Power Control | ✓ | ✓ | Extra $15 | Extra $10 |
| Display | 1.47" 320x172 LCD / 0.96" 128x64 OLED | 0.96" 128x64 OLED | - | 1.68" 280x240 |
| More Features | Sync LED Strip / Smart Assistant | - | - | - |
| Power Consumption | 0.4A@5V | 0.2A@5V | 0.4A@5V | 0.2A@5V |
| Power Input | USB-C or PoE | USB-C | USB-C | USB-C |
| Dimensions | 65x65x26mm | 40x36x36mm | 80x60x17.5mm | 60x43x(24~31)mm |
| Price | ~~$79~~ $69 ATX / ~~$89~~ $79 Desk | $25 Lite / $50 Full(with ATX) | $89 no ATX / $102 with ATX | $69 no ATX / $79 with ATX |
## 📂 Project Structure
``` shell
├── kvmapp # APP update package
│ ├── jpg_stream # Compatible for direct updates from very old versions
│ ├── kvm_new_app # Triggers necessary components for kvm_system update
│ ├── kvm_system # kvm_system application
│ ├── server # NanoKVM front-end and back-end applications
│ └── system # Necessary system components
├── web # NanoKVM front-end
├── server # NanoKVM back-end
├── support # Auxiliary functions (image subsystem, system status, system updates, screen, keys, etc.)
│ ├── sg2002 # NanoKVM-Lite/Full/PCIe
│ └── h618 # NanoKVM-Pro
├── ...
```
## 🔩 Hardware Platform (NanoKVM Cube/PCIe)
NanoKVM is based on Sipeed [LicheeRV Nano](https://wiki.sipeed.com/hardware/zh/lichee/RV_Nano/1_intro.html)you can find specifications, schematics, and dimensional drawings [here](http://cn.dl.sipeed.com/shareURL/LICHEE/LicheeRV_Nano).
The NanoKVM Lite is constructed by the LicheeRV Nano and HDMItoCSI board, and the NanoKVM FULL adds the NanoKVM-A/B board and shell to the NanoKVM Lite. The HDMItoCSI board is used to convert the HDMI signal; NanoKVM-A, including OLED, ATX control output (USB Type-C interface), auxiliary power supply and ATX power on/off and reset buttons; The NanoKVM-B is connected to the plate at one end and the computer at the other end is connected to the computer ATX-Pin, which is used to remotely control the power of the computer.
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.
Note: Out of the 256MB memory in SG2002, 158MB 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_RV_Nano_KVM_B_30131.pdf)
* [NanoKVM img](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
![NanoKVM PCB Pinout](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_2.jpg)
## 🤝 Contributing
We welcome contributions! Here's how you can help:
1. Fork the repository.
2. Create a feature branch.
3. Commit your changes.
4. Push to the branch.
5. Open a Pull Request.
Please keep your pull requests small and focused to facilitate easier review and merging.
> 🎁 **Contributors who submit high-quality Pull Requests may receive a NanoKVM Cube, PCIe, or Pro as a token of our appreciation!**
## 🛒 Where to Buy
* [Aliexpress(global except USA&Russia)](https://www.aliexpress.com/item/1005007369816019.html)
* [淘宝](https://item.taobao.com/item.htm?id=811206560480)
* [Preorder (any other country that not support in Aliexpress or Taobao)](https://sipeed.com/nanokvm)
## 💬 Community & Support
* [MaixHub Discussion](https://maixhub.com/discussion/nanokvm)
* QQ group: 703230713
## 📜 License
This project is licensed under the GPL-3.0 License - see the LICENSE file for details.

129
README_JA.md Normal file
View File

@@ -0,0 +1,129 @@
NanoKVM
======
<div align="center">
![](https://wiki.sipeed.com/hardware/assets/NanoKVM/introduce/NanoKVM_3.png)
<h3>
<a href="https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html"> クイックスタート </a>
|
<a href="https://cn.dl.sipeed.com/shareURL/KVM/nanoKVM"> ハードウェア </a>
</h3>
[English](./README.md) | [中文](./README_ZH.md) | 日本語 | [한국어](./README_KO.md)
</div>
> NanoKVM は [RISC-V](https://en.wikipedia.org/wiki/RISC-V) を搭載しています!
> 使用中に問題や提案がある場合は、ここで issue を提出するか、[MaixHub Discussion](https://maixhub.com/discussion/nanokvm) でお知らせください。
## オープンソース & コントリビューション
### 2025.02.19 更新
NanoKVM のすべてのコンポーネントはオープンソース化されており、[front-end](https://github.com/sipeed/NanoKVM/tree/main/web)、[back-end](https://github.com/sipeed/NanoKVM/tree/main/server)、[kvm_vision](https://github.com/sipeed/NanoKVM/tree/main/vision/components/kvm)、[kvm_mmf](https://github.com/sipeed/NanoKVM/tree/main/vision/components/kvm_mmf)、[kvm_system](https://github.com/sipeed/NanoKVM/tree/main/support)、[kvmapp update package](https://github.com/sipeed/NanoKVM-System/tree/main/kvmapp)、[system sdk](https://github.com/sipeed/LicheeRV-Nano-Build/tree/NanoKVM)、[packaging methods](https://github.com/sipeed/LicheeRV-Nano-Build/blob/NanoKVM/kvm/NanoKVM_img.sh)が含まれます。
### 2025.02.14 更新
最新のアプリケーションバージョン v2.1.6 には、多くのセキュリティ強化とバグ修正が追加されているため、一般のユーザーはこのバージョン以降へのアップグレードをお勧めします。
### 2025.02.05 更新
セキュリティを懸念しているユーザーは、この issue をお読みください: <https://github.com/sipeed/NanoKVM/issues/301>、セキュリティに関するすべての懸念事項について説明されています。
GitHub は、オープンで透明性のあるプラットフォームとして、いわゆる「バックドア」の懸念事項を議論する場を提供しています。オープンソースであることにより、製品のセキュリティがさらに強化されます!
### 2024.10.18 更新
10/08にバックエンドコードをオープンソース化しました。すぐにPRを提出してくれたCivilに感謝します。最新のNanoKVM-PCIeを報酬として提供します
10月中旬のバッチはテストとパッケージングを開始しており、10/01以前のほとんどの注文は次週と次々週に出荷されます。
10/01以降、アリエクスプレスの出荷日は12月に変更されました。これは保守的な納期です。10月の注文は11/15〜12/15の間に発送される予定です。
## 紹介
Lichee NanoKVMは、LicheeRV NanoをベースにしたIP-KVM製品で、LicheeRV Nanoの極小サイズと強力な機能を継承しています。
Lichee NanoKVMは2つのバージョンがあります
NanoKVM Liteは基本構成で、一定のDIY能力を持つ個人ユーザーや大量のニーズを持つ企業ユーザーに適しています。
NanoKVM Fullは完全版で、洗練されたケースと完全なアクセサリーを備え、起動時にすぐに使用できるシステムミラーカードが内蔵されており、個人ユーザーに推奨されます。
![NanoKVM 分解画像](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_1.jpg)
## 技術仕様
| 製品 | NanoKVM (Lite) | NanoKVM (Full) | PiKVM V4 |
|----------------------- |-------------------------------------- |---------------------------------- |----------------------------------- |
| 計算ユニット | LicheeRV Nano(RISCV) | LicheeRV Nano(RISCV) | CM4 (ARM) |
| 解像度 | 1080P @ 60fps | 1080P @ 60fps | 1080P @ 60fps |
| ビデオエンコーディング | MJPEG, H264 | MJPEG, H264 | MJPEG, H264 |
| ビデオ遅延 | 90230ms | 90230ms | 100230ms |
| UEFI/BIOS | ✓ | ✓ | ✓ |
| 仮想HID | ✓ | ✓ | ✓ |
| 仮想CD-ROM | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ |
| Wake-on-LAN | ✓ | ✓ | ✓ |
| ETH | 100M/10M | 100M/10M | 1000M/100M/10M |
| ATX電源制御 | なし、ユーザーが自分で接続 | USBインターフェースIO制御ボード | RJ-45インターフェースIO制御ボード |
| OLED | なし、ユーザーが自分で接続 | 128x64 0.96" 白 | 128x32 0.91" 白 |
| UART | 2 | 2 | 1 |
| TFカード | なし | ✓ | ✓ |
| 拡張 | なし | PoE | WiFi/LTE |
| 消費電力 | 0.2A@5V | 0.2A@5V | ピーク時 2.6A@5V |
| 電源入力 | PC USBで給電可能 | PC USBまたは補助電源 | DC 5V 3A電源が必要 |
| 冷却 | 静音ファンレス | 静音ファンレス | ファン冷却 |
| サイズ | 23x37x15mm 1/30 PiKVM V4サイズ | 40x36x36mm 1/7 PiKVM V4サイズ | 120x68x44mm |
![NanoKVM PCB ピン配置](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_2.jpg)
## NanoKVM ハードウェアプラットフォーム
NanoKVMはSipeed [LicheeRV Nano](https://wiki.sipeed.com/hardware/zh/lichee/RV_Nano/1_intro.html)に基づいており、仕様、回路図、寸法図は[こちら](http://cn.dl.sipeed.com/shareURL/LICHEE/LicheeRV_Nano)で確認できます。
NanoKVM LiteはLicheeRV NanoとHDMItoCSIボードで構成され、NanoKVM FULLはNanoKVM LiteにNanoKVM-A/Bボードとシェルを追加しています。HDMItoCSIボードはHDMI信号を変換するために使用されます。NanoKVM-AにはOLED、ATX制御出力USB Type-Cインターフェース、補助電源供給およびATX電源オン/オフおよびリセットボタンが含まれています。NanoKVM-Bは一端がAボードに接続され、他端がコンピュータのATXピンに接続され、コンピュータの電源をリモートで制御します。
NanoKVMイメージはLicheeRV Nano SDKおよびMaixCDKに基づいて構築されており、LicheeRV Nanoを使用する資料と互換性があります。逆に、KVMソフトウェアはLicheeRV Nanoや他のSG2002製品では使用できません。LicheeRV NanoやMaixCamでHDMI入力アプリケーションを構築したい場合は、技術サポートを受けるためにお問い合わせください。
SG2002の256MBメモリのうち、現在158MBがマルチメディアサブシステムに割り当てられており、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)
## ロードマップ
### Q1 2025
**改善:**
- [x] HDMI モジュールをリファクタリングし、libmaixcam_lib.so の依存関係を削除
- [x] SSH をデフォルトで無効にし、Web UI に有効/無効の切り替えを追加
- [x] Tailscale をデフォルトで無効にし、Web UI に有効/無効の切り替えを追加
- [x] 設定ファイルに JWT 設定オプションを追加
- [x] bcrypt を利用したパスワードストレージのセキュリティ保護
**配布:**
- [x] GitHub 経由でのアプリケーション配布
- [x] オンラインでの更新の際に整合性チェックを実施
- [ ] オフラインでの更新をサポート
**バグ修正:**
- [x] DNS の問題を修正
- [x] CSRF の脆弱性を修正
**機能**
- [ ] [79](https://github.com/sipeed/NanoKVM/issues/79) Zerotier をサポート
- [ ] [99](https://github.com/sipeed/NanoKVM/issues/99) WireGuard をサポート
- [ ] [249](https://github.com/sipeed/NanoKVM/issues/249) Mouse Jiggler を追加
## 購入方法
* [Aliexpress(グローバル、米国とロシアを除く)](https://www.aliexpress.com/item/1005007369816019.html)
* [淘宝](https://item.taobao.com/item.htm?id=811206560480)
* [予約注文 (淘宝とアリエクスプレスがサポートされていない国)](https://sipeed.com/nanokvm)
## コミュニティ
* [MaixHub Discussion](https://maixhub.com/discussion/nanokvm)
* QQグループ: 703230713

139
README_KO.md Normal file
View File

@@ -0,0 +1,139 @@
NanoKVM
======
<div align="center">
![](https://wiki.sipeed.com/hardware/assets/NanoKVM/introduce/NanoKVM_3.png)
<h3>
<a href="https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html">🚀 빠른 시작</a>
|
<a href="https://cn.dl.sipeed.com/shareURL/KVM/nanoKVM">🛠️ 하드웨어 정보</a>
|
<a href="https://github.com/sipeed/NanoKVM/releases/latest">💾 펌웨어 릴리즈</a>
</h3>
[English](./README.md) | [中文](./README_ZH.md) | [日本語](./README_JA.md) | 한국어
</div>
## 🌟 NanoKVM이 무엇인가요?
NanoKVM은 소형 오픈 소스 IP-KVM 장치 시리즈입니다. LicheeRV Nano(RISC-V)를 기반으로 구축된 NanoKVM을 사용하면 마치 컴퓨터 앞에 바로 앉아있는 것처럼 원격으로 컴퓨터에 접근하고 제어할 수 있어 서버, 임베디드 시스템 또는 모든 헤드리스 머신을 관리하는 데 완벽합니다.
## 📦 제품군
다양한 요구를 충족할 수 있도록 여러 NanoKVM 버전을 제공합니다:
* **NanoKVM-Cube Lite:** DIY 사용자 및 대량 배포가 필요한 기업용을 위한 최소 구성 키트입니다.
* **NanoKVM-Cube Full:** 세련된 케이스, 액세서리, 사전 플래시된 시스템 SD 카드가 포함된 완전 구성 패키지입니다. 개봉 후 즉시 사용할 수 있어 개인 사용자에게 적합합니다.
* **NanoKVM-PCIe:** 독특한 폼팩터로, PCIe 브래킷을 통해 섀시 내부에 장착하며, 전원인 PCIe 슬롯에서 직접 공급받습니다. 선택적으로 WiFi와 PoE 기능을 추가할 수 있습니다.
### 🚀 NanoKVM-Pro: 4K를 위한 파워 머신
대중적인 수요를 기반으로, NanoKVM을 **NanoKVM-Pro**로 업그레이드했습니다:
* **해상도 업그레이드:** 1080P에서 놀라운 **4K@30fps / 2K@60fps**까지.
* **네트워크 업그레이드:** 초고속 **GbE + PoE + WiFi 6** (100M 이더넷 대비 향상).
* **지연 시간 업그레이드:** 인코더 가속 지연시간이 100-150ms에서 **50-100ms**로 감소.
> NanoKVM-Pro가 예약 판매 중입니다! [제품 세부 정보는 여기를 클릭하세요](https://sipeed.com/nanokvm/pro).
<div align="center">
![NanoKVM Product Family](https://cdn.sipeed.com/public/nanokvm-products.jpg)
</div>
## 🛠️ 기술 사양
| 제품 | NanoKVM-Pro | NanoKVM (Cube/PCIe) | GxxKVM | JxxKVM |
|------------------- |-------------------------------------- |---------------------------------- |----------------------------------- |------------------------------------ |
| 코어 | AX631 2xA53 1.5G | SG2002 1xC906 1.0G | RV1126 4xA7 1.5G | RV1106 1xA7 1.2G |
| 메모리 & 저장 공간 | 1G LPDDR4X + 32G eMMC | 256M DDR3 + 32G microSD | 1G DDR3 + 8G eMMc | 256M DDR3 + 16G eMMC |
| 시스템 | NanoKVM / PiKVM | NanoKVM | GxxKVM | JxxKVM |
| 해상도 | 4K@30fps / 2K@60fps | 1080P@60fps | 4K@30fps / 2K@60fps | 1080P@60fps |
| HDMI 루프아웃 | 4K 루프아웃 | x | x | x |
| 영상 인코딩 | MJPEG / H.264 / H.265 | MJPEG / H264 | MJPEG / H264 | MJPEG / H264 |
| 오디오 전송 | ✓ | x | ✓ | x |
| UEFI / BIOS | ✓ | ✓ | ✓ | ✓ |
| USB 키보드 & 마우스 에뮬레이션 | ✓ | ✓ | ✓ | ✓ |
| USB ISO 에뮬레이션 | ✓ | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ | x |
| Wake-on-LAN | ✓ | ✓ | ✓ | ✓ |
| 웹 터미널 | ✓ | ✓ | ✓ | ✓ |
| 시리얼 터미널 | 3 채널 | 2 채널 | x | 1 채널 |
| 사용자 정의 스크립트 | ✓ | ✓ | x | x |
| 저장 공간 | 32G eMMC 300MB/s | 32G MicroSD 12MB/s | 8G eMMC 120MB/s | 8G eMMC 60MB/s |
| 이더넷 | 1000M | 100M | 1000M | 100M |
| PoE | 옵션 | 옵션 | x | x |
| WiFi | WiFi6 옵션 | WiFi6 옵션 | x | x |
| ATX 전원 조작 | ✓ | ✓ | $15 추가 | $10 추가 |
| 디스플레이 | 1.47" 320x172 LCD / 0.96" 128x64 OLED | 0.96" 128x64 OLED | - | 1.68" 280x240 |
| 기타 기능 | LED 줄 동기화 / 스마트 어시스턴트 | - | - | - |
| 전력 소비량 | 0.4A@5V | 0.2A@5V | 0.4A@5V | 0.2A@5V |
| 전원 입력 | USB-C 또는 PoE | USB-C | USB-C | USB-C |
| 크기 | 65x65x26mm | 40x36x36mm | 80x60x17.5mm | 60x43x(24~31)mm |
| 가격 | ~~$79~~ $69 ATX / ~~$89~~ $79 Desk | $25 Lite / $50 Full(with ATX) | ATX 미사용 시 $89 / ATX 사용 시 $102 | ATX 미사용 시 $69 / ATX 사용 시 $79 |
## 📂 프로젝트 구조
``` shell
├── kvmapp # APP 업데이트 패키지
│ ├── jpg_stream # 매우 오래된 버전에서도 직접 업데이트 가능하도록 호환됨
│ ├── kvm_new_app # kvm_system 업데이트에 필요한 구성 요소를 트리거함
│ ├── kvm_system # kvm_system 애플리케이션
│ ├── server # NanoKVM 프론트 엔드와 백엔드 애플리케이션
│ └── system # 필요한 시스템 구성 요소
├── web # NanoKVM 프론트엔드
├── server # NanoKVM 백엔드
├── support # 보조 기능 (이미지 하위 시스템, 시스템 상태, 시스템 업데이트, 화면, 키, 기타.)
│ ├── sg2002 # NanoKVM-Lite/Full/PCIe
│ └── h618 # NanoKVM-Pro
├── ...
```
## 🔩 하드웨어 플랫폼 (NanoKVM Cube/PCIe)
NanoKVM은 Sipeed [LicheeRV Nano](https://wiki.sipeed.com/hardware/zh/lichee/RV_Nano/1_intro.html)를 기반으로 하며,[여기](http://cn.dl.sipeed.com/shareURL/LICHEE/LicheeRV_Nano)에서 사양, 도식, 치수, 도면은 여기에서 찾을 수 있습니다.
NanoKVM Lite는 LicheeRV Nano와 HDMItoCSI 보드로 구성되어 있으며, NanoKVM FULL은 NanoKVM Lite에 NasnoKVM-A/B 보드와 케이스를 추가한 구성입니다. HDMItoCSI 보드는 HDMI 신호를 변환하는 역할을 하고 NanoKVM-A는 OLED, ATX 전원 출력 (USB Type-C 인터페이스), 보조 전원 공급 장치, ATX 전원 켜기/끄기 및 리셋 버튼을 포함합니다. NanoKVM-B는 한쪽 끝이 컴퓨터와 연결되고 다른 한쪽 끝은 컴퓨터의 ATX 핀에 연결되어 컴퓨터의 전원을 원격으로 제어하는 데 사용됩니다.
NanoKVM 이미지는 LicheeRV Nano SDK와 MaixCDK로 구축되었으며, LicheeRV Nano를 사용하는 자재와 호환됩니다. 반면에 KVM 소프트웨어는 LicheeRV Nano나 다른 SG2002 제품과 함께 사용할 수 없습니다. 만약 LicheeRV Nano나 MaixCam에서 HDMI 입력 애플리케이션을 구축하고 싶으시다면, 기술 지원에 문의해 주세요.
참고: SG2002의 256MB 메모리 중에 158MB는 멀티미디어 하위 폴더에 할당되어 있으며, 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_RV_Nano_KVM_B_30131.pdf)
* [NanoKVM 이미지](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
![NanoKVM PCB Pinout](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_2.jpg)
## 🤝 기여
여러분의 기여를 환영합니다! 도움을 줄 수 있는 방법은 다음과 같습니다:
1. 레포지토리를 포크하세요
2. 기능 브랜치를 만드세요
3. 변경한 것을 커밋하세요
4. 브랜치로 푸시하세요
5. 풀 리퀘스트를 생성하세요
Please keep your pull requests small and focused to facilitate easier review and merging.
> 🎁 **고품질 풀 리퀘스트를 제출한 기여자는 감사의 표시로 NanoKVM Cube, PCIe, 또는 Pro를 받을 수 있습니다!**
## 🛒 어디서 구매하나요?
* [Aliexpress(미국&러시아를 제외한 전 세계)](https://www.aliexpress.com/item/1005007369816019.html)
* [淘宝](https://item.taobao.com/item.htm?id=811206560480)
* [사전 주문 (Aliexpress나 Taobao를 지원하지 않는 국가)](https://sipeed.com/nanokvm)
## 💬 커뮤니티 & 지원
* [MaixHub Discussion](https://maixhub.com/discussion/nanokvm)
* QQ group: 703230713
## 📜 라이센스
이 프로젝트는 GPL-3.0 라이센스에 따라 라이센스가 부여됩니다. 자세한 사항은 LICENSE 파일을 참조하세요.

139
README_ZH.md Normal file
View File

@@ -0,0 +1,139 @@
NanoKVM
======
<div align="center">
![](https://wiki.sipeed.com/hardware/assets/NanoKVM/introduce/NanoKVM_3.png)
<h3>
<a href="https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html">🚀 快速开始</a>
|
<a href="https://cn.dl.sipeed.com/shareURL/KVM/nanoKVM">🛠️ 硬件信息</a>
|
<a href="https://github.com/sipeed/NanoKVM/releases/latest">💾 固件发布</a>
</h3>
[English](./README.md) | 中文 | [日本語](./README_JA.md) | [한국어](./README_KO.md)
</div>
## 🌟 NanoKVM 是什么?
NanoKVM 是一系列紧凑型开源 IP-KVM 设备。NanoKVM 基于 LicheeRV Nano (RISC-V) 构建,让您能够身临其境般的远程访问和控制计算机,是管理服务器、嵌入式系统或任何无头设备的理想之选。
## 📦 产品系列
我们提供多种 NanoKVM 版本以满足您的需求:
* **NanoKVM-Cube Lite**:为 DIY 爱好者和需要批量部署的企业用户提供的准系统套件。
* **NanoKVM-Cube Full**:包含外壳、配件以及预装系统 SD 卡的完整套装。开箱即用,非常适合个人用户。
* **NanoKVM-PCIe**:独特的外形设计,配备 PCIe 支架,可安装在机箱内部,并直接从 PCIe 插槽供电。可选配 WiFi 和 PoE 功能。
### 🚀 NanoKVM-Pro
根据大众的需求,我们将 NanoKVM 升级到了 **NanoKVM-Pro**
* **分辨率升级**:从 1080P 升级到 **4K@30fps / 2K@60fps**
* **网络升级**:从百兆网口升级到超快的 **GbE + WiFi 6**
* **延迟升级**:编码器加速延迟从 100-150 毫秒减少到 **50-100 毫秒**
> NanoKVM-Pro 现已开启预售![点击此处查看产品详情](https://sipeed.com/nanokvm/pro)。
<div align="center">
![NanoKVM Product Family](https://cdn.sipeed.com/public/nanokvm-products.jpg)
</div>
## 🛠️ 技术规格
| 产品 | NanoKVM-Pro | NanoKVM (Cube/PCIe) | GxxKVM | JxxKVM |
|------------------- |-------------------------------------- |---------------------------------- |----------------------------------- |------------------------------------ |
| 核心 | AX631 2xA53 1.5G | SG2002 1xC906 1.0G | RV1126 4xA7 1.5G | RV1106 1xA7 1.2G |
| 内存&存储 | 1G LPDDR4X + 32G eMMC | 256M DDR3 + 32G microSD | 1G DDR3 + 8G eMMc | 256M DDR3 + 16G eMMC |
| 系统 | NanoKVM / PiKVM | NanoKVM | GxxKVM | JxxKVM |
| 分辨率 | 4K@30fps / 2K@60fps | 1080P@60fps | 4K@30fps / 2K@60fps | 1080P@60fps |
| HDMI 环出 | 4K 环出 | x | x | x |
| 视频编码 | MJPEG / H.264 / H.265 | MJPEG / H264 | MJPEG / H264 | MJPEG / H264 |
| 音频输出 | ✓ | x | ✓ | x |
| UEFI / BIOS | ✓ | ✓ | ✓ | ✓ |
| 模拟 USB 键鼠 | ✓ | ✓ | ✓ | ✓ |
| 模拟 USB ISO | ✓ | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ | x |
| 局域网唤醒 | ✓ | ✓ | ✓ | ✓ |
| 网页终端 | ✓ | ✓ | ✓ | ✓ |
| 串口终端 | 3 channels | 2 channels | x | 1 channel |
| 用户脚本 | ✓ | ✓ | x | x |
| 存储 | 32G eMMC 300MB/s | 32G MicroSD 12MB/s | 8G eMMC 120MB/s | 8G eMMC 60MB/s |
| 网口 | 1000M | 100M | 1000M | 100M |
| PoE | 可选 | 可选 | x | x |
| WiFi | 可选 WiFi6 | 可选 WiFi6 | x | x |
| ATX 电源控制 | ✓ | ✓ | ✓ | ✓ |
| 显示屏 | 1.47" 320x172 LCD / 0.96" 128x64 OLED | 0.96" 128x64 OLED | - | 1.68" 280x240 |
| 特色功能 | LED 同步灯带 / 智能助手 | - | - | - |
| 功耗 | 0.4A@5V | 0.2A@5V | 0.4A@5V | 0.2A@5V |
| 电源输入 | USB-C or PoE | USB-C | USB-C | USB-C |
| 尺寸 | 65x65x26mm | 40x36x36mm | 80x60x17.5mm | 60x43x(24~31)mm |
| 价格 | ~~$79~~ $69 ATX / ~~$89~~ $79 Desk | $25 Lite / $50 Full(带ATX) | $89 无ATX / $102 带ATX | $69 无ATX / $79 带ATX |
## 📂 项目结构
``` shell
├── kvmapp # APP更新包
│ ├── jpg_stream # 兼容从非常老的版本中直接更新
│ ├── kvm_new_app # 触发 kvm_system 更新必要组件
│ ├── kvm_system # kvm_system 应用
│ ├── server # NanoKVM 前后端应用
│ └── system # 必要系统组件
├── server # NanoKVM 后端
├── support # 辅助功能(图像子系统、系统状态、系统更新、屏幕、按键……)
│ ├── sg2002 # NanoKVM-Lite/Full/PCIe
│ └── h618 # NanoKVM-Pro
├── web # NanoKVM 前端
├── LICENSE
├── README_JA.md
├── README.md
├── README_ZH.md
└── CHANGELOG.md
```
## 🔩 硬件平台(NanoKVM Cube/PCIe)
NanoKVM 基于 Sipeed [LicheeRV Nano](https://wiki.sipeed.com/hardware/zh/lichee/RV_Nano/1_intro.html) 核心板搭建,这部分硬件的规格书、原理图、尺寸图等均可在这里找到:[点击这里](http://cn.dl.sipeed.com/shareURL/LICHEE/LicheeRV_Nano)
NanoKVM Lite 由 LicheeRV Nano E 和 HDMItoCSI 小板构成NanoKVM FULL 在 NanoKVM Lite 基础上增加 NanoKVM-A/B 板和外壳。HDMItoCSI板用于转换HDMI信号NanoKVM-A 包含 OLED、ATX控制输出TypeC接口形式、辅助供电TypeC接口以及ATX开关机、复位按键NanoKVM-B 一端连接A板一端连接电脑ATX针脚用于电脑的远程开关机。
NanoKVM 镜像在LicheeRV Nano SDK 和 MaixCDK 基础上构建,可以兼容使用 LicheeRV Nano 的资料反之LicheeRV Nano 或其他 SG2002 产品无法使用KVM软件。如果您想在 LicheeRV Nano 或 MaixCam 上构建 HDMI输入相关应用请与我们联系以获得技术支持。
注: 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)
![NanoKVM PCB Pinout](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_2.jpg)
## 🤝 贡献代码
我们十分欢迎任何人来贡献代码!您可以通过以下方式提供帮助:
1. Fork 本仓库.
2. 创建一个分支.
3. 提交你的代码.
4. 推送代码到分支.
5. 创建一个PR.
请保持你的 PR 尽量简单且集中,以便于更轻松地审查和合并。
> 🎁 **提交高质量 PR 的贡献者可能会收到 NanoKVM Cube、PCIe 或 Pro 作为感谢礼物!**
## 🛒 购买渠道
* [Aliexpress(全球,除了美国和俄罗斯)](https://www.aliexpress.com/item/1005007369816019.html)
* [淘宝](https://item.taobao.com/item.htm?id=811206560480)
* [Preorder (其它不支持淘宝和速卖通的国家)](https://sipeed.com/nanokvm)
## 💬 社区
* [MaixHub Discussion](https://maixhub.com/discussion/nanokvm)
* QQ group: 703230713

View File

@@ -0,0 +1,91 @@
#!/bin/sh
# nanokvm Rev2.1
case "$1" in
start)
echo -n kvm > /boot/hostname.prefix
cp /mnt/data/sensor_cfg.ini.LT /mnt/data/sensor_cfg.ini
str_value=$(cat /sys/class/cvi-base/base_uid | awk '{print $2}')
first_uint=$(echo $str_value | cut -d'_' -f1)
second_uint=$(echo $str_value | cut -d'_' -f2)
result="$first_uint$second_uint"
echo $result > /device_key
# if [ ! -e /etc/kvm/hw ]
# then
# fi
# echo 504 > /sys/class/gpio/export # pwr led
# echo 505 > /sys/class/gpio/export # hdd led
# echo 503 > /sys/class/gpio/export # pwr key
# echo 507 > /sys/class/gpio/export # rst key
# echo in > /sys/class/gpio/gpio504/direction # pwr led
# echo in > /sys/class/gpio/gpio505/direction # hdd led
# echo out > /sys/class/gpio/gpio503/direction # pwr key
# echo out > /sys/class/gpio/gpio507/direction # rst key
iptables -A INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 8000 -m state --state ESTABLISHED -j DROP
cp -r /kvmapp/kvm_system /tmp/
/tmp/kvm_system/kvm_system &
# if [ -e /kvmapp/kvm_stream ]
# then
# cp -r /kvmapp/kvm_stream /tmp/
# /tmp/kvm_stream/kvm_stream &
# fi
cp -r /kvmapp/server /tmp/
/tmp/server/NanoKVM-Server &
;;
stop)
killall kvm_system
# killall kvm_stream
killall NanoKVM-Server
rm -r /tmp/kvm_system
# rm -r /tmp/kvm_stream
rm -r /tmp/server
echo "OK"
;;
# restart_stream)
# killall kvm_stream
# rm -r /tmp/kvm_stream
# if [ -e /kvmapp/kvm_stream ]
# then
# cp -r /kvmapp/kvm_stream /tmp/
# /tmp/kvm_stream/kvm_stream &
# echo "OK"
# fi
# ;;
restart)
killall kvm_system
# killall kvm_stream
killall NanoKVM-Server
rm -r /tmp/kvm_system
# rm -r /tmp/kvm_stream
rm -r /tmp/server
cp -r /kvmapp/kvm_system /tmp/
/tmp/kvm_system/kvm_system &
# if [ -e /kvmapp/kvm_stream ]
# then
# cp -r /kvmapp/kvm_stream /tmp/
# /tmp/kvm_stream/kvm_stream &
# fi
cp -r /kvmapp/server /tmp/
/tmp/server/NanoKVM-Server &
sync
echo "OK"
;;
esac

View File

@@ -0,0 +1,5 @@
rm /etc/init.d/S95webkvm
cp /kvmapp/jpg_stream/S95nanokvm /etc/init.d/
cp /kvmapp/jpg_stream/dl_lib/libmaixcam_lib.so /kvmapp/kvm_system/dl_lib
rm -r /kvmapp/jpg_stream
/etc/init.d/S95nanokvm restart

0
kvmapp/kvm_new_app Normal file
View File

View File

View File

@@ -0,0 +1,32 @@
#!/bin/sh
if [ "$1" = "start" ]
then
. /etc/profile
printf "load kernel module: "
cd /mnt/system/ko/
insmod soph_sys.ko
insmod soph_base.ko
insmod soph_rtos_cmdqu.ko
insmod soph_fast_image.ko
insmod soph_mipi_rx.ko
insmod soph_snsr_i2c.ko
insmod soph_vi.ko
insmod soph_vpss.ko
insmod soph_dwa.ko
insmod soph_vo.ko
insmod soph_rgn.ko
insmod soph_wdt.ko
insmod soph_clock_cooling.ko
insmod soph_tpu.ko
insmod soph_vcodec.ko
insmod soph_jpeg.ko
insmod soph_vc_driver.ko MaxVencChnNum=9 MaxVdecChnNum=9
insmod soph_rtc.ko
insmod soph_ive.ko
insmod soph_mon.ko
insmod soph_pwm.ko
insmod soph_wiegand.ko
echo "OK"
exit 0
fi

View File

@@ -0,0 +1,42 @@
#!/bin/sh
if [ "$1" = "start" ]
then
# use all sdcard free space for data
parted -s /dev/mmcblk0 "resizepart 2 -0"
echo "yes
8192MB
" | parted ---pretend-input-tty /dev/mmcblk0 "resizepart 2 8192MB"
# resize data filesystem
(resize2fs /dev/mmcblk0p2) &
. /etc/profile
printf "mounting filesystem : "
mkdir -p /boot
mount -t vfat /dev/mmcblk0p1 /boot
mount -t configfs configfs /sys/kernel/config
mount -t debugfs debugfs /sys/kernel/debug
if [ -e /boot/usb.disk0 ]
then
if [ ! -e /etc/kvm.disk0 ]
then
touch /etc/kvm.disk0
# use all sdcard free space for data
parted -s /dev/mmcblk0 "mkpart primary 8193MB 100%"
sleep 1
# resize data filesystem
(mkfs.exfat /dev/mmcblk0p3) &
sleep 1
fi
fi
if [ -e /dev/mmcblk0p3 ]
then
mkdir -p /data
mount /dev/mmcblk0p3 /data
fi
echo "OK"
fi

View File

@@ -0,0 +1,152 @@
#!/bin/sh
# kvmhwd Rev2.1
start_usb_dev(){
. /etc/profile
echo "usb mode: device"
cd /sys/kernel/config/usb_gadget
mkdir g0
cd g0
# echo 0x3346 > idVendor
# echo 0x1009 > idProduct
if [ -e /boot/usb.vid ]
then
cat /boot/usb.vid > idVendor
else
echo 0x3346 > idVendor
fi
if [ -e /boot/usb.pid ]
then
cat /boot/usb.pid > idProduct
else
echo 0x1009 > idProduct
fi
mkdir strings/0x409
echo '0123456789ABCDEF' > strings/0x409/serialnumber
echo 'sipeed' > strings/0x409/manufacturer
echo 'NanoKVM' > strings/0x409/product
mkdir configs/c.1
echo 0xE0 > configs/c.1/bmAttributes
echo 120 > configs/c.1/MaxPower
mkdir configs/c.1/strings/0x409
echo "NanoKVM" > configs/c.1/strings/0x409/configuration
if [ -e /boot/usb.ncm ]
then
mkdir functions/ncm.usb0
ln -s functions/ncm.usb0 configs/c.1/
else
if [ -e /boot/usb.rndis0 ]
then
mkdir functions/rndis.usb0
ln -s functions/rndis.usb0 configs/c.1/
fi
fi
if [ ! -e /boot/disable_hid ]
then
# keyboard
mkdir functions/hid.GS0
if [ -e /boot/BIOS ]
then
echo 1 > functions/hid.GS0/subclass
fi
if [ ! -e /boot/usb.notwakeup ]
then
echo 1 > functions/hid.GS0/wakeup_on_write
fi
echo 1 > functions/hid.GS0/protocol
echo 8 > functions/hid.GS0/report_length
echo -ne \\x05\\x01\\x09\\x06\\xa1\\x01\\x05\\x07\\x19\\xe0\\x29\\xe7\\x15\\x00\\x25\\x01\\x75\\x01\\x95\\x08\\x81\\x02\\x95\\x01\\x75\\x08\\x81\\x03\\x95\\x05\\x75\\x01\\x05\\x08\\x19\\x01\\x29\\x05\\x91\\x02\\x95\\x01\\x75\\x03\\x91\\x03\\x95\\x06\\x75\\x08\\x15\\x00\\x25\\x65\\x05\\x07\\x19\\x00\\x29\\x65\\x81\\x00\\xc0 > functions/hid.GS0/report_desc
ln -s functions/hid.GS0 configs/c.1
# mouse
mkdir functions/hid.GS1
if [ -e /boot/BIOS ]
then
echo 1 > functions/hid.GS1/subclass
fi
if [ ! -e /boot/usb.notwakeup ]
then
echo 1 > functions/hid.GS1/wakeup_on_write
fi
echo 2 > functions/hid.GS1/protocol
echo 4 > functions/hid.GS1/report_length
echo -ne \\x5\\x1\\x9\\x2\\xa1\\x1\\x9\\x1\\xa1\\x0\\x5\\x9\\x19\\x1\\x29\\x3\\x15\\x0\\x25\\x1\\x95\\x3\\x75\\x1\\x81\\x2\\x95\\x1\\x75\\x5\\x81\\x3\\x5\\x1\\x9\\x30\\x9\\x31\\x9\\x38\\x15\\x81\\x25\\x7f\\x75\\x8\\x95\\x3\\x81\\x6\\xc0\\xc0 > functions/hid.GS1/report_desc
ln -s functions/hid.GS1 configs/c.1
# touchpad
mkdir functions/hid.GS2
if [ -e /boot/BIOS ]
then
echo 1 > functions/hid.GS2/subclass
fi
if [ ! -e /boot/usb.notwakeup ]
then
echo 1 > functions/hid.GS2/wakeup_on_write
fi
echo 2 > functions/hid.GS2/protocol
echo 6 > functions/hid.GS2/report_length
echo -ne \\x05\\x01\\x09\\x02\\xa1\\x01\\x09\\x01\\xa1\\x00\\x05\\x09\\x19\\x01\\x29\\x03\\x15\\x00\\x25\\x01\\x95\\x03\\x75\\x01\\x81\\x02\\x95\\x01\\x75\\x05\\x81\\x01\\x05\\x01\\x09\\x30\\x09\\x31\\x15\\x00\\x26\\xff\\x7f\\x35\\x00\\x46\\xff\\x7f\\x75\\x10\\x95\\x02\\x81\\x02\\x05\\x01\\x09\\x38\\x15\\x81\\x25\\x7f\\x35\\x00\\x45\\x00\\x75\\x08\\x95\\x01\\x81\\x06\\xc0\\xc0 > functions/hid.GS2/report_desc
ln -s functions/hid.GS2 configs/c.1
fi
if [ -e /boot/usb.disk0 ]
then
mkdir functions/mass_storage.disk0
ln -s functions/mass_storage.disk0 configs/c.1/
echo 1 > functions/mass_storage.disk0/lun.0/removable
if [ -e /boot/usb.disk0.ro ]
then
echo 1 > functions/mass_storage.disk0/lun.0/ro
echo 0 > functions/mass_storage.disk0/lun.0/cdrom
fi
echo "NanoKVM USB Mass Storage0520" > functions/mass_storage.disk0/lun.0/inquiry_string
disk=$(cat /boot/usb.disk0)
if [ -z "${disk}" ]
then
# if [ ! -e /mnt/usbdisk.img ]
# then
# fallocate -l 8G /mnt/usbdisk.img
# mkfs.vfat /mnt/usbdisk.img
# fi
echo /dev/mmcblk0p3 > functions/mass_storage.disk0/lun.0/file
else
cat /boot/usb.disk0 > functions/mass_storage.disk0/lun.0/file
fi
fi
ls /sys/class/udc/ | cat > UDC
echo device > /proc/cviusb/otg_role
}
start_usb_host(){
echo '' > /sys/kernel/config/usb_gadget/g0/UDC
echo host > /proc/cviusb/otg_role
}
restart_usb_dev(){
echo > /sys/kernel/config/usb_gadget/g0/UDC
sleep 1
ls /sys/class/udc/ | cat > /sys/kernel/config/usb_gadget/g0/UDC
echo "USB Restart OK!"
}
case "$1" in
start)
start_usb_dev
;;
restart)
restart_usb_dev
;;
stop)
start_usb_host
;;
stop_start)
start_usb_host
start_usb_dev
;;
esac

View File

@@ -0,0 +1,105 @@
#!/bin/sh
# kvmhwd hid only
start_usb_dev(){
. /etc/profile
echo "usb mode: device"
cd /sys/kernel/config/usb_gadget
mkdir g0
cd g0
echo 0x0101 > bcdUSB
echo 0x0623 > bcdDevice
# echo 0x3346 > idVendor
# echo 0x1009 > idProduct
if [ -e /boot/usb.vid ]
then
cat /boot/usb.vid > idVendor
else
echo 0x3346 > idVendor
fi
if [ -e /boot/usb.pid ]
then
cat /boot/usb.pid > idProduct
else
echo 0x1009 > idProduct
fi
mkdir strings/0x409
# echo '0' > strings/0x409/serialnumber
echo 'sipeed' > strings/0x409/manufacturer
echo 'NanoKVM' > strings/0x409/product
mkdir configs/c.1
echo 0xA0 > configs/c.1/bmAttributes
echo 200 > configs/c.1/MaxPower
mkdir configs/c.1/strings/0x409
echo "NanoKVM" > configs/c.1/strings/0x409/configuration
# keyboard
mkdir functions/hid.GS0
echo 1 > functions/hid.GS0/subclass
if [ ! -e /boot/usb.notwakeup ]
then
echo 1 > functions/hid.GS0/wakeup_on_write
fi
echo 1 > functions/hid.GS0/protocol
echo 8 > functions/hid.GS0/report_length
echo -ne \\x05\\x01\\x09\\x06\\xa1\\x01\\x05\\x07\\x19\\xe0\\x29\\xe7\\x15\\x00\\x25\\x01\\x75\\x01\\x95\\x08\\x81\\x02\\x95\\x01\\x75\\x08\\x81\\x03\\x95\\x05\\x75\\x01\\x05\\x08\\x19\\x01\\x29\\x05\\x91\\x02\\x95\\x01\\x75\\x03\\x91\\x03\\x95\\x06\\x75\\x08\\x15\\x00\\x25\\x65\\x05\\x07\\x19\\x00\\x29\\x65\\x81\\x00\\xc0 > functions/hid.GS0/report_desc
ln -s functions/hid.GS0 configs/c.1
# mouse
mkdir functions/hid.GS1
echo 1 > functions/hid.GS1/subclass
if [ ! -e /boot/usb.notwakeup ]
then
echo 1 > functions/hid.GS1/wakeup_on_write
fi
echo 2 > functions/hid.GS1/protocol
echo 4 > functions/hid.GS1/report_length
echo -ne \\x5\\x1\\x9\\x2\\xa1\\x1\\x9\\x1\\xa1\\x0\\x5\\x9\\x19\\x1\\x29\\x3\\x15\\x0\\x25\\x1\\x95\\x3\\x75\\x1\\x81\\x2\\x95\\x1\\x75\\x5\\x81\\x3\\x5\\x1\\x9\\x30\\x9\\x31\\x9\\x38\\x15\\x81\\x25\\x7f\\x75\\x8\\x95\\x3\\x81\\x6\\xc0\\xc0 > functions/hid.GS1/report_desc
ln -s functions/hid.GS1 configs/c.1
# touchpad
mkdir functions/hid.GS2
echo 1 > functions/hid.GS2/subclass
if [ ! -e /boot/usb.notwakeup ]
then
echo 1 > functions/hid.GS2/wakeup_on_write
fi
echo 2 > functions/hid.GS2/protocol
echo 6 > functions/hid.GS2/report_length
echo -ne \\x05\\x01\\x09\\x02\\xa1\\x01\\x09\\x01\\xa1\\x00\\x05\\x09\\x19\\x01\\x29\\x03\\x15\\x00\\x25\\x01\\x95\\x03\\x75\\x01\\x81\\x02\\x95\\x01\\x75\\x05\\x81\\x01\\x05\\x01\\x09\\x30\\x09\\x31\\x15\\x00\\x26\\xff\\x7f\\x35\\x00\\x46\\xff\\x7f\\x75\\x10\\x95\\x02\\x81\\x02\\x05\\x01\\x09\\x38\\x15\\x81\\x25\\x7f\\x35\\x00\\x45\\x00\\x75\\x08\\x95\\x01\\x81\\x06\\xc0\\xc0 > functions/hid.GS2/report_desc
ln -s functions/hid.GS2 configs/c.1
ls /sys/class/udc/ | cat > UDC
echo device > /proc/cviusb/otg_role
}
start_usb_host(){
echo '' > /sys/kernel/config/usb_gadget/g0/UDC
echo host > /proc/cviusb/otg_role
}
restart_usb_dev(){
echo > /sys/kernel/config/usb_gadget/g0/UDC
sleep 1
ls /sys/class/udc/ | cat > /sys/kernel/config/usb_gadget/g0/UDC
echo "USB Restart OK!"
}
case "$1" in
start)
start_usb_dev
;;
restart)
restart_usb_dev
;;
stop)
start_usb_host
;;
stop_start)
start_usb_host
start_usb_dev
;;
esac

View File

@@ -0,0 +1,234 @@
#!/bin/sh
# kvmhwd Rev2.4
Alpha_OLED_RST_Pin=371
Beta_OLED_RST_Pin=502
Beta_OLED_SCL=595
Beta_OLED_SDA=507
WiFi_EN_Pin=506
Alpha_PWR_LED_Pin=504
Alpha_HDD_LED_Pin=505
Alpha_PWR_KEY_Pin=503
Alpha_RST_KEY_Pin=507
Beta_PWR_LED_Pin=504
Beta_PWR_KEY_Pin=503
Beta_RST_KEY_Pin=505
PCIe_HDMI_RST_Pin=451
init_alpha_hw(){
devmem 0x030010D0 32 0x2 # I2C1_SCL
devmem 0x030010DC 32 0x2 # I2C1_SDA
devmem 0x030010D4 32 0x3 # OLED_RST
devmem 0x0300103C 32 0x3 # GPIOA15
devmem 0x03001050 32 0x3 # GPIOA22
devmem 0x0300105C 32 0x3 # GPIOA23
devmem 0x03001060 32 0x3 # GPIOA24
devmem 0x03001054 32 0x3 # GPIOA25
devmem 0x03001058 32 0x3 # GPIOA27
devmem 0x03001068 32 0x6 # GPIOA 18 UART1 RX
devmem 0x03001064 32 0x6 # GPIOA 19 UART1 TX
devmem 0x03001070 32 0x2 # GPIOA 28 UART2 TX
devmem 0x03001074 32 0x2 # GPIOA 29 UART2 RX
echo ${Alpha_OLED_RST_Pin} > /sys/class/gpio/export # OLED_RST
echo out > /sys/class/gpio/gpio${Alpha_OLED_RST_Pin}/direction
echo 1 > /sys/class/gpio/gpio${Alpha_OLED_RST_Pin}/value
echo ${Alpha_PWR_LED_Pin} > /sys/class/gpio/export # pwr led
echo ${Alpha_HDD_LED_Pin} > /sys/class/gpio/export # hdd led
echo ${Alpha_PWR_KEY_Pin} > /sys/class/gpio/export # pwr key
echo ${Alpha_RST_KEY_Pin} > /sys/class/gpio/export # rst key
echo in > /sys/class/gpio/gpio${Alpha_PWR_LED_Pin}/direction # pwr led
echo in > /sys/class/gpio/gpio${Alpha_HDD_LED_Pin}/direction # hdd led
echo out > /sys/class/gpio/gpio${Alpha_PWR_KEY_Pin}/direction # pwr key
echo out > /sys/class/gpio/gpio${Alpha_RST_KEY_Pin}/direction # rst key
rmmod /mnt/system/ko/i2c-gpio.ko
rmmod /mnt/system/ko/i2c-algo-bit.ko
# rm /etc/init.d/S25wifimod
# rm /etc/init.d/S30wifi
}
init_beta_pcie_hw(){
devmem 0x0300103C 32 0x3 # GPIOA15
devmem 0x03001050 32 0x3 # GPIOA22
devmem 0x0300105C 32 0x3 # GPIOA23
devmem 0x03001060 32 0x3 # GPIOA24
devmem 0x03001054 32 0x3 # GPIOA25
devmem 0x03001058 32 0x3 # GPIOA27
devmem 0x030010E4 32 0x0 # SDIO CLK
devmem 0x030010E0 32 0x0 # SDIO CMD
devmem 0x030010DC 32 0x0 # SDIO D0
devmem 0x030010D8 32 0x0 # SDIO D1
devmem 0x030010D4 32 0x0 # SDIO D2
devmem 0x030010D0 32 0x0 # SDIO D3
devmem 0x03001068 32 0x6 # GPIOA 18 UART1 RX
devmem 0x03001064 32 0x6 # GPIOA 19 UART1 TX
devmem 0x03001070 32 0x2 # GPIOA 28 UART2 TX
devmem 0x03001074 32 0x2 # GPIOA 29 UART2 RX
echo ${Beta_OLED_RST_Pin} > /sys/class/gpio/export # Beta OLED_RST
echo out > /sys/class/gpio/gpio${Beta_OLED_RST_Pin}/direction
echo 1 > /sys/class/gpio/gpio${Beta_OLED_RST_Pin}/value
echo ${Beta_PWR_LED_Pin} > /sys/class/gpio/export # pwr led
echo ${Beta_PWR_KEY_Pin} > /sys/class/gpio/export # pwr key
echo ${Beta_RST_KEY_Pin} > /sys/class/gpio/export # rst key
echo ${PCIe_HDMI_RST_Pin} > /sys/class/gpio/export # hdmi rst key
echo in > /sys/class/gpio/gpio${Beta_PWR_LED_Pin}/direction # pwr led
echo out > /sys/class/gpio/gpio${Beta_PWR_KEY_Pin}/direction # pwr key
echo out > /sys/class/gpio/gpio${Beta_RST_KEY_Pin}/direction # rst key
echo out > /sys/class/gpio/gpio${PCIe_HDMI_RST_Pin}/direction # rst key
echo 1 > /sys/class/gpio/gpio${PCIe_HDMI_RST_Pin}/value # rst key
rmmod /mnt/system/ko/i2c-gpio.ko
rmmod /mnt/system/ko/i2c-algo-bit.ko
insmod /mnt/system/ko/i2c-algo-bit.ko
insmod /mnt/system/ko/i2c-gpio.ko
}
kvm_hw_detect(){
if [ ! -e /etc/kvm/hdmi_version ]
then
rm /etc/kvm/hw
fi
if [ -e /etc/kvm/hw ]
then
echo "/etc/kvm/hw exist"
else
echo "/etc/kvm/hw not exist"
if [ -d "/etc/kvm/" ]
then
echo "/etc/kvm/ exist"
else
mkdir /etc/kvm/
fi
devmem 0x0300104C 32 0x3 # GPIOA26 / WiFi_EN
echo ${WiFi_EN_Pin} > /sys/class/gpio/export # WiFi_EN
echo out > /sys/class/gpio/gpio${WiFi_EN_Pin}/direction
echo 0 > /sys/class/gpio/gpio${WiFi_EN_Pin}/value
devmem 0x0300103C 32 0x3 # GPIOA15
devmem 0x03001050 32 0x3 # GPIOA22
devmem 0x0300105C 32 0x3 # GPIOA23
devmem 0x03001060 32 0x3 # GPIOA24
devmem 0x03001054 32 0x3 # GPIOA25
devmem 0x03001058 32 0x3 # GPIOA27
devmem 0x030010D0 32 0x2 # I2C1_SCL
devmem 0x030010DC 32 0x2 # I2C1_SDA
devmem 0x030010D4 32 0x3 # OLED_RST
echo ${Alpha_OLED_RST_Pin} > /sys/class/gpio/export # OLED_RST
echo out > /sys/class/gpio/gpio${Alpha_OLED_RST_Pin}/direction
echo 1 > /sys/class/gpio/gpio${Alpha_OLED_RST_Pin}/value
kvm_tmp=$(i2cdetect -ry 1 0x3d 0x3d | grep 3d)
if [ -n "$kvm_tmp" ]
then
# alpha hw
echo "alpha" > /etc/kvm/hw
else
# beta/pcie hw
echo ${Alpha_OLED_RST_Pin} > /sys/class/gpio/unexport # OLED_RST
echo ${Beta_OLED_RST_Pin} > /sys/class/gpio/export # Beta_OLED_RST_Pin
echo out > /sys/class/gpio/gpio${Beta_OLED_RST_Pin}/direction
echo 1 > /sys/class/gpio/gpio${Beta_OLED_RST_Pin}/value
rmmod /mnt/system/ko/i2c-gpio.ko
rmmod /mnt/system/ko/i2c-algo-bit.ko
insmod /mnt/system/ko/i2c-algo-bit.ko
insmod /mnt/system/ko/i2c-gpio.ko
kvm_tmp=$(i2cdetect -ry 4 0x2c 0x2c | grep 2c)
if [ -n "$kvm_tmp" ]
then
echo "c" > /etc/kvm/hdmi_version
else
kvm_tmp1=$(i2cdetect -ry 4 0x2b 0x2b | grep 2b)
if [ -n "$kvm_tmp1" ]
then
echo "ux" > /etc/kvm/hdmi_version
else
echo "ue" > /etc/kvm/hdmi_version
fi
fi
kvm_tmp=$(i2cdetect -ry 5 0x3c 0x3c | grep 3c)
if [ -n "$kvm_tmp" ]
then
echo "pcie" > /etc/kvm/hw
sync
reboot
else
echo "beta" > /etc/kvm/hw
# rm /etc/init.d/S25wifimod
# rm /etc/init.d/S30wifi
sync
fi
echo 1 > /sys/class/gpio/gpio${WiFi_EN_Pin}/value
echo ${WiFi_EN_Pin} > /sys/class/gpio/unexport # WiFi_EN
fi
fi
sync
}
kvm_hw_init(){
FIND_FILE="/etc/kvm/hw"
if [ `grep -c "alpha" $FIND_FILE` -ne '0' ]
then
echo "hw = alpha!"
init_alpha_hw
fi
if [ `grep -c "beta" $FIND_FILE` -ne '0' ]
then
echo "hw = beta!"
init_beta_pcie_hw
fi
if [ `grep -c "pcie" $FIND_FILE` -ne '0' ]
then
echo "hw = pcie!"
init_beta_pcie_hw
fi
}
kvm_hdmi_version_detect(){
hdmi_tmp=$(i2cdetect -ry 4 0x2c 0x2c | grep 2c)
if [ -n "$hdmi_tmp" ]
then
echo "c" > /etc/kvm/hdmi_version
else
hdmi_tmp1=$(i2cdetect -ry 4 0x2b 0x2b | grep 2b)
if [ -n "$hdmi_tmp1" ]
then
echo "ux" > /etc/kvm/hdmi_version
else
echo "ue" > /etc/kvm/hdmi_version
fi
fi
}
case "$1" in
start)
kvm_hw_detect
kvm_hw_init
;;
re-detect)
rm /etc/kvm/hw
kvm_hw_detect
kvm_hw_init
;;
re-init)
kvm_hw_init
;;
get_hdmi_version)
kvm_hdmi_version_detect
;;
esac

View File

@@ -0,0 +1,67 @@
#!/bin/sh
RESERVE_INET="192.168.90.1/22"
clean_line() {
echo "$1" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//;s/\r//g'
}
calc_gw() {
addr="$1"
netid="$2"
IFS=. read a b c d <<EOF
$addr
EOF
ipnum=$(( (a<<24) + (b<<16) + (c<<8) + d ))
mask=$(( 0xFFFFFFFF << (32-netid) & 0xFFFFFFFF ))
gwnum=$(( (ipnum & mask) | 1 ))
echo "$(( (gwnum>>24)&255 )).$(( (gwnum>>16)&255 )).$(( (gwnum>>8)&255 )).$(( gwnum&255 ))"
}
start() {
if [ -e /boot/eth.nodhcp ]; then
while IFS= read -r line || [ -n "$line" ]; do
line=$(clean_line "$line")
[ -z "$line" ] && continue
set -- $line
inet="$1"
gw="$2"
[ -z "$inet" ] && continue
addr=${inet%/*}
netid=${inet#*/}
[ -z "$gw" ] && gw=$(calc_gw "$addr" "$netid")
arping -Dqc2 -Ieth0 "$addr" || continue
ip a add "$inet" brd + dev eth0
ip r add default via "$gw" dev eth0
echo -e "nameserver $gw" >> /etc/resolv.conf
break
done < /boot/eth.nodhcp
ip a show dev eth0 | grep inet > /dev/null || {
udhcpc -i eth0 -t 3 -T 1 -A 5 -b -p /run/udhcpc.eth0.pid &>/dev/null
ip a show dev eth0 | grep inet > /dev/null
} || {
inet=$RESERVE_INET
addr=${inet%/*}
ip a add "$inet" brd + dev eth0
} || exit 1
else
udhcpc -i eth0 -t 10 -T 1 -A 5 -b -p /run/udhcpc.eth0.pid &
fi
}
stop() {
[ ! -e "/run/udhcpc.eth0.pid" ] && exit 1
kill "$(cat /run/udhcpc.eth0.pid)"
rm /run/udhcpc.eth0.pid
}
case "$1" in
start) start ;;
stop) stop ;;
restart|reload)
$0 stop
$0 start
;;
*) exit 1 ;;
esac

View File

@@ -0,0 +1,175 @@
#!/bin/sh
. /etc/profile
gen_hostapd_conf() {
ssid="${1}"
pass="${2}"
echo "ctrl_interface=/var/run/hostapd"
echo "ctrl_interface_group=0"
echo "ssid=${ssid}"
echo "hw_mode=g"
echo "channel=1"
echo "beacon_int=100"
echo "dtim_period=2"
echo "max_num_sta=255"
echo "rts_threshold=-1"
echo "fragm_threshold=-1"
echo "macaddr_acl=0"
echo "auth_algs=3"
echo "wpa=2"
echo "wpa_passphrase=${pass}"
echo "ieee80211n=1"
}
gen_udhcpd_conf() {
interface=${1}
ipv4_prefix=${2}
echo "start ${ipv4_prefix}.100"
echo "end ${ipv4_prefix}.200"
echo "interface ${interface}"
echo "pidfile /var/run/udhcpd.${interface}.pid"
echo "lease_file /var/lib/misc/udhcpd.${interface}.leases"
echo "option subnet 255.255.255.0"
echo "option lease 864000"
}
gen_dnsmasq_conf() {
ipv4_prefix=${1}
echo "bind-interfaces"
echo "interface=wlan0"
echo "address=/config.kvm/${ipv4_prefix}.1"
echo "no-hosts"
echo "dhcp-range=${ipv4_prefix}.2,${ipv4_prefix}.254"
echo "dhcp-option=6,${ipv4_prefix}.1"
echo "dhcp-option=3,${ipv4_prefix}.1"
echo "dhcp-authoritative"
}
start() {
echo "wifi mode: sta"
ssid=""
pass=""
if [ -e /boot/wifi.ssid ] && [ -e /boot/wifi.pass ]; then
echo "Updating WiFi credentials from /boot to /etc/kvm/"
rm -f /etc/kvm/wifi.ssid /etc/kvm/wifi.pass
mv /boot/wifi.ssid /etc/kvm/wifi.ssid
mv /boot/wifi.pass /etc/kvm/wifi.pass
chown root:root /etc/kvm/wifi.ssid /etc/kvm/wifi.pass
chmod 644 /etc/kvm/wifi.ssid /etc/kvm/wifi.pass
fi
if [ -e /etc/kvm/wifi.ssid ]
then
ssid=`cat /etc/kvm/wifi.ssid`
fi
if [ -e /etc/kvm/wifi.pass ]
then
pass=`cat /etc/kvm/wifi.pass`
fi
echo "ctrl_interface=/var/run/wpa_supplicant" > /etc/wpa_supplicant.conf
wpa_passphrase "$ssid" "$pass" >> /etc/wpa_supplicant.conf
wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant.conf
if [ ! -e /boot/wifi.nodhcp ]
then
(udhcpc -i wlan0 -t 10 -T 1 -A 5 -b -p /run/udhcpc.wlan0.pid) &
fi
}
ap_start() {
echo "wifi mode: ap"
id2=$(printf "%d" 0x$(sha512sum /sys/class/cvi-base/base_uid | head -c 2))
id3=$(printf "%d" 0x$(sha512sum /sys/class/cvi-base/base_uid | head -c 4 | tail -c 2))
if [ "$id2" = "$id3" ]
then
id2=$((id2 + 1))
fi
if [ "$id2" -ge 255 ]
then
id2=253
fi
if [ "$id3" -ge 255 ]
then
id3=254
fi
ssid=""
pass=""
if [ -e /kvmapp/kvm/ap.ssid ]
then
ssid=`cat /kvmapp/kvm/ap.ssid`
fi
if [ -e /kvmapp/kvm/ap.pass ]
then
pass=`cat /kvmapp/kvm/ap.pass`
fi
gen_hostapd_conf "$ssid" "$pass" > /etc/hostapd.conf
ipv4_prefix=10.$id3.$id2
if [ ! -e /etc/udhcpd.wlan0.conf ]
then
gen_udhcpd_conf wlan0 "${ipv4_prefix}" > /etc/udhcpd.wlan0.conf
fi
# gen_dnsmasq_conf "${ipv4_prefix}" > /etc/dnsmasq.conf
# iptables --policy INPUT ACCEPT
# iptables --policy FORWARD ACCEPT
# iptables --policy OUTPUT ACCEPT
# iptables -F
# iptables -t nat -F
# iptables -t nat -A PREROUTING -i wlan0 -p udp --dport 53 -j DNAT --to ${ipv4_prefix}.1
ifconfig wlan0 up
ip route del default || true
ip add flush dev wlan0
ip addr add $ipv4_prefix.1/24 dev wlan0
# dnsmasq --pid-file=/tmp/dnsmasq.run -C /etc/dnsmasq.conf
hostapd -B -i wlan0 /etc/hostapd.conf
udhcpd -S /etc/udhcpd.wlan0.conf
}
stop() {
ps -ef|grep hostapd|grep -v grep|awk '{print $1}'|xargs kill -2 || true
ps -ef|grep "udhcpd -S /etc/udhcpd.wlan0.conf" |grep -v grep|awk '{print $1}'|xargs kill -2 || true
killall wpa_supplicant || true
if [ -e /run/udhcpc.wlan0.pid ]
then
kill `cat /run/udhcpc.wlan0.pid` || true
rm -f /run/udhcpc.wlan0.pid
fi
if [ -e /var/run/udhcpd.wlan0.pid ]
then
kill `cat /var/run/udhcpd.wlan0.pid` || true
rm -f /var/run/udhcpd.wlan0.pid
fi
if [ -e /tmp/dnsmasq.run ]
then
kill `cat /tmp/dnsmasq.run` || true
rm -f /tmp/dnsmasq.run
fi
# if [ -e /etc/wpa_supplicant.conf]
# then
# echo > /etc/wpa_supplicant.conf
# fi
airmon-ng stop wlan0mon || true
}
restart() {
stop
start
}
if [ "${1}" = "start" ]
then
start
elif [ "${1}" = "stop" ]
then
stop
elif [ "${1}" = "ap" ]
then
stop
ap_start
elif [ "${1}" = "restart" ]
then
restart
fi

View File

@@ -0,0 +1,20 @@
#!/bin/sh
#
# avahi-daemon init script
DAEMON=/usr/sbin/avahi-daemon
case "$1" in
start)
$DAEMON -c || $DAEMON -D
;;
stop)
$DAEMON -c && $DAEMON -k
;;
reload)
$DAEMON -c && $DAEMON -r
;;
*)
echo "Usage: S50avahi-daemon {start|stop|reload}" >&2
exit 1
;;
esac

View File

@@ -0,0 +1,49 @@
#!/bin/sh
DAEMON=ssdpd
PIDFILE=/var/run/$DAEMON.pid
CFGFILE=/etc/default/$DAEMON
DAEMON_ARGS=""
# Read configuration variable file if it is present
# shellcheck source=/dev/null
[ -r "$CFGFILE" ] && . "$CFGFILE"
# shellcheck disable=SC2086
start() {
printf 'Starting %s: ' "$DAEMON"
if start-stop-daemon -S -q -p "$PIDFILE" -x "$DAEMON" -- $DAEMON_ARGS; then
echo "OK"
else
echo "FAIL"
fi
}
stop() {
printf 'Stopping %s: ' "$DAEMON"
if start-stop-daemon -K -q -p "$PIDFILE" -x "$DAEMON"; then
echo "OK"
else
echo "FAIL"
fi
}
restart() {
stop
start
}
case "$1" in
start|stop|restart)
"$1"
;;
reload)
restart
;;
*)
echo "Usage: $0 {start|stop|restart|reload}"
exit 1
esac
exit $?

View File

@@ -0,0 +1,73 @@
#!/bin/sh
#
# sshd Starts sshd.
#
# Ensure required binaries exist
[ -x /usr/bin/ssh-keygen ] || exit 0
[ -x /usr/sbin/sshd ] || exit 1
PIDFILE="/var/run/sshd.pid"
umask 077
startssh() {
# Generate SSH keys if they do not exist
[ ! -f /etc/ssh/ssh_host_rsa_key ] && /usr/bin/ssh-keygen -A
printf "Starting sshd: "
/usr/sbin/sshd
touch /var/lock/sshd
echo "OK"
}
start() {
if [ -e /etc/kvm/ssh_stop ]; then
if [ -e /boot/start_ssh_once ]; then
rm -f /boot/start_ssh_once
startssh
else
echo "SSH does not start"
exit 0
fi
else
startssh
fi
}
stop() {
printf "Stopping sshd: "
killall sshd 2>/dev/null
rm -f /var/lock/sshd
echo "OK"
}
restart() {
stop
start
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart|reload)
restart
;;
permanent_on)
rm -f /etc/kvm/ssh_stop
start
;;
permanent_off)
touch /etc/kvm/ssh_stop
stop
;;
*)
echo "Usage: $0 {start|stop|restart|permanent_on|permanent_off}"
exit 1
esac
exit 0

View File

@@ -0,0 +1,29 @@
#!/bin/sh
DAEMON="dnsmasq"
PIDFILE="/var/run/$DAEMON.pid"
[ -f /etc/dnsmasq.conf ] || exit 0
case "$1" in
start)
printf "Starting dnsmasq: "
start-stop-daemon -S -p "$PIDFILE" -x "/usr/sbin/$DAEMON" -- \
--pid-file="$PIDFILE"
[ $? = 0 ] && echo "OK" || echo "FAIL"
;;
stop)
printf "Stopping dnsmasq: "
start-stop-daemon -K -q -p "$PIDFILE" -x "/usr/sbin/$DAEMON"
[ $? = 0 ] && echo "OK" || echo "FAIL"
;;
restart|reload)
$0 stop
$0 start
;;
*)
echo "Usage: $0 {start|stop|restart}"
exit 1
esac
exit 0

View File

@@ -0,0 +1,69 @@
#!/bin/sh
# nanokvm Rev3.1
case "$1" in
start)
echo -n kvm > /boot/hostname.prefix
# Copy sensor config if the file exists
[ -f /mnt/data/sensor_cfg.ini.LT ] && cp /mnt/data/sensor_cfg.ini.LT /mnt/data/sensor_cfg.ini
# Generate unique device key
if [ -f /sys/class/cvi-base/base_uid ]; then
str_value=$(awk '{print $2}' /sys/class/cvi-base/base_uid)
first_uint=$(echo "$str_value" | cut -d'_' -f1)
second_uint=$(echo "$str_value" | cut -d'_' -f2)
echo "$first_uint$second_uint" > /device_key
fi
# Set iptables rules (skip if already present)
iptables -C INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT 2>/dev/null || \
iptables -A INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -C OUTPUT -o eth0 -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT 2>/dev/null || \
iptables -A OUTPUT -o eth0 -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT
iptables -C INPUT -i eth0 -p tcp --sport 22 -m state --state NEW,ESTABLISHED -j ACCEPT 2>/dev/null || \
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -C OUTPUT -o eth0 -p tcp --dport 22 -m state --state ESTABLISHED -j ACCEPT 2>/dev/null || \
iptables -A OUTPUT -o eth0 -p tcp --dport 22 -m state --state ESTABLISHED -j ACCEPT
iptables -C OUTPUT -o eth0 -p tcp --sport 8000 -m state --state ESTABLISHED -j DROP 2>/dev/null || \
iptables -A OUTPUT -o eth0 -p tcp --sport 8000 -m state --state ESTABLISHED -j DROP
# Start services
cp -r /kvmapp/kvm_system /tmp/
/tmp/kvm_system/kvm_system &
cp -r /kvmapp/server /tmp/
/tmp/server/NanoKVM-Server &
;;
stop)
killall kvm_system
killall NanoKVM-Server
rm -r /tmp/kvm_system /tmp/server
echo "OK"
;;
restart)
killall kvm_system
killall NanoKVM-Server
rm -r /tmp/kvm_system /tmp/server
cp -r /kvmapp/kvm_system /tmp/
/tmp/kvm_system/kvm_system &
cp -r /kvmapp/server /tmp/
/tmp/server/NanoKVM-Server &
sync
echo "OK"
;;
*)
echo "Usage: $0 {start|stop|restart}"
exit 1
;;
esac

View File

@@ -0,0 +1,120 @@
#!/bin/sh
DAEMON="tailscaled"
PIDFILE="/var/run/$DAEMON.pid"
# Set the port to listen on for incoming VPN packets.
# Remote nodes will automatically be informed about the new port number,
# but you might want to configure this in order to set external firewall
# settings.
PORT="41641"
# Extra flags you might want to pass to tailscaled.
FLAGS=""
# You need tailscaled at /usr/sbin to server, and tailscale at /usr/bin to operate
# STATIC version needed. Download page at https://pkgs.tailscale.com/stable/#static
PKG_URL_LATEST="https://pkgs.tailscale.com/stable/tailscale_latest_riscv64.tgz"
[ ! -x /usr/sbin/$DAEMON ] &&
echo "/usr/sbin/$DAEMON not found, please download it from $PKG_URL_LATEST" &&
echo "Then unpack it, copy $DAEMON to /usr/sbin and copy tailscale to /usr/bin" &&
exit 1
VERSION=$(/usr/sbin/$DAEMON --version|sed -n '1p'|xargs echo -n)
[ -x /usr/bin/tailscale ] || echo "/usr/bin/tailscale not found, your installation of tailscale may be broken"
# just for those need forwarding
[ ! -f /etc/sysctl.d/99-tailscale.conf ] &&
mkdir -p /etc/sysctl.d/ &&
echo "missing /etc/sysctl.d/99-tailscale.conf, try make it below:" &&
(tee /etc/sysctl.d/99-tailscale.conf <<EOF
net.ipv4.ip_forward = 1
net.ipv6.conf.all.forwarding = 1
EOF
) &&
echo "if this message repeats showing, please look at $0 if you need forwarding"
case "$1" in
start)
if [ -f /etc/kvm/GOMEMLIMIT ]; then
value=$(cat /etc/kvm/GOMEMLIMIT)
export GOMEMLIMIT="${value}MiB"
else
export GOMEMLIMIT=1024MiB
fi
echo "GOMEMLIMIT set to ${GOMEMLIMIT}"
printf "Starting $DAEMON[$VERSION]: "
start-stop-daemon -S -bmq -p "$PIDFILE" -x "/usr/sbin/$DAEMON" -- \
--state=/var/lib/tailscale/tailscaled.state \
--socket=/var/run/tailscale/tailscaled.sock \
--port=${PORT} \
$FLAGS
if [ $? = 0 ]; then
echo "OK"
tailscale set --accept-dns=false
# example to make your nanoKVM an exit node
# tailscale set --advertise-exit-node --advertise-routes=192.168.0.0/16
else
echo "FAIL"
fi
;;
stop)
printf "Stopping $DAEMON: "
start-stop-daemon -K -p "$PIDFILE"
[ $? = 0 ] && (echo "OK"; rm -f "$PIDFILE") || echo "FAIL"
printf "cleaning tailscaled: "
/usr/sbin/$DAEMON --cleanup &>/dev/null
[ $? = 0 ] && echo "OK" || echo "FAIL"
;;
restart|reload)
$0 stop
$0 start
;;
doc)
cat <<EOF
To use tailscale, you need to meet these conditions below:
1. Both tailscale and tailscaled were installed.
2. At least one tailscale's account were registered.
(https://login.tailscale.com/start)
3. Your NanoKVM device must keep online.
Then, follow the steps below:
1. Login in https://login.tailscale.com on your PC
to enter into yout admin console.
2. Run 'tailscale login' on your device, and copy the link showed
to open on your PC, and confirm the auth.
3. Congratulations, your NanoKVM device is now on the tailnet, try to
visit it from all your device which on the same tailnet.
4. run 'tailscale set --webclient' and manage your device
on the web interface from localnet and tailenet.
Added: no more action to be repeat after your device reboot.
EOF
echo ""
cat <<EOF
为了正常使用 tailscale, 你需要满足以下几个条件:
1. tailscale 和 tailscaled 这两个静态链接的二进制程序
都已经正确安装在系统上。
2. 至少注册一个 tailscale 的帐号才能使用其服务。
(https://login.tailscale.com/start)
3. 你的 NanoKVM 设备必须保持在线。
然后,跟着以下步骤操作:
1. 在你的电脑上登录 https://login.tailscale.com 以进入控制台。
2. 在你的 NanoKVM ssh 终端上执行 'tailscale login', 然后复制
出现的链接到浏览器上,登录并通过验证。
3. 祝贺,你的 NanoKVM 现在已经加入了 tailnet 然后你可以从任意
同样已加入同一 tailnet 的设备去访问你的 NanoKVM。
4. 执行 'tailscale set --webclient' 然后你就可以从 '局域网' 和
'tailnet' 来访问特定网页,用来管理你的设备。
补充: 不需要重复上面的操作,哪怕你的设备重启过。
EOF
;;
*)
echo "Usage: $0 {start|stop|restart}"
exit 1
esac
exit 0

Binary file not shown.

View File

@@ -0,0 +1,96 @@
import os
import shutil
import time
import zipfile
import pathlib
import requests
temporary: str = "/root/.kvm-cache/"
def mkdir() -> None:
if pathlib.Path(temporary).exists():
shutil.rmtree(temporary)
pathlib.Path(temporary).mkdir()
print(f"Created temporary directory {temporary}")
def read(file: str) -> str:
return pathlib.Path(file).read_text().replace("\n", "")
def download_firmware() -> None:
print("Downloading firmware...")
now = int(time.time())
url = f"https://cdn.sipeed.com/nanokvm/latest.zip?n={now}"
print(f"Downloading firmware from {url}")
response = requests.get(url)
if response.status_code != 200:
raise Exception(f"Failed to download firmware, status: {response.status_code}")
content_type = response.headers.get("content-type")
if content_type != "application/zip":
raise Exception(f"Failed to download firmware, content_type: {content_type}")
zip_file = f"{temporary}/latest.zip"
with open(zip_file, "wb") as f:
for chunk in response.iter_content(chunk_size=1024):
f.write(chunk)
with zipfile.ZipFile(zip_file, "r") as f:
f.extractall(temporary)
print("Completed downloading firmware.")
def update() -> None:
backup_dir = pathlib.Path("/root/old")
firmware_dir = pathlib.Path("/kvmapp")
if backup_dir.exists():
shutil.rmtree(backup_dir)
if firmware_dir.exists():
firmware_dir.rename(backup_dir)
pathlib.Path(f"{temporary}/latest").rename(firmware_dir)
def change_permissions() -> None:
for root, dirs, files in os.walk("/kvmapp"):
os.chmod(root, 0o755)
for file in files:
file_path = os.path.join(root, file)
os.chmod(file_path, 0o755)
print("change permissions done")
def main() -> None:
try:
print("Stopping nanokvm service...")
os.system("/etc/init.d/S95nanokvm stop")
print("Staring update...")
mkdir()
download_firmware()
update()
change_permissions()
version = read("/kvmapp/version")
print(f"Successfully updated to version: {version}")
print("restart service\nthe nanokvm will reboot")
except Exception as e:
print(f"update failed\n{e}")
finally:
shutil.rmtree(temporary)
os.system("/etc/init.d/S95nanokvm restart")
if __name__ == "__main__":
main()

99
server/README.md Normal file
View File

@@ -0,0 +1,99 @@
# NanoKVM Server
This is the backend server implementation for NanoKVM.
For detailed documentation, please visit our [Wiki](https://wiki.sipeed.com/nanokvm).
## Structure
```shell
server
├── common // Common utility components
├── config // Server configuration
├── dl_lib // Shared object libraries
├── include // Header files for shared objects
├── logger // Logging system
├── middleware // Server middleware components
├── proto // API request/response definitions
├── router // API route handlers
├── service // Core service implementations
├── utils // Utility functions
└── main.go
```
## Configuration
The configuration file path is `/etc/kvm/server.yaml`.
```yaml
proto: http
port:
http: 80
https: 443
cert:
crt: server.crt
key: server.key
# Log level (debug/info/warn/error)
# Note: Use 'info' or 'error' in production, 'debug' only for development
logger:
level: info
file: stdout
# Authentication setting (enable/disable)
# Note: Only disable authentication in development environment
authentication: enable
jwt:
# JWT secret key. If left empty, a random 64-byte key will be generated automatically.
secretKey: ""
# JWT token expiration time in seconds. Default: 2678400 (31 days)
refreshTokenDuration: 2678400
# Invalidate all JWT tokens when the user logs out. Default: true
revokeTokensOnLogout: true
# Address for custom STUN server
# Note: You can disable the STUN service by setting it to 'disable' (e.g., in a LAN environment)
stun: stun.l.google.com:19302
# Address and authentication for custom TURN server
turn:
turnAddr: example_addr
turnUser: example_user
turnCred: example_cred
```
## Compile & Deploy
Note: Use Linux operating system (x86-64). This build process is not compatible with ARM, Windows or macOS.
1. Install the Toolchain
1. Download the toolchain from the following link: [Download Link](https://sophon-file.sophon.cn/sophon-prod-s3/drive/23/03/07/16/host-tools.tar.gz).
2. Extract the file and add the `host-tools/gcc/riscv64-linux-musl-x86_64/bin` directory to your PATH environment variable.
3. Run `riscv64-unknown-linux-musl-gcc -v`. If there is version information in the output, the installation is successful.
2. Compile the Project
1. Run `cd server` from the project root directory.
2. Run `go mod tidy` to install Go dependencies.
3. (Optional) If you compiled `libkvm.so` yourself, you need to modify its RPATH by `patchelf --add-rpath \$ORIGIN ./dl_lib/libkvm.so`.
4. Run `CGO_ENABLED=1 GOOS=linux GOARCH=riscv64 CC=riscv64-unknown-linux-musl-gcc CGO_CFLAGS="-mcpu=c906fdv -march=rv64imafdcv0p7xthead -mcmodel=medany -mabi=lp64d" go build` to compile the project.
5. After compilation, an executable file named `NanoKVM-Server` will be generated.
3. Modify RPATH
1. Run `sudo apt install patchelf` or `pip install patchelf` to install patchelf.
2. Run `patchelf --version`. Ensure the version is 0.14 or higher`.
3. Run `patchelf --add-rpath \$ORIGIN/dl_lib NanoKVM-Server` to modify the RPATH of the executable file.
4. Deploy the Application
1. File uploads requires SSH. Please enable it in the Web Settings: `Settings > SSH`;
2. Replace the original file in the NanoKVM `/kvmapp/server/` directory with the newly compiled `NanoKVM-Server`.
3. Restart the service on NanoKVM by executing `/etc/init.d/S95nanokvm restart`.
## Manually Update
> File uploads requires SSH. Please enable it in the Web Settings: `Settings > SSH`;
1. Download the latest application from [GitHub](https://github.com/sipeed/NanoKVM/releases);
2. Unzip the downloaded file and rename the unzipped folder to `kvmapp`;
3. Back up the existing `/kvmapp` directory on your NanoKVM, then replace it with the new `kvmapp` folder;
4. Run `/etc/init.d/S95nanokvm restart` on your NanoKVM to restart the service.

97
server/README_JA.md Normal file
View File

@@ -0,0 +1,97 @@
# NanoKVM サーバー
これは NanoKVM のバックエンドサーバーの実装です。
詳細なドキュメントについては、[Wiki](https://wiki.sipeed.com/nanokvm) を参照してください。
## 構造
```shell
server
├── common // 共通ユーティリティコンポーネント
├── config // サーバー設定
├── dl_lib // 共有オブジェクトライブラリ
├── include // 共有オブジェクトのヘッダーファイル
├── logger // ロギングシステム
├── middleware // サーバーミドルウェアコンポーネント
├── proto // API リクエスト/レスポンス定義
├── router // API ルートハンドラ
├── service // コアサービスの実装
├── utils // ユーティリティ関数
└── main.go
```
## 設定
設定ファイルのパスは `/etc/kvm/server.yaml` です。
```yaml
proto: http
port:
http: 80
https: 443
cert:
crt: server.crt
key: server.key
# ログレベル (debug/info/warn/error)
# 注意: 本番環境では 'info' または 'error' を使用し、'debug' は開発環境でのみ使用してください
logger:
level: info
file: stdout
# 認証設定 (enable/disable)
# 注意: 認証を無効にするのは開発環境でのみ行ってください
authentication: enable
jwt:
# JWT 秘密鍵の設定。 空のままにすると、サーバー起動時にランダムな 64 バイトの鍵が自動的に生成されます。
secretKey: ""
# JWT トークンの有効期限(秒単位)。 デフォルト: 2678400 (31 日)
refreshTokenDuration: 2678400
# ユーザーがログアウトすると、すべての JWT トークンが無効になります。 デフォルト: true
revokeTokensOnLogout: true
# カスタム STUN サーバーのアドレス
stun: stun.l.google.com:19302
# カスタム TURN サーバーのアドレスと認証情報
turn:
turnAddr: turn.cloudflare.com:3478
turnUser: example_user
turnCred: example_cred
```
## コンパイルとデプロイ
注意: Linux オペレーティングシステム (x86-64) を使用してください。このビルドプロセスは ARM、Windows、macOS では互換性がありません。
1. ツールチェーンのインストール
1. 以下のリンクからツールチェーンをダウンロードします: [ダウンロードリンク](https://sophon-file.sophon.cn/sophon-prod-s3/drive/23/03/07/16/host-tools.tar.gz)。
2. ファイルを解凍し、`host-tools/gcc/riscv64-linux-musl-x86_64/bin` ディレクトリを PATH 環境変数に追加します。
3. `riscv64-unknown-linux-musl-gcc -v` を実行します。バージョン情報が表示されれば、インストールは成功です。
2. プロジェクトのコンパイル
1. プロジェクトのルートディレクトリから `cd server` を実行します。
2. `go mod tidy` を実行して Go の依存関係をインストールします。
3. `CGO_ENABLED=1 GOOS=linux GOARCH=riscv64 CC=riscv64-unknown-linux-musl-gcc CGO_CFLAGS="-mcpu=c906fdv -march=rv64imafdcv0p7xthead -mcmodel=medany -mabi=lp64d" go build` を実行してプロジェクトをコンパイルします。
4. コンパイルが完了すると、`NanoKVM-Server` という名前の実行ファイルが生成されます。
3. RPATH の変更
1. `sudo apt install patchelf` または `pip install patchelf` を実行して patchelf をインストールします。
2. `patchelf --version` を実行します。バージョンが 0.14 以上であることを確認します。
3. `patchelf --add-rpath \$ORIGIN/dl_lib NanoKVM-Server` を実行して、実行ファイルの RPATH を変更します。
4. アプリケーションのデプロイ
1. デプロイ前に、ブラウザでアプリケーションを最新バージョンに更新します。手順は[こちら](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/system/updating.html)を参照してください。
2. コンパイルして生成された `NanoKVM-Server` ファイルを使用して、NanoKVM の `/kvmapp/server/` ディレクトリ内の元のファイルを置き換えます。
3. NanoKVM で `/etc/init.d/S95nanokvm restart` を実行してサービスを再起動します。
## 手動更新
> ファイルのアップロードには SSH が必要です。Web 設定で有効にしてください: `設定 > SSH`
1. [GitHub](https://github.com/sipeed/NanoKVM/releases) から最新のアプリケーションをダウンロードします。
2. ダウンロードしたファイルを解凍し、解凍したフォルダーの名前を `kvmapp` に変更します。
3. NanoKVM 上の既存の `/kvmapp` ディレクトリをバックアップし、新しい `kvmapp` フォルダーに置き換えます。
4. NanoKVM で `/etc/init.d/S95nanokvm restart` を実行してサービスを再起動します。

96
server/README_ZH.md Normal file
View File

@@ -0,0 +1,96 @@
# NanoKVM Server
NanoKVM 后端服务的代码。更多文档请参考 [Wiki](https://wiki.sipeed.com/nanokvm) 。
## 目录结构
```shell
server
├── common // 公用组件
├── config // 服务配置
├── dl_lib // so 文件
├── include // 头文件
├── logger // 服务日志
├── middleware // 中间件
├── proto // api 请求响应参数
├── router // api 路由
├── service // api 处理逻辑
├── utils // 工具函数
└── main.go
```
## 配置文件
配置文件路径为 `/etc/kvm/server.yaml`
```yaml
proto: http
port:
http: 80
https: 443
cert:
crt: server.crt
key: server.key
# 日志级别debug/info/warn/error
# 注意:在生产环境中使用 info 或 error。debug 模式仅在开发环境中使用。
logger:
level: info
file: stdout
# 鉴权设置enable/disable
# 注意:生产环境中请勿使用 disable。
authentication: enable
jwt:
# jwt 密钥。设置为空则使用随机生成的64位密钥
secretKey: ""
# jwt token 过期时间单位默认为267840031天
refreshTokenDuration: 2678400
# 在帐号登出时是否使所有 jwt token 失效。默认为 true
revokeTokensOnLogout: true
# 自定义 STUN 服务器的地址
# 注意可以设置为“disable”来禁用 STUN 服务(例如在局域网环境中使用时)
stun: stun.l.google.com:19302
turn:
turnAddr: example_addr
turnUser: example_user
turnCred: example_cred
```
## 编译部署
**注意:请使用 Linux 操作系统x86-64。该工具链无法在 ARM、Windows 或 macOS 下使用。**
1. 安装工具链
1. 下载工具链:[下载地址](https://sophon-file.sophon.cn/sophon-prod-s3/drive/23/03/07/16/host-tools.tar.gz)
2. 解压下载文件,然后将 `host-tools/gcc/riscv64-linux-musl-x86_64/bin` 目录加入到环境变量;
3. 执行 `riscv64-unknown-linux-musl-gcc -v`,如果显示版本信息则安装成功。
2. 编译
1. 在项目根目录下执行 `cd server` 进入 server 目录;
2. 执行 `go mod tidy` 安装 Go 依赖包;
3. (可选)如果您手动编译了 `libkvm.so`,则需要通过 `patchelf --add-rpath \$ORIGIN ./dl_lib/libkvm.so` 修改其 RPATH 属性。
4. 执行 `CGO_ENABLED=1 GOOS=linux GOARCH=riscv64 CC=riscv64-unknown-linux-musl-gcc CGO_CFLAGS="-mcpu=c906fdv -march=rv64imafdcv0p7xthead -mcmodel=medany -mabi=lp64d" go build` 进行编译;
5. 编译完成后,会生成可执行文件 `NanoKVM-Server`
3. 修改 RPATH
1. 执行 `sudo apt install patchelf``pip install patchelf` 安装 patchelf
2. 执行 `patchelf --version`,确保版本大于等于 0.14
3. 执行 `patchelf --add-rpath \$ORIGIN/dl_lib NanoKVM-Server` 修改可执行文件的 RPATH 属性。
4. 部署
1. 上传文件需要启用 SSH 功能。请在 Web `设置 - SSH` 中检查 SSH 是否已经启用;
2. 使用编译生成的 `NanoKVM-Server` 文件,替换 NanoKVM 中 `/kvmapp/server/` 目录下的原始文件;
3. 在 NanoKVM 中执行 `/etc/init.d/S95nanokvm restart` 重启服务。
## 手动更新
> 请确保已经在 Web 界面的 `设置 - SSH` 中启用了 SSH 功能,以便上传文件。
1. 从 [GitHub](https://github.com/sipeed/NanoKVM/releases) 下载最新的应用安装包;
2. 解压缩下载的安装包,并将解压后的文件夹重命名为 `kvmapp`
3. 备份 NanoKVM 系统中的 `/kvmapp` 目录,然后用解压后的 `kvmapp` 文件夹替换现有目录。
4. 在 NanoKVM 中执行 `/etc/init.d/S95nanokvm restart` 重启服务。

64
server/build.sh Normal file
View File

@@ -0,0 +1,64 @@
#!/bin/bash
set -e
# Configuration Variables
BINARY_NAME="NanoKVM-Server"
CC_COMPILER="riscv64-unknown-linux-musl-gcc"
CGO_CFLAGS_OPTS="-mcpu=c906fdv -march=rv64imafdcv0p7xthead -mcmodel=medany -mabi=lp64d"
# Define colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Helper function to check if a command exists
check_dependency() {
if ! command -v "$1" &> /dev/null; then
echo -e "${RED}[ERROR] Required command '$1' not found.${NC}"
echo "Please install it or ensure it is in your PATH."
exit 1
fi
}
# ------------------------------------------------------------------------------
# Step 1: Check Prerequisites
# ------------------------------------------------------------------------------
echo -e "${YELLOW}[INFO] Checking build environment...${NC}"
check_dependency "go"
check_dependency "patchelf"
check_dependency "$CC_COMPILER"
echo -e "${GREEN}[OK] All dependencies found.${NC}"
# ------------------------------------------------------------------------------
# Step 2: Build the Binary
# ------------------------------------------------------------------------------
echo -e "${YELLOW}[INFO] Starting cross-compilation for RISC-V 64-bit (BoringCrypto enabled)...${NC}"
export CGO_ENABLED=1
export GOOS=linux
export GOARCH=riscv64
# export GOEXPERIMENT=boringcrypto
export CC="$CC_COMPILER"
export CGO_CFLAGS="$CGO_CFLAGS_OPTS"
go build -o "$BINARY_NAME" -v
if [ -f "$BINARY_NAME" ]; then
echo -e "${GREEN}[SUCCESS] Binary '$BINARY_NAME' created successfully.${NC}"
else
echo -e "${RED}[ERROR] Build failed. Binary not found.${NC}"
exit 1
fi
# ------------------------------------------------------------------------------
# Step 3: Patch RPATH
# ------------------------------------------------------------------------------
echo -e "${YELLOW}[INFO] Patching RPATH with patchelf...${NC}"
patchelf --add-rpath '$ORIGIN/dl_lib' "$BINARY_NAME"
echo -e "${GREEN}[DONE] Build script completed successfully!${NC}"

111
server/common/kvm_vision.go Normal file
View File

@@ -0,0 +1,111 @@
package common
/*
#cgo CFLAGS: -I../include
#cgo LDFLAGS: -L../dl_lib -lkvm
#include "kvm_vision.h"
*/
import "C"
import (
"sync"
"unsafe"
log "github.com/sirupsen/logrus"
)
var (
kvmVision *KvmVision
kvmVisionOnce sync.Once
)
type KvmVision struct{}
func GetKvmVision() *KvmVision {
kvmVisionOnce.Do(func() {
kvmVision = &KvmVision{}
logLevel := C.uint8_t(0)
C.kvmv_init(logLevel)
log.Debugf("kvm vision initialized")
})
return kvmVision
}
func (k *KvmVision) ReadMjpeg(width uint16, height uint16, quality uint16) (data []byte, result int) {
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))
return
}
func (k *KvmVision) ReadH264(width uint16, height uint16, bitRate uint16) (data []byte, result int) {
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))
return
}
func (k *KvmVision) SetHDMI(enable bool) int {
hdmiEnable := C.uint8_t(0)
if enable {
hdmiEnable = C.uint8_t(1)
}
result := int(C.kvmv_hdmi_control(hdmiEnable))
if result < 0 {
log.Errorf("failed to set hdmi to %t", enable)
return result
}
return result
}
func (k *KvmVision) SetGop(gop uint8) {
_gop := C.uint8_t(gop)
C.set_h264_gop(_gop)
}
func (k *KvmVision) SetFrameDetect(frame uint8) {
_frame := C.uint8_t(frame)
C.set_frame_detact(_frame)
}
func (k *KvmVision) Close() {
C.kvmv_deinit()
log.Debugf("stop kvm vision...")
}

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

@@ -0,0 +1,105 @@
package common
import "sync"
type Screen struct {
Width uint16
Height uint16
FPS int
Quality uint16
BitRate uint16
GOP uint8
}
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,
GOP: 30,
}
})
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)
case "gop":
screen.GOP = uint8(value)
}
}
func CheckScreen() {
if _, ok := ResolutionMap[screen.Height]; !ok {
screen.Width = 1920
screen.Height = 1080
}
if _, ok := QualityMap[screen.Quality]; !ok {
screen.Quality = 80
}
if _, ok := BitRateMap[screen.BitRate]; !ok {
screen.BitRate = 3000
}
}
func validateFPS(fps int) int {
if fps > 60 {
return 60
}
if fps < 10 {
return 10
}
return fps
}

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

@@ -0,0 +1,122 @@
package config
import (
"bytes"
"errors"
"log"
"os"
"sync"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
)
var (
instance Config
once sync.Once
)
func GetInstance() *Config {
once.Do(initialize)
return &instance
}
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(&instance); err != nil {
log.Fatalf("Failed to parse configuration: %s", err)
}
checkDefaultValue()
if instance.Authentication == "disable" {
log.Println("NOTICE: Authentication is disabled! Please ensure your service is secure!")
}
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()
}

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

@@ -0,0 +1,50 @@
package config
var defaultConfig = &Config{
Proto: "http",
Port: Port{
Http: 80,
Https: 443,
},
Cert: Cert{
Crt: "server.crt",
Key: "server.key",
},
Logger: Logger{
Level: "info",
File: "stdout",
},
JWT: JWT{
SecretKey: "",
RefreshTokenDuration: 2678400,
RevokeTokensOnLogout: true,
},
Stun: "stun.l.google.com:19302",
Turn: Turn{
TurnAddr: "",
TurnUser: "",
TurnCred: "",
},
Authentication: "enable",
}
func checkDefaultValue() {
if instance.JWT.SecretKey == "" {
instance.JWT.SecretKey = generateRandomSecretKey()
instance.JWT.RevokeTokensOnLogout = true
}
if instance.JWT.RefreshTokenDuration == 0 {
instance.JWT.RefreshTokenDuration = 2678400
}
if instance.Stun == "" {
instance.Stun = "stun.l.google.com:19302"
}
if instance.Authentication == "" {
instance.Authentication = "enable"
}
instance.Hardware = getHardware()
}

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

@@ -0,0 +1,45 @@
package config
import (
"os"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
)
const ConfigurationFile = "/etc/kvm/server.yaml"
func Read() (*Config, error) {
data, err := os.ReadFile(ConfigurationFile)
if err != nil {
log.Errorf("failed to read config: %v", err)
return nil, err
}
var conf Config
if err := yaml.Unmarshal(data, &conf); err != nil {
log.Fatalf("failed to unmarshal config: %v", err)
return nil, err
}
log.Debugf("read %s successfully", ConfigurationFile)
return &conf, nil
}
func Write(conf *Config) error {
data, err := yaml.Marshal(&conf)
if err != nil {
log.Errorf("failed to marshal config: %v", err)
return err
}
err = os.WriteFile(ConfigurationFile, data, 0644)
if err != nil {
log.Errorf("failed to write config: %v", err)
return err
}
log.Debugf("write to %s successfully", ConfigurationFile)
return nil
}

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

@@ -0,0 +1,95 @@
package config
import (
"os"
"strings"
log "github.com/sirupsen/logrus"
)
type HWVersion int
const (
HWVersionAlpha HWVersion = iota
HWVersionBeta
HWVersionPcie
HWVersionFile = "/etc/kvm/hw"
)
var HWAlpha = Hardware{
Version: HWVersionAlpha,
GPIOReset: "/sys/class/gpio/gpio507/value",
GPIOPower: "/sys/class/gpio/gpio503/value",
GPIOPowerLED: "/sys/class/gpio/gpio504/value",
GPIOHDDLed: "/sys/class/gpio/gpio505/value",
}
var HWBeta = Hardware{
Version: HWVersionBeta,
GPIOReset: "/sys/class/gpio/gpio505/value",
GPIOPower: "/sys/class/gpio/gpio503/value",
GPIOPowerLED: "/sys/class/gpio/gpio504/value",
GPIOHDDLed: "",
}
var HWPcie = Hardware{
Version: HWVersionPcie,
GPIOReset: "/sys/class/gpio/gpio505/value",
GPIOPower: "/sys/class/gpio/gpio503/value",
GPIOPowerLED: "/sys/class/gpio/gpio504/value",
GPIOHDDLed: "",
}
func (h HWVersion) String() string {
switch h {
case HWVersionAlpha:
return "Alpha"
case HWVersionBeta:
return "Beta"
case HWVersionPcie:
return "PCIE"
default:
return "Unknown"
}
}
func GetHwVersion() HWVersion {
content, err := os.ReadFile(HWVersionFile)
if err != nil {
return HWVersionAlpha
}
version := strings.ReplaceAll(string(content), "\n", "")
switch version {
case "alpha":
return HWVersionAlpha
case "beta":
return HWVersionBeta
case "pcie":
return HWVersionPcie
default:
return HWVersionAlpha
}
}
func getHardware() (h Hardware) {
version := GetHwVersion()
switch version {
case HWVersionAlpha:
h = HWAlpha
case HWVersionBeta:
h = HWBeta
case HWVersionPcie:
h = HWPcie
default:
h = HWAlpha
log.Errorf("Unsupported hardware version: %s", version)
}
return
}

28
server/config/jwt.go Normal file
View File

@@ -0,0 +1,28 @@
package config
import (
"crypto/rand"
"encoding/base64"
"fmt"
"time"
)
// RegenerateSecretKey regenerate secret key when logout
func RegenerateSecretKey() {
if instance.JWT.RevokeTokensOnLogout {
instance.JWT.SecretKey = generateRandomSecretKey()
}
}
// Generate random string for secret key.
func generateRandomSecretKey() 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)
}

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

@@ -0,0 +1,49 @@
package config
type Config struct {
Proto string `yaml:"proto"`
Port Port `yaml:"port"`
Cert Cert `yaml:"cert"`
Logger Logger `yaml:"logger"`
Authentication string `yaml:"authentication"`
JWT JWT `yaml:"jwt"`
Stun string `yaml:"stun"`
Turn Turn `yaml:"turn"`
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 JWT struct {
SecretKey string `yaml:"secretKey"`
RefreshTokenDuration uint64 `yaml:"refreshTokenDuration"`
RevokeTokensOnLogout bool `yaml:"revokeTokensOnLogout"`
}
type Turn struct {
TurnAddr string `yaml:"turnAddr"`
TurnUser string `yaml:"turnUser"`
TurnCred string `yaml:"turnCred"`
}
type Hardware struct {
Version HWVersion `yaml:"-"`
GPIOReset string `yaml:"-"`
GPIOPower string `yaml:"-"`
GPIOPowerLED string `yaml:"-"`
GPIOHDDLed string `yaml:"-"`
}

Binary file not shown.

BIN
server/dl_lib/libaacdec2.so Normal file

Binary file not shown.

BIN
server/dl_lib/libaacenc2.so Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
server/dl_lib/libae.so Normal file

Binary file not shown.

BIN
server/dl_lib/libaf.so Normal file

Binary file not shown.

BIN
server/dl_lib/libawb.so Normal file

Binary file not shown.

BIN
server/dl_lib/libcli.so Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
server/dl_lib/libcvi_bin.so Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
server/dl_lib/libcvi_ive.so Normal file

Binary file not shown.

BIN
server/dl_lib/libcvi_ssp.so Normal file

Binary file not shown.

BIN
server/dl_lib/libcvi_vqe.so Normal file

Binary file not shown.

BIN
server/dl_lib/libdnvqe.so Normal file

Binary file not shown.

BIN
server/dl_lib/libini.so Normal file

Binary file not shown.

BIN
server/dl_lib/libisp.so Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
server/dl_lib/libkvm.so Normal file

Binary file not shown.

BIN
server/dl_lib/libkvm_mmf.so Normal file

Binary file not shown.

BIN
server/dl_lib/libmipi_tx.so Normal file

Binary file not shown.

BIN
server/dl_lib/libmisc.so Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
server/dl_lib/libosdc.so Normal file

Binary file not shown.

Binary file not shown.

BIN
server/dl_lib/libsys.so Normal file

Binary file not shown.

Binary file not shown.

BIN
server/dl_lib/libvdec.so Normal file

Binary file not shown.

BIN
server/dl_lib/libvenc.so Normal file

Binary file not shown.

BIN
server/dl_lib/libvpu.so Normal file

Binary file not shown.

79
server/go.mod Normal file
View File

@@ -0,0 +1,79 @@
module NanoKVM-Server
go 1.24.0
require (
github.com/creack/pty v1.1.24
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.2
github.com/gorilla/websocket v1.5.3
github.com/mervick/aes-everywhere/go/aes256 v0.0.0-20240803013625-6759956693c0
github.com/pion/dtls/v3 v3.0.3
github.com/pion/rtp v1.8.18
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.45.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/ice/v4 v4.0.2 // indirect
github.com/pion/interceptor v0.1.39 // indirect
github.com/pion/logging v0.2.3 // indirect
github.com/pion/mdns/v2 v2.0.7 // indirect
github.com/pion/randutil v0.1.0 // indirect
github.com/pion/rtcp v1.2.15 // 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.47.0 // indirect
golang.org/x/sys v0.38.0 // indirect
golang.org/x/text v0.31.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
)

186
server/go.sum Normal file
View File

@@ -0,0 +1,186 @@
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/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
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.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
github.com/golang-jwt/jwt/v5 v5.2.2/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.39 h1:Y6k0bN9Y3Lg/Wb21JBWp480tohtns8ybJ037AGr9UuA=
github.com/pion/interceptor v0.1.39/go.mod h1:Z6kqH7M/FYirg3frjGJ21VLSRJGBXB/KqaTIrdqnOic=
github.com/pion/logging v0.2.3 h1:gHuf0zpoh1GW67Nr6Gj4cv5Z9ZscU7g/EaoC/Ke/igI=
github.com/pion/logging v0.2.3/go.mod h1:z8YfknkquMe1csOrxK5kc+5/ZPAzMxbKLX5aXpbpC90=
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.15 h1:LZQi2JbdipLOj4eBjK4wlVoQWfrZbh3Q6eHtWtJBZBo=
github.com/pion/rtcp v1.2.15/go.mod h1:jlGuAjHMEXwMUHK78RgX0UmEJFV4zUKOFHR7OP+D3D0=
github.com/pion/rtp v1.8.18 h1:yEAb4+4a8nkPCecWzQB6V/uEU18X1lQCGAQCjP+pyvU=
github.com/pion/rtp v1.8.18/go.mod h1:bAu2UFKScgzyFqvUKmbvzSdPr+NGbZtv6UB2hesqXBk=
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/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.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.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
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.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
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.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
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,74 @@
#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>
#include <time.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
#define NORMAL_RES 0
#define NEW_RES 1
#define UNSUPPORT_RES 2
#define UNKNOWN_RES 3
#define ERROR_RES 4
void kvmv_init(uint8_t _debug_info_en);
void set_venc_auto_recyc(uint8_t _enable);
/**********************************************************************************
* @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
-7: HDMI INPUT RES ERROR
-6: Unsupported resolution, please modify it in the host settings.
-5: Retrieving image, please wait
-4: Modifying image resolution, please wait
-3: img buffer full
-2: VENC Error
-1: No images were acquired
0: Acquire MJPEG encoded images
1: Acquire H264 encoded images(SPS)[Deprecated]
2: Acquire H264 encoded images(PPS)[Deprecated]
3: Acquire H264 encoded images(I)
4: Acquire H264 encoded images(P)
5: IMG not changed
**********************************************************************************/
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 free_kvmv_data(uint8_t ** _pp_kvm_data);
void free_all_kvmv_data();
void set_h264_gop(uint8_t _gop);
void set_frame_detact(uint8_t _frame_detact);
void kvmv_deinit();
uint8_t kvmv_hdmi_control(uint8_t _en);
#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.000")
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")
}

114
server/main.go Normal file
View File

@@ -0,0 +1,114 @@
package main
import (
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"NanoKVM-Server/common"
"NanoKVM-Server/config"
"NanoKVM-Server/logger"
"NanoKVM-Server/middleware"
"NanoKVM-Server/router"
"NanoKVM-Server/service/vm/jiggler"
"NanoKVM-Server/utils"
"github.com/gin-gonic/gin"
cors "github.com/rs/cors/wrapper/gin"
)
func main() {
initialize()
defer dispose()
run()
}
func initialize() {
logger.Init()
// init screen parameters
_ = common.GetScreen()
// init HDMI
vision := common.GetKvmVision()
vision.SetHDMI(false)
time.Sleep(10 * time.Millisecond)
if !utils.IsHdmiDisabled() {
vision.SetHDMI(true)
}
// run mouse jiggler
jiggler.GetJiggler().Run()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
go func() {
sig := <-sigChan
log.Printf("\nReceived signal: %v\n", sig)
dispose()
os.Exit(0)
}()
}
func run() {
conf := config.GetInstance()
gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.Use(gin.Recovery())
if conf.Authentication == "disable" {
r.Use(cors.AllowAll())
}
router.Init(r)
httpAddr := fmt.Sprintf(":%d", conf.Port.Http)
httpsAddr := fmt.Sprintf(":%d", conf.Port.Https)
if conf.Proto == "https" {
go func() {
r.Use(middleware.Tls())
err := r.RunTLS(httpsAddr, conf.Cert.Crt, conf.Cert.Key)
if err != nil {
panic("start https server failed")
}
}()
runRedirect(httpAddr, httpsAddr)
} else {
if err := r.Run(httpAddr); err != nil {
panic("start http server failed")
}
}
}
func runRedirect(httpPort string, httpsPort string) {
err := http.ListenAndServe(httpPort, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
host := req.Host
if strings.Contains(host, httpPort) {
host = strings.Split(host, httpPort)[0]
}
targetURL := "https://" + host + req.URL.String()
if httpsPort != ":443" {
targetURL = "https://" + host + httpsPort + req.URL.String()
}
http.Redirect(w, req, targetURL, http.StatusTemporaryRedirect)
}))
if err != nil {
panic("start http server failed")
}
}
func dispose() {
common.GetKvmVision().Close()
}

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

@@ -0,0 +1,75 @@
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
}
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()
expireDuration := time.Duration(conf.JWT.RefreshTokenDuration) * time.Second
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.JWT.SecretKey))
}
func ParseJWT(jwtToken string) (*Token, error) {
conf := config.GetInstance()
t, err := jwt.ParseWithClaims(jwtToken, &Token{}, func(token *jwt.Token) (interface{}, error) {
return []byte(conf.JWT.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,14 @@
package proto
type GetVersionRsp struct {
Current string `json:"current"`
Latest string `json:"latest"`
}
type GetPreviewRsp struct {
Enabled bool `json:"enabled"`
}
type SetPreviewReq struct {
Enable bool `validate:"omitempty"`
}

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

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

11
server/proto/download.go Normal file
View File

@@ -0,0 +1,11 @@
package proto
type ImageEnabledRsp struct {
Enabled bool `json:"enabled"`
}
type StatusImageRsp struct {
Status string `json:"status"`
File string `json:"file"`
Percentage string `json:"percentage"`
}

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

@@ -0,0 +1,9 @@
package proto
type GetHidModeRsp struct {
Mode string `json:"mode"` // normal or hid-only
}
type SetHidModeReq struct {
Mode string `validate:"required"` // normal or hid-only
}

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

@@ -0,0 +1,44 @@
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 SetMacNameReq struct {
Mac string `form:"mac" validate:"required"`
Name string `form:"name" validate:"required"`
}
type TailscaleState string
const (
TailscaleNotInstall TailscaleState = "notInstall"
TailscaleNotRunning TailscaleState = "notRunning"
TailscaleNotLogin TailscaleState = "notLogin"
TailscaleStopped TailscaleState = "stopped"
TailscaleRunning TailscaleState = "running"
)
type GetTailscaleStatusRsp struct {
State TailscaleState `json:"state"`
Name string `json:"name"`
IP string `json:"ip"`
Account string `json:"account"`
}
type LoginTailscaleRsp struct {
Url string `json:"url"`
}
type GetWifiRsp struct {
Supported bool `json:"supported"`
Connected bool `json:"connected"`
}

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)
}

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

@@ -0,0 +1,22 @@
package proto
type GetImagesRsp struct {
Files []string `json:"files"`
}
type MountImageReq struct {
File string `json:"file" validate:"omitempty"`
Cdrom bool `json:"cdrom" validate:"omitempty"`
}
type GetMountedImageRsp struct {
File string `json:"file"`
}
type GetCdRomRsp struct {
Cdrom int64 `json:"cdrom"`
}
type DeleteImageReq struct {
File string `json:"file" validate:"required"`
}

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

@@ -0,0 +1,9 @@
package proto
type UpdateFrameDetectReq struct {
Enabled bool `validate:"omitempty"`
}
type StopFrameDetectReq struct {
Duration int `validate:"omitempty"`
}

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

@@ -0,0 +1,138 @@
package proto
type IP struct {
Name string `json:"name"`
Addr string `json:"addr"`
Version string `json:"version"`
Type string `json:"type"`
}
type GetInfoRsp struct {
IPs []IP `json:"ips"`
Mdns string `json:"mdns"`
Image string `json:"image"`
Application string `json:"application"`
DeviceKey string `json:"deviceKey"`
}
type GetHardwareRsp struct {
Version string `json:"version"`
}
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"`
}
type SetMemoryLimitReq struct {
Enabled bool `validate:"omitempty"`
Limit int64 `validate:"omitempty"`
}
type GetMemoryLimitRsp struct {
Enabled bool `json:"enabled"`
Limit int64 `json:"limit"`
}
type SetOledReq struct {
Sleep int `validate:"omitempty"`
}
type GetOLEDRsp struct {
Exist bool `json:"exist"`
Sleep int `json:"sleep"`
}
type GetGetHdmiStateRsp struct {
Enabled bool `json:"enabled"`
}
type GetSSHStateRsp struct {
Enabled bool `json:"enabled"`
}
type GetSwapRsp struct {
Size int64 `json:"size"` // unit: MB
}
type SetSwapReq struct {
Size int64 `validate:"omitempty"` // unit: MB
}
type GetMouseJigglerRsp struct {
Enabled bool `json:"enabled"`
Mode string `json:"mode"`
}
type SetMouseJigglerReq struct {
Enabled bool `validate:"omitempty"`
Mode string `validate:"omitempty"`
}
type GetMdnsStateRsp struct {
Enabled bool `json:"enabled"`
}
type SetHostnameReq struct {
Hostname string `validate:"required"`
}
type GetHostnameRsp struct {
Hostname string `json:"hostname"`
}
type SetWebTitleReq struct {
Title string `validate:"omitempty"`
}
type GetWebTitleRsp struct {
Title string `json:"title"`
}
type SetTlsReq struct {
Enabled bool `validate:"omitempty"`
}

View File

@@ -0,0 +1,19 @@
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
api.GET("/application/preview", service.GetPreview) // get preview updates state
api.POST("/application/preview", service.SetPreview) // set preview updates state
}

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

@@ -0,0 +1,21 @@
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.GET("/auth/account", service.GetAccount) // get account
api.POST("/auth/password", service.ChangePassword) // change password
api.POST("/auth/logout", service.Logout) // logout
}

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

@@ -0,0 +1,17 @@
package router
import (
"NanoKVM-Server/service/download"
"github.com/gin-gonic/gin"
"NanoKVM-Server/middleware"
)
func downloadRouter(r *gin.Engine) {
service := download.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
api.POST("/download/image", service.DownloadImage) // download image
api.GET("/download/image/status", service.StatusImage) // download image
api.GET("/download/image/enabled", service.ImageEnabled) // download image
}

View File

@@ -0,0 +1,25 @@
package router
import (
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/extensions/tailscale"
"github.com/gin-gonic/gin"
)
func extensionsRouter(r *gin.Engine) {
api := r.Group("/api/extensions").Use(middleware.CheckToken())
ts := tailscale.NewService()
api.POST("/tailscale/install", ts.Install) // install tailscale
api.POST("/tailscale/uninstall", ts.Uninstall) // uninstall tailscale
api.GET("/tailscale/status", ts.GetStatus) // get tailscale status
api.POST("/tailscale/up", ts.Up) // run tailscale up
api.POST("/tailscale/down", ts.Down) // run tailscale down
api.POST("/tailscale/login", ts.Login) // tailscale login
api.POST("/tailscale/logout", ts.Logout) // tailscale logout
api.POST("/tailscale/start", ts.Start) // tailscale start
api.POST("/tailscale/stop", ts.Stop) // tailscale stop
api.POST("/tailscale/restart", ts.Restart) // tailscale restart
}

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

@@ -0,0 +1,19 @@
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/paste", service.Paste) // paste
api.GET("/hid/mode", service.GetHidMode) // get hid mode
api.POST("/hid/mode", service.SetHidMode) // set hid mode
api.POST("/hid/reset", service.ResetHid) // reset hid
}

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

@@ -0,0 +1,22 @@
package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/network"
)
func networkRouter(r *gin.Engine) {
service := network.NewService()
r.POST("/api/network/wifi", service.ConnectWifi) // connect Wi-Fi
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/wol/mac/name", service.SetMacName) // set mac name
api.GET("/network/wifi", service.GetWifi) // get Wi-Fi information
}

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