commit 70d467d05215a708f8b02e859eff00810e156e5f
Author: qing <1776177662@qq.com>
Date: Mon Jul 20 11:12:29 2026 +0800
init
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..bf6f23c
--- /dev/null
+++ b/README.md
@@ -0,0 +1,3 @@
+# micro_servers
+
+DIY的微服务架构
diff --git a/_inst.sh b/_inst.sh
new file mode 100644
index 0000000..705b311
--- /dev/null
+++ b/_inst.sh
@@ -0,0 +1,32 @@
+#!/bin/bash
+set -euo pipefail
+
+run_if_exists() {
+ local script="$1"
+ echo "---- run ${script} ----"
+
+ if [ -f "$script" ]; then
+ bash "$script"
+ fi
+}
+
+inst_module() {
+ local module="$1"
+ echo "======== Install ${module} ========"
+
+ local set_file="./${module}/_set.sh"
+
+ if [ -f "$set_file" ]; then
+ run_if_exists "$set_file"
+ return 0
+ else
+ echo "Failed" >&2
+ return 1
+ fi
+}
+
+inst_module "libth"
+inst_module "libhttp"
+inst_module "libcrypt"
+inst_module "core"
+inst_module "gateway"
diff --git a/_setup.sh b/_setup.sh
new file mode 100644
index 0000000..c3011fe
--- /dev/null
+++ b/_setup.sh
@@ -0,0 +1,5 @@
+#!/bin/bash
+
+# Debian
+sudo apt update
+sudo apt install libboost-all-dev libcurl4-gnutls-dev python3 python3-venv python3-pip g++ patchelf
diff --git a/core/.gitignore b/core/.gitignore
new file mode 100644
index 0000000..5e246e0
--- /dev/null
+++ b/core/.gitignore
@@ -0,0 +1,132 @@
+#prj
+users/
+*.crt
+*.key
+*.pem
+build/
+build_*/
+nidus
+
+# ide
+.vscode/
+.arts/
+
+# Prerequisites
+*.d
+
+# Compiled Object files
+*.slo
+*.lo
+*.o
+*.obj
+
+# Precompiled Headers
+*.gch
+*.pch
+
+# Compiled Dynamic libraries
+*.so
+*.dylib
+*.dll
+
+# Fortran module files
+*.mod
+*.smod
+
+# Compiled Static libraries
+*.lai
+*.la
+*.a
+*.lib
+
+# Executables
+*.exe
+*.out
+*.app
+
+
+
+# cangjie
+build/
+target/
+output/
+module-resolve.json
+module-lock.json
+cjpm.lock
+.cjpm-history
+*.macrocall
+*.gcda
+*.gcno
+
+
+
+# Precompiled Headers
+*.gch
+*.pch
+
+# Compiled Dynamic libraries
+*.so
+*.dylib
+*.dll
+
+# Fortran module files
+*.mod
+*.smod
+
+# Compiled Static libraries
+*.lai
+*.la
+*.a
+*.lib
+
+# Executables
+*.exe
+*.out
+*.app
+
+
+
+# 我加的
+.env/
+*.db
+*.api_key
+*.key
+*.pem
+pmcd
+rzgs_2
+crt
+cert
+
+# 其他
+log/
+report/
+tmp/
+*.cache
+*.pyc
+*.cython
+#*.jpg
+#*.png
+*.pth
+.eggs/
+*.egg-info
+.idea/
+.vscode/
+
+# nodejs
+node_modules/
+
+#python
+__pycache__/
+venv
+
+# do not ignore the log folder by pmc-mgmt
+!./mgmt/app/log/
+
+# go
+go.mod
+go.sum
+
+
+# VS
+x64
+.vs
diff --git a/core/LICENSE b/core/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/core/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ 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.
+
+
+ Copyright (C)
+
+ 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 .
+
+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:
+
+ Copyright (C)
+ 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
+.
+
+ 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
+.
diff --git a/core/Makefile b/core/Makefile
new file mode 100644
index 0000000..399c883
--- /dev/null
+++ b/core/Makefile
@@ -0,0 +1,88 @@
+VERSION := 0.0.4
+
+APP_NAME := nidus
+
+INSTL_DIRS := /usr/local/bin
+
+CONF_NAME := init.txt
+
+CONF_DIR := /etc/Nidus
+
+SRV_NAME := Nidus.service
+
+SRV_DIR := /etc/systemd/system
+
+CPP:= g++
+
+INCS:= -I include/
+
+MY_LIBS := -L/usr/lib -lus_th -lus_http
+LIBS := -lpthread -lssl -lcrypto -lboost_program_options -lboost_json -lboost_thread -lboost_filesystem
+
+CPPFLAGS := --std=c++20 -O3 -pipe #-Wall -Werror
+
+BUILD_DIR = build
+$(shell mkdir -p $(BUILD_DIR))
+
+#--------
+all: ${APP_NAME}.out
+${APP_NAME}.out: $(BUILD_DIR)/main.o $(BUILD_DIR)/PPool.o $(BUILD_DIR)/ProcessTask.o $(BUILD_DIR)/HttpTask.o $(BUILD_DIR)/Tttask.o $(BUILD_DIR)/pmc_mtd.o $(BUILD_DIR)/subsys_call.o
+ $(CPP) $^ $(MY_LIBS) $(LIBS) -o $@
+
+$(BUILD_DIR)/main.o: src/main.cpp
+ $(CPP) $(CPPFLAGS) -c $^ $(INCS) -o $@
+
+$(BUILD_DIR)/PPool.o: src/main/PPool.cpp
+ $(CPP) $(CPPFLAGS) -c $^ $(INCS) -o $@
+
+$(BUILD_DIR)/ProcessTask.o: src/main/ProcessTask.cpp
+ $(CPP) $(CPPFLAGS) -c $^ $(INCS) -o $@
+
+$(BUILD_DIR)/Tttask.o: src/main/Tttask.cpp
+ $(CPP) $(CPPFLAGS) -c $^ $(INCS) -o $@
+
+$(BUILD_DIR)/HttpTask.o: src/main/HttpTask.cpp
+ $(CPP) $(CPPFLAGS) -c $^ $(INCS) -o $@
+
+$(BUILD_DIR)/pmc_mtd.o: src/main/pmc_mtd.cpp
+ $(CPP) $(CPPFLAGS) -c $^ $(INCS) -o $@
+
+$(BUILD_DIR)/subsys_call.o: src/main/subsys_call.cpp
+ $(CPP) $(CPPFLAGS) -c $^ $(INCS) -o $@
+
+
+
+install: $(APP_NAME).out
+ @echo "正在安装 $(APP_NAME) 到$(INSTL_DIRS)"
+ @
+ #@mkdir -p $(INSTL_DIRS)
+ @cp -f $(APP_NAME).out $(INSTL_DIRS)/$(APP_NAME)
+ #@chmod 755 $(INSTL_DIRS)/pmcd
+ @
+ @echo "正在配置 $(APP_NAME)"
+ @mkdir -p $(CONF_DIR)
+ @cp $(CONF_NAME) $(CONF_DIR)/$(CONF_NAME)
+ @cp $(SRV_NAME) $(SRV_DIR)/$(SRV_NAME)
+ @systemctl daemon-reload
+ @systemctl enable $(SRV_NAME)
+ @systemctl restart $(SRV_NAME)
+ @
+ @echo "安装完成!"
+
+uninstall:
+ @echo "正在从 $(INSTL_DIRS) 卸载 $(APP_NAME)"
+ @
+ @rm -f $(INSTL_DIRS)/$(APP_NAME)
+ @rm -f $(CONF_DIRS)/$(CONF_NAME)
+ @rm -f -d ${CONF_DIRS}
+ @
+ @systemctl stop $(SRV_NAME)
+ @systemctl disable $(SRV_NAME)
+ @rm -f $(SRV_DIRS)/$(SRV_NAME)
+ @systemctl daemon-reload
+ @
+ @echo "卸载完成!"
+
+clear:
+ @rm -rvf $(BUILD_DIR)
+ @rm -vf *.out
diff --git a/core/Nidus.service b/core/Nidus.service
new file mode 100644
index 0000000..71894cc
--- /dev/null
+++ b/core/Nidus.service
@@ -0,0 +1,10 @@
+[Unit]
+Description=PMC Http Interfaces
+After=network.target
+
+[Service]
+User=qing
+Group=qing
+ExecStart=nidus -i /etc/Nidus/init.txt --serve 5200
+[Install]
+WantedBy=multi-user.target
diff --git a/core/README.md b/core/README.md
new file mode 100644
index 0000000..5e3f3b1
--- /dev/null
+++ b/core/README.md
@@ -0,0 +1,56 @@
+# 进程机器(PMC)
+这是一个可以创建、管理子进程以及模块的程序。
+
+## pmc是一个什么项目?
+这是一个可扩展的模块,可以在文件夹下建立单独的模块,pmc核心模块可以托管运行这些模块。
+
+
+## 为什么要做一个这样的项目?
+2024年的时候,我想做一个树莓派机器人,准备用python来写控制程序,可是当时python的多线程能力较弱,所以想到使用子系统,就自己写了一个进程托管程序
+
+
+## 项目的文件结构是怎样的?
+users用户可以在目录下创建子模块,extra下面还有一些额外的模块。
+
+请留意模块的README文件
+
+
+## 如何托管外部模块
+编辑启动列表程序,常为init.txt
+
+
+## PMC的安装方式
+``` bash
+# 1.安装依赖
+
+# 安装UniServe的libth包
+git clone https://github.com/gopsc/UniServe_libth
+cd UniServe_libth
+sudo bash _set.sh
+
+# 安装别的依赖
+sudo apt update
+sudo apt install git g++ make
+sudo apt install libboost-all-dev
+#sudo apt install libssl-dev
+#sudo apt install libcurl4-openssl-dev
+#sudo apt install libcurl4-gnutls-dev
+
+# 2. 创建项目
+git clone https://github.com/gopsc/UniServe_core
+cd UniServe_core
+make
+sudo make install
+```
+
+## 加密通信机制(废弃)
+PMC在启动时生成一个AES密钥,然后用一个RSA公钥将其加密发送给访问者。
+
+然后访问者与客户端之间的交流全部用此AES密钥加密
+
+
+## 如何使用并发机器运行程序
+首先应该在模块中创建一个启动脚本,脚本中应该完成工作目录的切换、虚拟环境的激活,以及程序的启动。
+
+
+
diff --git a/core/_run.sh b/core/_run.sh
new file mode 100644
index 0000000..cdc554d
--- /dev/null
+++ b/core/_run.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+cd "$(dirname "$0")" || exit
+./nidus.out -i /etc/Nidus/init.txt --serve 5200
+
diff --git a/core/_set.sh b/core/_set.sh
new file mode 100644
index 0000000..d8a7788
--- /dev/null
+++ b/core/_set.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+cd "$(dirname "$0")" || exit
+make clear && make $@
+make install
diff --git a/core/include/cn/中文化.hpp b/core/include/cn/中文化.hpp
new file mode 100644
index 0000000..d5cdddd
--- /dev/null
+++ b/core/include/cn/中文化.hpp
@@ -0,0 +1,177 @@
+
+//作者:简单
+//修改:qing
+/*
+ * C++17支持了中文变量名,配合define预编译指令可以将代码中文化。
+ *
+ * 在C语言中,变量名只能由字母、数字或是下划线组成。
+ * 由于C++语言兼容C语言,最开始的C++是不能够使用多字节变量名的。
+ *
+ * */
+#ifndef __中文模式
+#define __中文模式
+#include
+/*保留字*/
+#define 使用 using
+#define 命名空间 namespace
+#define 取别名 typedef
+#define 覆盖 override
+#define 取内存大小 sizeof
+#define 返回 return
+#define 如果 if
+#define 否则 else
+#define 又或者 else if
+#define 真 true
+#define 假 false
+//#define 且 and
+//#define 或 or
+#define 空类型 void
+#define 常量 const
+#define 有符号 signed
+#define 无符号 unsigned
+#define 文件 FILE
+#define 文件结束 EOF
+#define 类 class
+#define 结构体 struct
+#define 枚举类型 enum
+#define 对象 this
+#define 抛出异常 throw
+#define 新建 new
+//#define 新的 new
+#define 删除 delete
+#define 跳出 break
+#define 继续 continue
+#define 判断循环 while
+#define 循环判断 do
+#define 循环判断尾 while
+#define 分支选择 switch
+#define 支系 case
+#define 缺省 default
+#define 计次循环 for
+#define 尝试 try
+#define 获取异常 catch
+#define 捕获异常 catch
+#define 退出 exit
+#define 公开的 public
+#define 受保护的 protected
+#define 私有的 private
+#define 外部的 extern
+#define 静态的 static
+#define 虚拟的 virtual
+
+#define 有号8位整 int8_t
+#define 无号8位整 uint8_t
+#define 有号16位整 int16_t
+#define 无号16位整 uint16_t
+#define 有号32位整 int32_t
+#define 无号32位整 uint32_t
+#define 有号64位整 int64_t
+#define 无号64位整 uint64_t
+
+#define 空的 NULL
+#define 空指针 nullptr
+#define 整数 int
+#define 字符 char
+#define 短整数 short
+#define 长型 long
+#define 超长型 long long
+#define 单精度小数 float
+#define 双精度小数 double
+#define 长度单位 size_t
+#define 布尔 bool
+#define 逻辑型 bool
+#define 可变类型 auto
+#define 自动的 auto
+#define 适应 auto
+#define _文件 FILE
+#define _文件结束 EOF
+#define _读模式 "r"
+#define _写模式 "w"
+#define 模板 template
+#define 类型名 typename
+#define 默认的 default
+#define 被删除 delete
+#define 入口 main
+#define 主函数 main
+#define 或 ||
+#define 或者 ||
+#define 而且 &&
+#define 且 &&
+#define 等于 ==
+#define 大于等于 >=
+#define 小于等于 <=
+#define 大于 >
+#define 小于 <
+#define 不报错的 noexcept
+#define 不转换的 explicit
+#define 纯函数的 consteval
+#define 预求值的 constexpr
+
+#define _加法重载 operator+
+#define _取下标重载 operator[]
+#define _开始 begin
+#define _结束 end
+//-----------------------------------------------------------
+//-----------------------------------------------------------
+//基本单元
+#ifdef __cplusplus
+#include
+
+命名空间 中文标准{
+
+类 字符串 {
+公开的:
+ /* 初始化为空字符串 */
+ 字符串() {
+ 对象->s = "";
+ }
+ /* 以字面量初始化 */
+ 字符串(常量 字符* 源) {
+ 对象->s = 源;
+ }
+ /* 访问器 */
+ 常量 字符* 取值() {
+ 返回 s.c_str();
+ }
+ /* */
+ 字符串& _加法重载(常量 字符* 乙方) {
+ 对象->s += 乙方;
+ 返回 *对象;
+ }
+ /* 字符串之间的连接 */
+ 字符串& _加法重载(字符串& 乙) {
+ 对象->s += 乙.取值();
+ 返回 *对象;
+ }
+私有的:
+ std::string s;
+};
+
+类 标准输出{
+公开的:
+ 空类型 调试输出(常量 字符* 消息) {
+ std::cout << 消息;
+ }
+ 空类型 调试输出(字符串& 信) {
+ std::cout<< 信.取值();
+ }
+};
+
+类 标准输入{
+公开的:
+ 字符串 取字符串(){
+ std::string s;
+ std::cin >> s;
+ 返回 字符串(s.c_str());
+ }
+ 整数 取整数() {
+ 整数 数;
+ std::cin >> 数;
+ 返回 数;
+ }
+};
+
+
+}
+#endif //__cplusplus
+#endif //__中文模式
diff --git a/core/include/cn/向量.hpp b/core/include/cn/向量.hpp
new file mode 100644
index 0000000..2380e08
--- /dev/null
+++ b/core/include/cn/向量.hpp
@@ -0,0 +1,129 @@
+#pragma once
+#include "中文化.hpp"
+#include "异常.hpp"
+命名空间 中文标准 {
+模板 <类型名 类型1>
+类 向量{
+公开的:
+
+ /* 注意:当长度单位为0时,内部指针是空的 */
+ 向量() {
+ 对象->指针 = 空指针;
+ 对象->容量 = 0;
+ }
+ /* 专门用于处理花括号初始化列表 */
+ 向量(常量 std::initializer_list<类型1>& init = {}) {
+ 对象->指针 = 新建 类型1[init.size()] {空的};
+ 对象->容量 = init.size();
+ 长度单位 计数 = 0;
+ 计次循环(适应 & 东西: init) {
+ 对象->指针[计数++] = 东西;
+ }
+ }
+
+ ~向量() {
+ 删除 对象->指针;
+ 对象->指针 = 空指针;
+ 对象->容量 = 0;
+ }
+ /*----------访问器----------*/
+ 长度单位 取容量() {
+ 返回 对象->容量;
+ }
+
+ 布尔 是否为空() {
+ 返回 对象->容量 等于 0;
+ }
+
+ /*--------运算符重载--------*/
+ 向量& _取下标重载( 常量 长度单位 下标 ) {
+ 如果(下标 < 0 或 下标 >= 对象->容量)
+ 抛出异常 下标越界{"向量", 对象->容量, 下标};
+ 返回 对象->指针[下标];
+ }
+
+ /*--------可范围遍历--------*/
+ 类型1* _开始() {
+ 返回 对象->指针;
+ }
+
+ 类型1* _结束() {
+ 返回 对象->指针 + 对象->容量;
+ }
+
+ /*----------变异器----------*/
+ 空类型 插入元素(常量 长度单位 位置, 常量 向量& 媒介) {
+
+ /* 越界检查 */
+ 如果(位置 < 0 或 位置 > 对象->容量)
+ 抛出异常 下标越界{"向量元素插入", 对象->容量+1, 位置};
+
+ 适应 长度 = 取容量();
+ 适应 新的 = 新建 类型1[长度 + 1] { 空的 };
+
+ /* 插入位置之前 */
+ 计次循环(适应 计数 = 0; 计数 < 位置; ++计数)
+ 新的[计数] = 对象->指针[计数];
+
+ /* 执行插入 */
+ 新的[位置] = 媒介;
+
+ /* 插入位置之后 */
+ 计次循环(适应 计数 = 位置 + 1; 计数 <= 长度; ++计数)
+ 新的[计数] = 对象->指针[计数 - 1];
+
+ 如果(对象->指针) 删除[] 对象->指针; /* 可能为空 */
+ 对象->指针 = 新的;
+ }
+
+ 空类型 追加元素(常量 向量& 媒介) {
+ 适应 长度 = 取容量();
+ 适应 新的 = 新建 类型1[长度 +1] {空的};
+ 计次循环(适应 计数 = 0; 计数 < 长度; ++计数)
+ 新的[计数] = 对象->指针[计数];
+ 新的[长度] = 媒介;
+ 如果(对象->指针) 删除[] 指针; /* 可能为空 */
+ 对象->指针 = 新的;
+ }
+
+ 空类型 删除元素(常量 长度单位 位置) {
+
+ /* 越界检查 */
+ 如果(位置 < 0 或 位置 >= 对象->容量)
+ 抛出异常 下标越界{"向量元素插入", 对象->容量 + 1, 位置};
+
+ 适应 长度 = 取容量();
+ 适应 新的 = (长度 等于 1)
+ ? 空指针 : 新建 类型1[长度 - 1] { 空的 };
+
+ /* 目标位置之前 */
+ 计次循环(适应 计数 = 0; 计数 < 位置; ++计数)
+ 新的[计数] = 对象->指针[计数];
+
+ /* 目标位置之后 */
+ 计次循环(适应 计数 = 位置; 计数 < 长度; ++计数)
+ 新的[计数] = 对象->指针[计数 + 1];
+
+ 删除[] 对象->指针;
+ 对象->指针 = 新的;
+ }
+
+
+
+ /*----------------*/
+ //类 迭代器{
+ //公开的:
+ // 迭代器(常量 std::vector<类型1>::iterator& it) {
+ // this->it = it;
+ // }
+ //私有的:
+ // std::vector<类型1>::iterator it;
+ //};
+ /*----------------*/
+
+
+私有的:
+ 类型1 *指针;
+ 长度单位 容量;
+};
+}
\ No newline at end of file
diff --git a/core/include/cn/异常.hpp b/core/include/cn/异常.hpp
new file mode 100644
index 0000000..79208bd
--- /dev/null
+++ b/core/include/cn/异常.hpp
@@ -0,0 +1,24 @@
+#pragma once
+#include "中文化.hpp"
+命名空间 中文标准 {
+类 标准异常 : 公开的 std::exception {
+公开的:
+ 不转换的 标准异常(常量 字符* 信息): 信息(信息) {}
+ 常量 字符* what() 常量 不报错的 覆盖 {
+ 返回 信息;
+ }
+私有的:
+ 常量 字符* 信息;
+};
+
+类 下标越界 : 公开的 标准异常{
+公开的:
+ 下标越界(常量 字符 * 提示, 常量 长度单位 标准值, 常量 长度单位 目前值)
+ : 标准异常(提示), 标准值(标准值), 目前值(目前值) {
+};
+ 长度单位 取标准值() { 返回 标准值; }
+ 长度单位 取目前值() { 返回 目前值; }
+私有的:
+ 长度单位 标准值, 目前值;
+};
+}
\ No newline at end of file
diff --git a/core/include/cn/链串.hpp b/core/include/cn/链串.hpp
new file mode 100644
index 0000000..cd5a9ec
--- /dev/null
+++ b/core/include/cn/链串.hpp
@@ -0,0 +1,97 @@
+#pragma once
+#include "中文化.hpp"
+#include "异常.hpp"
+#include "顺序表.hpp"
+命名空间 中文标准 {
+模板 <类型名 类型1, 长度单位 节点大小 = 64>
+类 链串 {
+公开的:
+ /* 初始化为空链串 */
+ 链串() {
+ 对象->长度 = 0;
+ 对象->下一个 = 空指针;
+ 对象->上一个 = 空指针;
+ 对象->头 = 对象; /* 每一个子节点都记录同一个头结点 */
+ 对象->尾 = 对象; /* 为了方便,只有头结点记录尾节点 */
+ }
+
+ 链串 (常量 std::initializer_list<类型1>& init = {})
+ {
+ 计次循环(适应 & 东西: init) {
+ 插入(东西);
+ }
+ }
+
+ /*
+ * 链式析构
+ *
+ * 析构时,会递归析构所有节点。
+ */
+ ~链串() {
+ 删除[] 对象->下一个;
+ }
+
+ 空类型 插入(常量 类型1& 元素) {
+ 链串 *暂时 = 对象->尾;
+ 如果(暂时->长度 等于 节点大小)
+ _推();
+ 暂时->存储[暂时->长度++] = 元素;
+ }
+
+ 长度单位 统计() {
+ 长度单位 总数 = 0;
+ 链串 *暂时 = 对象->头;
+ 判断循环(暂时 != 空指针) {
+ 总数 += 暂时->长度;
+ 暂时 = 暂时->下一个;
+ }
+ 返回 总数;
+ }
+
+ /*
+ * 链串重组
+ *
+ * 将链串重组为顺序表W
+ */
+ 顺序表<类型1> 重组() {
+ 顺序表<类型1> 结果(统计());
+ 链串 *暂时 = 对象->头;
+ 长度单位 计数 = 0;
+ 判断循环(暂时 != 空指针) {
+ 计次循环(适应 索引 = 0; 索引 < 暂时->长度; ++索引) {
+ 结果[计数++] = 暂时->存储[索引];
+ }
+ 暂时 = 暂时->下一个;
+ }
+ 返回 结果;
+ }
+
+ 类 链串异常: 公开的 标准异常{
+ 公开的:
+ 链串异常(常量 字符* 消息) : 标准异常(消息) {}
+ };
+私有的:
+ 类型1 存储[节点大小];
+ 长度单位 长度; /* 存储中的元素数量 */
+ 链串 *下一个;
+ 链串 *上一个;
+ 链串 *头;
+ 链串 *尾;
+
+ 空类型 _推() {
+ 链串*新的;
+ 尝试{ 新的 = 新建 链串(); }
+ 捕获异常 (std::exception& exp){
+ 抛出异常 链串异常{"链串推失败"};
+ }
+ _拼接节点(新的);
+ }
+
+ 空类型 _拼接节点(链串* 新的) {
+ 对象->尾->下一个 = 新的;
+ 新的->上一个 = 对象->尾;
+ 对象->尾 = 新的;
+ 新的->头 = 对象;
+ }
+};
+}
\ No newline at end of file
diff --git a/core/include/cn/顺序表.hpp b/core/include/cn/顺序表.hpp
new file mode 100644
index 0000000..d8b55cc
--- /dev/null
+++ b/core/include/cn/顺序表.hpp
@@ -0,0 +1,28 @@
+#pragma once
+#include "中文化.hpp"
+#include "异常.hpp"
+命名空间 中文标准 {
+模板<类型名 类型1>
+类 顺序表 {
+公开的:
+ 顺序表(长度单位 大小) {
+ 存储 = 新建 类型1[大小];
+ 长度 = 大小;
+ }
+ ~顺序表() {
+ 删除[] 存储;
+ }
+ 类型1 _取下标重载(长度单位 下标) {
+ 如果(下标 >= 长度)
+ 抛出异常 顺序表异常{"下标超出范围"};
+ 返回 存储[下标];
+ }
+ 类 顺序表异常: 公开的 标准异常{
+ 公开的:
+ 顺序表异常(常量 字符* 消息) : 标准异常(消息) {}
+ };
+私有的:
+ 类型1 *存储;
+ 长度单位 长度;
+};
+}
\ No newline at end of file
diff --git a/core/include/logs/Logger.hpp b/core/include/logs/Logger.hpp
new file mode 100644
index 0000000..7d3baa0
--- /dev/null
+++ b/core/include/logs/Logger.hpp
@@ -0,0 +1,107 @@
+/* 日志 */
+#pragma once
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+enum class LogLevel {
+ DEBUG,
+ INFO,
+ WARNING,
+ ERROR,
+ CRITICAL
+};
+
+namespace qing {
+ /*
+ * 这是由Deepseek创作的,用于记录日志的类模块
+ * 简化版本,只输出到控制台
+ *
+ * 优化意见:改为存储日志文件
+ */
+ class Logger {
+ public:
+ //获取日志实例(单例模式)
+ static Logger& getInstance() {
+ static Logger instance;
+ return instance;
+ }
+
+ //初始化日志系统
+ void init(LogLevel minLogLevel = LogLevel::INFO,
+ bool consoleOutput = true) {
+ std::lock_guard lock(mutex_);
+
+ if (initialized_) {
+ return;
+ }
+
+ minLogLevel_ = minLogLevel;
+ consoleOutput_ = consoleOutput;
+ initialized_ = true;
+ }
+
+ // 设置最低日志级别
+ void setMinLogLevel(LogLevel level) {
+ std::lock_guard lock(mutex_);
+ minLogLevel_ = level;
+ }
+
+ // 日志输出方法
+ void log(LogLevel level, const std::string& message) {
+ if (level < minLogLevel_ || !consoleOutput_) {
+ return;
+ }
+
+ auto now = std::chrono::system_clock::now();
+ auto in_time_t = std::chrono::system_clock::to_time_t(now);
+ auto ms = std::chrono::duration_cast(
+ now.time_since_epoch()) % 1000;
+
+ std::tm tm;
+ localtime_r(&in_time_t, &tm);
+
+ std::stringstream ss;
+ ss << std::put_time(&tm, "%Y-%m-%d %H:%M:%S")
+ << "." << std::setfill('0') << std::setw(3) << ms.count()
+ << " [" << logLevelToString(level) << "] "
+ << message;
+
+ std::lock_guard lock(mutex_);
+ std::cout << ss.str() << std::endl;
+ }
+
+ Logger(const Logger&) = delete;
+ Logger& operator=(const Logger&) = delete;
+
+ private:
+ Logger() = default;
+ ~Logger() = default;
+
+ std::string logLevelToString(LogLevel level) {
+ switch (level) {
+ case LogLevel::DEBUG: return "DEBUG";
+ case LogLevel::INFO: return "INFO";
+ case LogLevel::WARNING: return "WARNING";
+ case LogLevel::ERROR: return "ERROR";
+ case LogLevel::CRITICAL: return "CRITICAL";
+ default: return "UNKNOWN";
+ }
+ }
+
+ std::mutex mutex_;
+ LogLevel minLogLevel_ = LogLevel::INFO;
+ bool consoleOutput_ = true;
+ bool initialized_ = false;
+ };
+}
+
+#define LOG_DEBUG(message) qing::Logger::getInstance().log(LogLevel::DEBUG, message)
+#define LOG_INFO(message) qing::Logger::getInstance().log(LogLevel::INFO, message)
+#define LOG_WARNING(message) qing::Logger::getInstance().log(LogLevel::WARNING, message)
+#define LOG_ERROR(message) qing::Logger::getInstance().log(LogLevel::ERROR, message)
+#define LOG_CRITICAL(message) qing::Logger::getInstance().log(LogLevel::CRITICAL, message)
diff --git a/core/include/main/HttpTask.hh b/core/include/main/HttpTask.hh
new file mode 100644
index 0000000..3858b99
--- /dev/null
+++ b/core/include/main/HttpTask.hh
@@ -0,0 +1,110 @@
+#pragma once
+#include
+#include
+#include
+namespace qing {
+ namespace http = boost::beast::http;
+ /* ----------------
+ * HttpTask类 - 超文本服务器任务 */
+ class HttpTask: public ITask {
+ public:
+
+ /* 接受一个回调函数,其接受pmc::net::HttpServer对象的引用,在回调函数中对服务器进行配置 */
+ HttpTask(int port, std::function handler);
+
+ /* 在一个线程中判断线程是否正在有效运行 */
+ bool isRunning() override;
+
+ /* 启动该项任务 */
+ void start() override;
+
+ /* 停止该项任务 */
+ void stop() override;
+
+ private:
+ int port;
+ std::function handler;
+ std::unique_ptr th; /* ---- 可控线程指针 */
+ std::unique_ptr server; /* ---- HTTP服务器的指针 ---- */
+
+ /* 初始化线程,定义线程的行为(Http服务器) */
+ void init_thread();
+ };
+
+ /*-----------------------------------------------------------------------------*/
+
+
+
+/* ================
+ * 进程托管http服务器
+ * ================
+ * 对操作进程列表的http服务器进行配置,即是输入回调函数 */
+namespace process_http_server {
+
+ /* ---- 注册POST路由 ---- */
+ void registerRoutes(pmc::net::HttpServer& server);
+
+ /**
+ * @brief 解析请求体中的JSON数据
+ * @param body 请求体字符串
+ * @return JSON解析后的属性树
+ */
+ boost::property_tree::ptree parseJsonBody(const std::string& body);
+
+ /**
+ * @brief 构建JSON响应
+ * @param success 是否成功
+ * @param message 消息
+ * @param data 附加数据
+ * @return JSON字符串
+ */
+ std::string buildJsonResponse(bool success, const std::string& message,
+ const boost::property_tree::ptree& data = boost::property_tree::ptree());
+
+ /**
+ * @brief 从请求中提取target参数
+ * @param params 查询参数
+ * @return target值(空字符串表示本机)
+ */
+ std::string getTarget(const std::unordered_map& params);
+
+ /**
+ * @brief 从请求中提取exec参数
+ * @param params 查询参数
+ * @return 要执行的指令
+ */
+ std::string getExecCommand(const std::unordered_map& params);
+
+ /**
+ * @brief 从请求中提取kill参数
+ * @param params 查询参数
+ * @return 目标进程号
+ */
+ int getPid(const std::unordered_map& params);
+
+ /* POST方法处理器 */
+ http::response handleList(
+ const http::request& req,
+ const std::unordered_map& params);
+
+ http::response handleExec(
+ const http::request& req,
+ const std::unordered_map& params);
+
+ http::response handleKill(
+ const http::request& req,
+ const std::unordered_map& params);
+
+ /** 内部实现函数 */
+ std::string listProcesses(const std::string& target);
+ std::string execCommand(const std::string& command, const std::string& target);
+ bool killProcess(int pid, const std::string& target);
+
+
+
+
+
+}
+
+
+}
diff --git a/core/include/main/PPool.hh b/core/include/main/PPool.hh
new file mode 100644
index 0000000..b487a41
--- /dev/null
+++ b/core/include/main/PPool.hh
@@ -0,0 +1,53 @@
+#pragma once
+#include
+#include
+#include
+#include "main/ProcessTask.hh"
+
+namespace qing {
+
+
+
+/* -----------------
+ * subprocess pool 子进程池
+ * ----------------
+ * FIXME: 将列表(序列化)功能放到这里来 */
+class PPool {
+public:
+
+ /* CREATE PROCESS - 创建进程
+ *
+ * cmd: 启动命令 */
+ void crtp(const std::string& cmd);
+
+
+ /* CLEAR 清理 - 删除所有已经停下的进程 */
+ void clr();
+
+
+ /* 获取进程池的大小 */
+ size_t size() { return pool.size(); }
+
+
+ /* 删除一个进程,需要输入进程的下标。
+ *
+ * FIXME: 输入进程下标似乎不太自然 */
+ void kill(int idx);
+
+ /* 取下标运算符重载 - 取元素对象 */
+ ProcessTask& operator[](const size_t idx);
+
+
+ /* TODO: 实现迭代器和begin()、end()
+ * ...... */
+
+private:
+
+ /* 进程任务的shared指针的容器 */
+ std::list> pool{};
+
+};
+
+
+
+}
diff --git a/core/include/main/ProcessTask.hh b/core/include/main/ProcessTask.hh
new file mode 100644
index 0000000..9969679
--- /dev/null
+++ b/core/include/main/ProcessTask.hh
@@ -0,0 +1,70 @@
+#pragma once
+#include
+#include
+
+namespace qing {
+
+/* ----------------
+ * 【子进程任务】
+ * ----------------
+ * 输入要执行的命令,构造子进程任务
+ * TODO: 我们可以重定向子进程的输入和输出,实时交互 */
+class ProcessTask: public ITask {
+public:
+
+ /* 输入一个字符串(要执行的命令)(但是并没有执行起来) */
+ ProcessTask(std::string cmd): cmd(cmd) {}
+
+ /* 任务是否在运行中 */
+ bool isRunning() override { return p && p->running(); }
+
+ /* 启动任务 */
+ void start() override {
+ if (!isRunning())
+ this->p = std::make_unique(cmd); }
+
+ /* 终止该任务(并且重置子进程指针) */
+ void stop() override {
+ if (isRunning()) p->terminate();
+ p.reset();
+ }
+
+ /* 获取该任务(子进程)的命令 */
+ std::string check() { return this->cmd; }
+
+ /* 获取该子进程的pid(进程编号) */
+ pid_t pid() { return p->id(); }
+
+private:
+ std::unique_ptr p; /* 子进程指针 */
+ std::string cmd; /* 该进程执行的命令 */
+};
+
+}
+
+
+#ifdef __NEW_VER
+/* ---- [子进程任务]boost.process库升级到了v2 ---- */
+class ProcessTask: public ITask {
+public:
+ ProcessTask(std::string cmd): cmd(cmd) {}
+ bool isRunning() override;
+ int getExitCode();
+ void start() override;
+ /* ---- NOTE(202606025-qing): 杀死进程失败只是打印错误信息 ---- */
+ void stop() override;
+ std::string check() {
+ return this->cmd;
+ }
+ pid_t pid() {
+ return p->id();
+ }
+
+private:
+ boost::asio::io_context ctx; /* 异步上下文 */
+ std::unique_ptr p; /* 子进程指针 */
+ boost::system::error_code exit_code; /* 进程退出的代码 */
+ std::string cmd; /* 要执行的命令 */
+};
+}
+#endif
diff --git a/core/include/main/Tttask.hh b/core/include/main/Tttask.hh
new file mode 100644
index 0000000..da3e6f9
--- /dev/null
+++ b/core/include/main/Tttask.hh
@@ -0,0 +1,58 @@
+#pragma onces
+#include "tt/Mq.h"
+namespace qing {
+
+
+/*
+ * TRANSMIT TASK 通信任务
+ * (创建一个通信伺服器,它收到消息就执行回调)
+ * (长时间伺服运行会不会有问题)
+ */
+class Tttask: public ITask {
+public:
+
+/* 构造【通信任务】
+ * msglen: 单条消息的长度
+ * msgcnt: 消息伺服长度
+ * callback: 回调函数 */
+Tttask(const size_t msglen, size_t msgcnt, const sf_t callback);
+
+/* 启动该通信伺服任务 */
+void start() override;
+
+/* 终止这个通信伺服任务
+ *
+ * TODO: 研究一下要不要释放一些资源
+ * TODO: 增加超时 */
+void stop() override {
+ if (this->isRunning())
+ th->WaitClose();
+}
+
+
+/* 该任务是否在运行
+ *
+ * FIXME: 对START状态的处理还应该考虑
+ * FIXME: 如果在STOP状态而没有stop()任务,可能会造成线程未关闭,一直占用资源? */
+bool isRunning() override;
+
+
+private:
+std::unique_ptr th; /* 可控线程指针 */
+std::unique_ptr callback; /* 回调行为(接收之后)指针 */
+std::unique_ptr mq; /* 消息队列指针 */
+size_t msglen=0, msgcnt=0; /* 消息的缓存规格 */
+std::string name; /* 消息队列名(进程号) */
+
+
+
+
+/* 初始化通信伺服线程,
+ * 初始化方法就是通过传入一些函数,
+ * 构建线程 */
+void init_thread();
+
+
+
+};
+}
diff --git a/core/include/main/pmc_mtd.hh b/core/include/main/pmc_mtd.hh
new file mode 100644
index 0000000..e45486d
--- /dev/null
+++ b/core/include/main/pmc_mtd.hh
@@ -0,0 +1,20 @@
+#pragma once
+#include
+namespace qing {
+/* ----------------
+ * 进程托管服务方法集
+ * ----------------
+ * 直接对进程组列表进行操作
+ *
+ */
+namespace pmc_mtd
+{
+ auto list() -> std::string; /* 列出所有的进程 */
+ auto kill(const int pid) -> bool; /* 杀死一个进程,需提供PID */
+ auto exec(const std::string& cmd) -> bool; /* 执行一个进程,输入要执行的命令行 */
+ auto parse_self_init_list(std::string &path) -> void; /* 解析自启动脚本 */
+}
+
+
+
+}
diff --git a/core/include/main/subsys_call.hh b/core/include/main/subsys_call.hh
new file mode 100644
index 0000000..05a05df
--- /dev/null
+++ b/core/include/main/subsys_call.hh
@@ -0,0 +1,19 @@
+#pragma once
+namespace qing {
+
+/* ----------------
+ * 子系统调用
+ * ----------------
+ * 通过进程间通信与子系统进行通讯,调用不同的功能
+ *
+ */
+
+
+namespace subsys_call
+{
+ std::string send_list_and_recv_pipe(const std::string& name_mq);
+ std::string send_start_and_recv_pipe(const std::string& name_mq, const std::string& exec);
+ std::string send_kill_and_recv_pipe(const std::string& name_mq, const int kill);
+}
+
+}
diff --git a/core/include/tt/Mq.h b/core/include/tt/Mq.h
new file mode 100644
index 0000000..97559d7
--- /dev/null
+++ b/core/include/tt/Mq.h
@@ -0,0 +1,93 @@
+/*
+ * 目前是Message Queue 的发送端(不涉及创建消息队列)
+ *
+ * FIXME: 集成发送、接收和创建
+ */
+
+#pragma once
+#include
+#include
+#include
+#include
+
+namespace qing {
+namespace bip = boost::interprocess;
+using sf_t = std::function; /* 通信成功的回调函数 success */
+using ef_t = std::function; /* 通信失败的回调函数 error */
+class Mq {
+public:
+ enum {CREATOR=0, USER=1};
+ Mq(const std::string& name, int msglen, size_t msgcnt, int mode = USER) {
+ this->name = std::string("/") + name;
+ this->msglen = msglen;
+ this->msgcnt = msgcnt;
+ this->mode = mode;
+ switch (mode) {
+ case USER:
+ mqp = std::make_unique(bip::open_only, this->name.c_str());
+ break;
+ case CREATOR: /* 由创建者创建消息队列 */
+ bip::message_queue::remove(this->name.c_str());
+ mqp = std::make_unique(
+ bip::create_only, this->name.c_str(),
+ msgcnt, msglen * sizeof(char)
+ );
+ break;
+ }
+ }
+
+ /* 创建者负责清理 */
+ ~Mq() {
+ if (mode == CREATOR)
+ bip::message_queue::remove(name.c_str());
+ }
+
+ /* */
+ Mq(const Mq&) = delete;
+ Mq& operator=(const Mq&) = delete;
+
+
+ /* 发送消息 */
+ void send(std::string &msg)
+ {
+ if (msg.size() + 1 > msglen) /* over the len */
+ throw std::length_error("Message queue Send Length over");
+
+ mqp->send(msg.c_str(), msg.size() + 1, 0); /* include \0 */
+ }
+
+ /* 尝试接收消息 */
+ void recv(sf_t success, ef_t notyet) {
+
+ auto data = std::make_unique(msglen); /* 接收缓冲区 */
+ unsigned int priority; /* 优先级 */
+ bip::message_queue::size_type recvd_size;
+
+ try { /* try_receive()返回bool类型 */
+ auto r = mqp->try_receive(
+ data.get(), msglen*sizeof(char),
+ recvd_size, priority
+ );
+
+ if (r) /* 成功接收到数据 */
+ success(data.get());
+
+ else /* 没有收到数据 */
+ notyet();
+ }
+
+ catch (std::exception &exp) {
+ std::cerr << "exception type: " << typeid(exp).name() << std::endl;
+ std::cerr << "exception message: " << exp.what() << std::endl;
+ }
+ }
+
+private:
+
+ /* */
+ std::unique_ptr mqp;
+ std::string name;
+ size_t msglen=0, msgcnt=0;
+ int mode;
+};
+}
diff --git a/core/include/tt/Pipe.h b/core/include/tt/Pipe.h
new file mode 100644
index 0000000..f6a6c4e
--- /dev/null
+++ b/core/include/tt/Pipe.h
@@ -0,0 +1,157 @@
+#pragma once
+#include
+#include
+#include
+#include /* open() */
+#include /* mkfifo() */
+#include
+
+namespace qing {
+
+/* 20260309(qing): 该类不会抛出异常 */
+class Pipe{
+public:
+ static const int CREATOR = 1;
+ static const int USER =2;
+ static const ssize_t PIPE_MAX_LEN = 2048;
+ Pipe(const std::string& path, int mode)
+ : fd(-1), isCreator(mode == CREATOR) {
+ std::string real_path = "/tmp/pst-";
+ real_path += path;
+ fifo_path = real_path;
+ if (isCreator && mkfifo(fifo_path.c_str(), 0666) == -1 && errno != EEXIST) /* wr_wr_wr */
+ perror("mkfifo"); /* 文件已存在是正常情况,其他错误才需要处理 */
+ }
+
+ ~Pipe() {
+ /* 如果打开了文件,则关闭文件 */
+ if (fd != -1) close(fd);
+ /**********************/
+ /* 如果管道由该对象创建,就要负责清理 */
+ if (isCreator) unlink(fifo_path.c_str()); /* 创建者负责清理 */
+ }
+ Pipe(const Pipe&) = delete;
+ Pipe& operator=(const Pipe&) = delete;
+
+ /* 这里才是打开文件的指令 - 以读模式打开,可以非阻塞 */
+ bool openForRead(bool nonblock = false) {
+
+ /* 设置是否以非阻塞方式打开文件 */
+ int flags = O_RDONLY;
+ if (nonblock) {
+ flags |= O_NONBLOCK;
+ }
+
+ fd = open(fifo_path.c_str(), flags);
+
+ if (fd == -1) {
+ perror("open for read");
+ return false;
+ }
+
+ else {
+ FD_ZERO(&read_fds);
+ FD_SET(fd, &read_fds);
+ if (fd > max_fd) max_fd = fd;
+ return true;
+ }
+
+ }
+
+ /* 以写模式打开文件 */
+ bool openForWrite(/*bool nonblock = falsei*/) {
+
+ /* 写入管道是不需要阻塞/非阻塞的? */
+ int flags = O_WRONLY;
+ //if (nonblock) {
+ // flags |= O_NONBLOCK;
+ //}
+ fd = open(fifo_path.c_str(), flags);
+ if (fd == -1) {
+ perror("open for write");
+ return false;
+ }
+
+ else {
+ FD_ZERO(&write_fds);
+ FD_SET(fd, &write_fds);
+ if (fd > max_fd) max_fd = fd;
+ return true;
+ }
+
+ }
+
+ /* 写入管道,如果失败返回-1。成功返回写入的字符数。 */
+ ssize_t writePipe(const std::string &data) {
+ if (fd == -1) {
+ std::cerr << "Pipe not opened for writing" << std::endl;
+ return -1;
+ }
+ else {
+ return write(fd, data.c_str(), data.size());
+ }
+ }
+
+ /* 将探测与读取解耦,使用者可以自行决定要不要阻塞 */
+ bool waitForRead(int timeout_sec = 0, int timeout_usec = 0) {
+
+ /* 如果文件没打开,等待是失败的 */
+ if (fd == -1) return false;
+
+ fd_set temp_fds = read_fds;
+ struct timeval timeout = {timeout_sec, timeout_usec};
+
+ int ret = select(max_fd + 1, &temp_fds, nullptr, nullptr, &timeout);
+
+ if (ret == -1) {
+ perror("select");
+ return false;
+ }
+
+ else {
+ return ret > 0 && FD_ISSET(fd, &temp_fds);
+ }
+ }
+
+ /* 读取数据到字符串,返回实际读取的字节数 */
+ ssize_t readPipe(std::string *output) {
+
+ if (fd == -1) {
+ std::cerr << "Pipe not opened for reading" << std::endl;
+ return -1;
+ }
+
+ else
+
+ {
+
+ char buffer[PIPE_MAX_LEN];
+ ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
+ if (n >0) {
+ buffer[n] = '\0';
+ *output = buffer;
+ }
+
+ else if (n == 0) {
+ /* 管道写入端关闭 */
+ *output = "";
+ }
+
+ else {
+ perror("read");
+ }
+
+ return n;
+
+ }
+ }
+private:
+ std::string fifo_path;
+ int fd;
+ bool isCreator;
+ fd_set read_fds;
+ fd_set write_fds;
+ fd_set except_fds;
+ int max_fd;
+};
+}
diff --git a/core/init.txt b/core/init.txt
new file mode 100644
index 0000000..26bbba8
--- /dev/null
+++ b/core/init.txt
@@ -0,0 +1,2 @@
+bash /home/qing/micro_servers/gateway/_run.sh
+bash /home/qing/micro_servers/static/_run.sh
diff --git a/core/src/main.cpp b/core/src/main.cpp
new file mode 100644
index 0000000..37a904e
--- /dev/null
+++ b/core/src/main.cpp
@@ -0,0 +1,306 @@
+/* ===============================================
+ * 通用子系统、进程机器、进程托管服务
+ *
+ *
+ * 【主函数文件】
+ *
+ * 直接子系统调用,或者启动一个pmc子系统(可以打开http)。
+ * ===============================================
+ */
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "logs/Logger.hpp"
+#include
+#include
+#include
+#include "tt/Pipe.h"
+#include "main/Tttask.hh"
+#include "main/HttpTask.hh"
+#include "main/pmc_mtd.hh"
+#include "main/subsys_call.hh"
+
+/* 中文模式 Chinese Mode */
+#include "cn/中文化.hpp"
+
+/* 静态区 - 存放全局变量 */
+static const char *PMC_VERSION = "0.0.10"; /* 版本号 */
+static const size_t MSGLEN = 2048; /* 单条消息的长度 */
+static const size_t MSGCNT = 100; /* 消息条数 */
+
+/* ---- 命名空间 ---- */
+using namespace qing;
+
+/* ---- 给命令行参数的命名空间取别名 ---- */
+namespace po = boost::program_options;
+
+
+void pmc_init(po::variables_map&); /* 初始化pmc并行机器 */
+void pmc_serve(po::variables_map&); /* pmc的http伺服器模式 */
+void parse_data_from_mq(std::string&); /* 解析消息队列收到的消息 */
+
+//-------------------------------------------------------------
+//-------------------------------------------------------------
+
+
+/*-------------------------------------------------------------------------*/
+/*-------------------------------------------------------------------------*/
+Cv_wait cv = Cv_wait(); /* 条件变量的等待机制(让主程序等待中断信号) */
+
+auto taskPool = std::vector>{}; /* 基层任务池 - !!! 非子进程 !!! */
+
+
+
+
+
+
+/*-------------------------------------------------------------------------*/
+
+
+/* 捕获中断信号,结束线程并且退出 */
+void signalHandler(int signum)
+{
+ LOG_INFO("收到终止信号,准备停止服务器...");
+ cv.WakeCv(); /* 唤醒条件信号即关闭程序 */
+ //if (server) server->stop(); /* TODO: 封装成ITask */
+}
+
+/*---------------- SIGNAL ACTION ----------------*/
+//
+/* 对信号的响应行为 TODO: 我应该系统地学习一下这个库 */
+void set_signal_action() {
+
+ /* 该结构体用于描述信号的处理方式 */
+ struct sigaction sa;
+
+
+ /* 绑定处理函数 */
+ sa.sa_handler = signalHandler;
+
+ /*
+ * 清空并初始化一个信号掩码集 --------------> 用于指定哪些信号在当前或即将执行的信号处理函数期间应该被阻塞(位掩码)
+ * “在执行这个信号处理函数时,除了当前正在处理的信号外,还希望临时阻塞其他某些信号”
+ * 不阻塞其他信号
+ * 确保在执行期间没有其他特定的信号会被阻塞
+ * 防止处理过程中被其他信号中断
+ */
+ sigemptyset(&sa.sa_mask);
+
+ /*
+ * 用于设置信号处理函数的行为特性。
+ * 0 - 默认选项
+ * SA_NODEFER - 表示在执行信号处理函数时不允许其他信号被阻塞
+ * SA_RESETHAND - 在信号处理函数返回后,将信号的处理方式重置为默认
+ * SA_NOCLDSTOP - 对于子进程发送的停止信号,父进程不会停止。
+ * SA_NOCLDWAIT - 父进程在等待等待子进程终止时不会因为子进程发送信号而收到通知
+ * SA_SIGINFO - 使用扩展的信号信息,信号处理函数接收三个参数而不是一个
+ */
+ sa.sa_flags = 0;
+
+ /* 注册信号 */
+ sigaction(SIGINT, &sa, nullptr); /* Ctrl + C */
+ sigaction(SIGTERM, &sa, nullptr); /* kill 或 systemctl stop */
+
+}
+
+/*-------------------------------------------------------------------------*/
+/*-------------------------------------------------------------------------*/
+/* 入口函数 */
+int main(int argc, char** argv) {
+
+ /*------------------------------*/
+ /* 设置信号行为*/
+ set_signal_action();
+
+ /*------------------------------*/
+ /* 解析命令行参数 */
+ po::options_description desc("pmc subsystem start options");
+ desc.add_options() /* 定义选项 */
+ ("help,h", "display help message") /* 帮助菜单 */
+ ("version,v", "display version message") /* 显示版本 */
+ /******** 子系统调用模式 *********/
+ ("send,s", po::value(), "send a message to pmc sys") /* 输入目标pid */
+ ("exec", po::value(), "message body") /* 启动一个进程 */
+ ("list", "list process all run") /* 列出运行中的进程 */
+ ("kill", po::value(), "kill a process") /* 杀死一个进程 */
+ /********* 子系统服务模式 ********/
+ ("init,i", po::value(), "self-init list") /* 输入自启动列表 */
+ ("serve", po::value(), "Run as http server"); /* 启用http伺服器 */
+
+ /* 参数变量映射关系 */
+ po::variables_map vm;
+
+ try { /* 开始解析 */
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ po::notify(vm);
+ if (vm.count("help")) { /* 获取帮助页面 */
+ std::cout << desc << std::endl;
+ std::cout << "--------- API MAP ---------" << std::endl;
+ std::cout << "Available endpoints:" << std::endl;
+ std::cout << " POST /list?target=optional" << std::endl;
+ std::cout << " POST /exec?command=ls&target=optional" << std::endl;
+ std::cout << " POST /kill?pid=1234&target=optional" << std::endl;
+ return 0;
+ }
+ if (vm.count("version")) { /* 获取版本信息 */
+ std::cout << PMC_VERSION << std::endl;
+ return 0;
+ }
+ }
+
+ catch (const std::exception& e) {
+ std::cerr << "ERROR: " << e.what() << std::endl;
+ std::cerr << "using --help to check options message" << std::endl;
+ throw e;
+ }
+
+ /*----------------------------------------*/
+
+ if ( vm.count("send") && vm.count("exec")) {
+ auto send = vm["send"].as();
+ auto exec = vm["exec"].as ();
+ auto msg = subsys_call::send_start_and_recv_pipe(send, exec);
+ std::cout << msg << std::endl;
+ return 0;
+ }
+
+ else if ( vm.count("send") && vm.count("list")){
+ auto send = vm["send"].as ();
+ auto msg = subsys_call::send_list_and_recv_pipe(send);
+ std::cout << msg << std::endl;
+ return 0;
+ }
+
+ else if (vm.count("send") && vm.count("kill")) {
+ auto send = vm["send"].as ();
+ auto kill = vm["kill"].as();
+ auto msg = subsys_call::send_kill_and_recv_pipe(send, kill);
+ std::cout << msg << std::endl;
+ return 0;
+ }
+
+ /* 初始化日志模块 */
+ Logger::getInstance().init(LogLevel::DEBUG, true);
+
+
+ /* 列表自启动 */
+ if (vm.count("init")){
+ std::string path = vm["init"].as();
+ pmc_mtd::parse_self_init_list(path);
+ }
+
+
+ /**********************************************/
+
+ /* TODO: 抽象出来 */
+ if (vm.count("serve"))
+ pmc_serve(vm);
+
+
+ /* pmc初始化函数 */
+ pmc_init(vm);
+
+ /*
+ * 主线程等待
+ *
+ * 触发器在信号处理那里
+ */
+ cv.Wait();
+
+ /* 主线程被唤醒,停止所有任务 */
+ for (auto& task: taskPool) {
+ task->stop();
+ }
+
+
+}
+
+
+
+
+/*-----------------------------------------------------------------------------*/
+/* 初始化子系统 即是启动通信 */
+void pmc_init(po::variables_map& vm) {
+
+ /*-------------------*/
+ auto ttt = std::make_shared (MSGLEN, MSGCNT,
+ [](const char *data) { /* 处理收到的数据 */
+ auto json_str = std::string(data);
+ parse_data_from_mq(json_str);
+ });
+ ttt->start();
+ taskPool.push_back(ttt);
+}
+
+/* http伺服器模式(只监听本地)TODO: 集成为ITask */
+void pmc_serve(po::variables_map& vm)
+{
+ int port = vm["serve"].as();
+ auto server = std::make_shared (port, [](pmc::net::HttpServer& server_) {
+ process_http_server::registerRoutes(server_);
+ });
+ server->start();
+ taskPool.push_back(server);
+
+}
+
+
+
+
+
+/* 解析从消息队列中接收到的数据,运行在服务端 */
+void parse_data_from_mq(std::string& json_str)
+try {
+ boost::json::value jv = boost::json::parse(json_str);
+ std::string namepipe = jv.at("pipe").as_string().c_str();
+ std::string typ = jv.at("type").as_string().c_str();
+ auto pipe = Pipe(namepipe, Pipe::USER);
+ pipe.openForWrite();
+
+
+ if (typ == "list") {
+ auto msg = pmc_mtd::list();
+ pipe.writePipe(msg);
+ return;
+ }
+
+ else if (typ == "kill") {
+ int trg = jv.at("kill").as_int64();
+ auto flag = pmc_mtd::kill(trg);
+ std::string msg = flag ? "OK" : "Nope";
+ pipe.writePipe(msg);
+ return;
+ }
+
+ else if (typ == "exec"){
+ std::string cmd = jv.at("exec").as_string().c_str();
+ std::string msg = (pmc_mtd::exec(cmd)) ? "OK" : "ERR";
+ pipe.writePipe(msg);
+ return;
+ }
+}
+
+/* 捕获异常后,仅仅只是打印出来? */
+catch (std::exception &exp) {
+ std::cerr << "Exception at: parse_data_from_mq()" << std::endl;
+ std::cerr << "Exception type: " << typeid(exp).name() << std::endl;
+ std::cerr << "Exception info: " << exp.what() << std::endl;
+}
+
+
+
diff --git a/core/src/main/HttpTask.cpp b/core/src/main/HttpTask.cpp
new file mode 100644
index 0000000..acae6de
--- /dev/null
+++ b/core/src/main/HttpTask.cpp
@@ -0,0 +1,347 @@
+#include
+#include
+#include
+#include "main/HttpTask.hh"
+#include "main/pmc_mtd.hh"
+#include "main/subsys_call.hh"
+
+using namespace qing;
+namespace qing {
+
+
+ /* -------- HttpTask -------- */
+
+ HttpTask::HttpTask(int port, std::function handler)
+ : port(port), handler(handler) {
+ this->th = std::make_unique ();
+ init_thread();
+ }
+
+ bool HttpTask::isRunning() {
+ auto stat = th->check();
+ return !(stat == Fsm::Stat::STOP || stat == Fsm::Stat::SHUT);
+ }
+
+
+ void HttpTask::start() {
+ if (!this->isRunning()) {
+ th->Activate(); /* FIXME: 这里获取了资源,不知道会不会造成内存泄漏 */
+ th->WaitStart(); /* TODO: add timeout 增加超时 */
+ }
+ }
+
+ void HttpTask::stop() {
+ this->server->stop();
+ if (this->isRunning())
+ th->WaitClose();
+ }
+
+ void HttpTask::init_thread() {
+
+ /* 构造通信线程 */
+ this->th = std::make_unique ();
+
+ /* stop callback 静止事件 */
+ this->th->set_stop( [](Thread& th) -> void {
+ /* 由线程提供的等待状态机发生改变信号的方法 */
+ th.suspend();
+ });
+
+
+ /* start callback 唤醒事件 */
+ this->th->set_wake( [this](Thread& th) -> void {
+ this->server = std::make_unique ("127.0.0.1", port, "server.crt", "server.key", 4);
+ handler(*this->server);
+ th.run();
+
+ this->server->start(); /* 这里包含了端口启动提示符输出 */
+ this->server->run(); /* 堵死线程,等待服务器运行结束 */
+ });
+
+
+ /* loop callback 循环事件 */
+ this->th->set_loop( [this](Thread& th) -> void {
+ /* 如果服务器是主动退出的 */
+ th.stop(); /* 停止线程,防止跌入死循环 */
+ });
+
+
+ /* clean callback 清理事件 */
+ this->th->set_clear( [this] (Thread& th) -> void {
+ this->server.reset();;
+ });
+
+ }
+
+
+/*==============================================================*/
+/* 这些是尚未整理的工具 */
+
+/* --------------------------- */
+/* json字符串转boost.ptree
+ * FIXME: 这个方法好像在ProcessManagerService进程托管服务中集成了*/
+boost::property_tree::ptree parseJsonToPtree(const std::string& jsonStr) {
+ boost::property_tree::ptree pt;
+ try {
+ std::stringstream ss(jsonStr);
+ boost::property_tree::read_json(ss, pt);
+ } catch (const boost::property_tree::json_parser_error& e) {
+ // 解析失败处理
+ std::cerr << "JSON parse error: " << e.what() << std::endl;
+ }
+ return pt;
+}
+
+/* --------------------------- */
+/* url 解码 */
+static std::string url_decode(const std::string& str) {
+ std::string result;
+ std::istringstream iss(str);
+ char ch;
+
+ while (iss.get(ch)) {
+ if (ch == '%') {
+ int hex;
+ if (iss >> std::hex >> hex) {
+ result += static_cast(hex);
+ }
+ } else if (ch == '+') {
+ result += ' ';
+ } else {
+ result += ch;
+ }
+ }
+ return result;
+}
+
+/*==============================================================*/
+
+
+/**
+ * @brief 进程托管服务 - 相关模块
+ *
+ * 提供进程的列表、执行和终止功能
+ * TODO(20260629-qing): 将这个模块合入HttpTask类模块
+ */
+
+namespace process_http_server {
+
+ /* ---- 注册POST路由 ---- */
+ void registerRoutes(pmc::net::HttpServer& server) {
+ server.post("/list", [](const auto& req, const auto& params) {
+ return handleList(req, params);
+ });
+
+ server.post("/exec", [](const auto& req, const auto& params) {
+ return handleExec(req, params);
+ });
+
+ server.post("/kill", [](const auto& req, const auto& params) {
+ return handleKill(req, params);
+ });
+ }
+
+ /* ---- 解析json ---- */
+ boost::property_tree::ptree parseJsonBody(const std::string& body) {
+ boost::property_tree::ptree pt;
+ try {
+ std::stringstream ss(body);
+ boost::property_tree::read_json(ss, pt);
+ }
+ catch (...) {
+ /* ---- JSON解析失败,返回空树 ---- */
+ }
+ return pt;
+ }
+
+ std::string buildJsonResponse(bool success, const std::string& message,
+ const boost::property_tree::ptree& data) {
+ boost::property_tree::ptree response;
+ response.put("success", success);
+ response.put("message", message);
+ if (!data.empty()) {
+ response.add_child("data", data);
+ }
+
+ std::stringstream ss;
+ boost::property_tree::write_json(ss, response);
+ return ss.str();
+ }
+
+ std::string getTarget(const std::unordered_map& params) {
+ auto it = params.find("target");
+ if (it != params.end())
+ return url_decode(it->second); // <--- 这里
+ return "";
+ }
+
+ std::string getExecCommand(const std::unordered_map& params) {
+ auto it = params.find("command");
+ if (it != params.end())
+ return url_decode(it->second); // <--- 这里
+ return "";
+ }
+
+ int getPid(const std::unordered_map& params) {
+ auto it = params.find("pid");
+ if (it != params.end()) {
+ std::string decoded = url_decode(it->second); // <--- 这里
+ return std::stoi(decoded);
+ }
+ return -1;
+ }
+
+ http::response handleList(
+ const http::request& req,
+ const std::unordered_map& params) {
+
+ http::response res;
+ res.version(req.version());
+ res.set(http::field::content_type, "application/json");
+
+ try {
+ std::string target = getTarget(params);
+
+ std::string result = listProcesses(target);
+ boost::property_tree::ptree data = parseJsonToPtree(result);
+
+ res.result(http::status::ok);
+ res.body() = buildJsonResponse(true, "Process list retrieved successfully", data);
+ }
+
+ catch (const std::exception& e) {
+ res.result(http::status::internal_server_error);
+ res.body() = buildJsonResponse(false, std::string("Error: ") + e.what());
+ }
+
+ res.prepare_payload();
+ return res;
+ }
+
+ http::response handleExec(
+ const http::request& req,
+ const std::unordered_map& params) {
+
+ http::response res;
+ res.version(req.version());
+ res.set(http::field::content_type, "application/json");
+
+ try {
+ std::string target = getTarget(params);
+ std::string command = getExecCommand(params);
+
+ if (command.empty()) {
+ // 尝试从POST body中获取command
+ auto body_json = parseJsonBody(req.body());
+ command = body_json.get("command", "");
+ }
+
+ if (command.empty()) {
+ res.result(http::status::bad_request);
+ res.body() = buildJsonResponse(false, "Missing required parameter: command");
+ res.prepare_payload();
+ return res;
+ }
+
+ // 实现命令执行逻辑
+ std::string result = execCommand(command, target);
+
+ boost::property_tree::ptree data;
+ data.put("command", command);
+ data.put("output", result);
+
+ res.result(http::status::ok);
+ res.body() = buildJsonResponse(true, "Command executed successfully", data);
+ }
+
+ catch (const std::exception& e) {
+ res.result(http::status::internal_server_error);
+ res.body() = buildJsonResponse(false, std::string("Error: ") + e.what());
+ }
+
+ res.prepare_payload();
+ return res;
+ }
+
+ http::response handleKill(
+ const http::request& req,
+ const std::unordered_map& params) {
+
+ http::response res;
+ res.version(req.version());
+ res.set(http::field::content_type, "application/json");
+
+ try {
+ std::string target = getTarget(params);
+ int pid = getPid(params);
+
+ if (pid <= 0 && !req.body().empty()) {
+ // 尝试从POST body中获取pid
+ auto body_json = parseJsonBody(req.body());
+ pid = body_json.get("pid", -1);
+ }
+
+ if (pid <= 0) {
+ res.result(http::status::bad_request);
+ res.body() = buildJsonResponse(false, "Missing or invalid parameter: pid");
+ res.prepare_payload();
+ return res;
+ }
+
+ bool success = killProcess(pid, target);
+
+ if (success) {
+ boost::property_tree::ptree data;
+ data.put("pid", pid);
+ res.result(http::status::ok);
+ res.body() = buildJsonResponse(true, "Process terminated successfully", data);
+ } else {
+ res.result(http::status::internal_server_error);
+ res.body() = buildJsonResponse(false, "Failed to terminate process");
+ }
+ }
+
+ catch (const std::exception& e) {
+ res.result(http::status::internal_server_error);
+ res.body() = buildJsonResponse(false, std::string("Error: ") + e.what());
+ }
+
+ res.prepare_payload();
+ return res;
+ }
+
+ // 如果target为空,在本机执行
+ // 否则在目标服务器执行
+ std::string listProcesses(const std::string& target)
+ {
+ if (target == "")
+ return pmc_mtd::list();
+ else
+ return subsys_call::send_list_and_recv_pipe(target);
+ }
+
+ std::string execCommand(const std::string& command, const std::string& target)
+ {
+ if (target == "")
+ return pmc_mtd::exec(command) ? "OK" :"ERR";
+ else
+ return subsys_call::send_start_and_recv_pipe(target, command); /* 发送启动命令并且接收回复 */
+ }
+
+ bool killProcess(int pid, const std::string& target)
+ {
+ if (target == "")
+ return pmc_mtd::kill(pid);
+ else
+ return subsys_call::send_kill_and_recv_pipe(target, pid) == "OK";
+ }
+
+
+}
+
+
+
+
+}
+
+
diff --git a/core/src/main/PPool.cpp b/core/src/main/PPool.cpp
new file mode 100644
index 0000000..b5eacb3
--- /dev/null
+++ b/core/src/main/PPool.cpp
@@ -0,0 +1,61 @@
+#include
+#include
+#include "main/PPool.hh"
+
+namespace qing {
+
+ void PPool::crtp(const std::string& cmd) try
+ {
+ auto pt = std::make_shared(cmd);
+ pt->start(); /* 直接创建了进程丢进容器 */
+ pool.push_back(pt);
+ }
+
+ /* 如果boost的子进程模块报错,表示子进程创建失败? */
+ catch (boost::system::system_error &exp) {
+ std::cerr << "Failed to execute this command: " << cmd << std::endl;
+ }
+
+
+ void PPool::clr() {
+ auto it = --pool.end(); /* 由最后一个元素开始 */
+ for (; it != pool.begin(); --it) /* 回溯遍历 */
+ if (!(*it)-> isRunning()) { /* 如果任务已经终止 */
+ auto tmp= it; /* 储存当前位置 */
+ it++; /* 返回上一个结点 */
+ pool.erase(tmp); /* 自动释放终止的节点 */
+ }
+
+ /* 循环结束时it == begin(),如果容器为空则end() == begin() */
+ if (pool.size() > 0 && !(*it)->isRunning()) /* */
+ pool.erase(it); /* 如果end() == begin(),此步将会试图删除哨兵 */
+ }
+
+ void PPool::kill(int idx) {
+
+
+ /* 从头部向后计数idx */
+ auto it = pool.begin();
+ int i = 0;
+ for (; i < idx && it != pool.end(); ++i, ++it);
+
+ if (it != pool.end()) { /* 如果找到了目标(因到达idx而停止)(计数器没有指向尾节点) */
+ (*it)->stop(); /* 关闭当前任务 */
+ pool.erase(it); /* 从容器中移除当前任务 */
+ }
+
+ /* 因抵达终点而停下(下标越界) */
+ else {
+ throw std::out_of_range("PPool::kill()");
+ }
+
+ }
+
+ ProcessTask& PPool::operator[](const size_t idx) {
+ auto it = pool.begin();
+ for (int i = 0; i < idx; ++it, ++i) /* 遍历idx次 */
+ if (it == pool.end()) /* 如果该节点是尾部哨兵(下标越界) */
+ throw std::out_of_range("PPool::operator[]()");
+ return **it; /* 返回当前节点 */
+ }
+}
\ No newline at end of file
diff --git a/core/src/main/ProcessTask.cpp b/core/src/main/ProcessTask.cpp
new file mode 100644
index 0000000..d485971
--- /dev/null
+++ b/core/src/main/ProcessTask.cpp
@@ -0,0 +1,30 @@
+#include
+#include "main/ProcessTask.hh"
+
+#ifdef __NEW_VER
+namespace qing {
+ bool ProcessTask::isRunning() {
+ return p && p->running(exit_code);
+ }
+ int ProcessTask::getExitCode() {
+ return exit_code.value();
+ }
+ void ProcessTask::start() {
+ if (!isRunning()) {
+ auto ccmd = boost::process::v2::shell(cmd);
+ auto exe = ccmd.exe();
+ auto args = ccmd.args();
+ this->p = std::make_unique(ctx, exe, args);
+ }
+ }
+ void ProcessTask::stop() {
+ p->terminate(exit_code);
+ if (exit_code) {
+ std::cerr << "杀死进程失败: " << exit_code.message() << std::endl;
+ }
+ else {
+ p.reset();
+ }
+ }
+}
+#endif
diff --git a/core/src/main/Tttask.cpp b/core/src/main/Tttask.cpp
new file mode 100644
index 0000000..713d7da
--- /dev/null
+++ b/core/src/main/Tttask.cpp
@@ -0,0 +1,69 @@
+#include
+#include
+#include
+#include
+#include "main/Tttask.hh"
+
+namespace qing {
+ Tttask::Tttask(const size_t msglen, size_t msgcnt, const sf_t callback)
+ : msglen(msglen), msgcnt(msgcnt) {
+ this->callback = std::make_unique(callback); /* FIXME: 使用指针似乎有所不妥 */
+ init_thread();
+ }
+
+ void Tttask::start() {
+ if (!this->isRunning()) {
+
+ th->Activate(); /* FIXME: 这里获取了资源,不知道会不会造成内存泄漏 */
+ th->WaitStart(); /* TODO: add timeout 增加超时 */
+ }
+ }
+
+ bool Tttask::isRunning() {
+ auto stat = th->check();
+ return !(stat == Fsm::Stat::STOP
+ || stat == Fsm::Stat::SHUT);
+ }
+
+ void Tttask::init_thread() {
+
+ /* 构造通信线程 */
+ this->th = std::make_unique ();
+
+ /* stop callback 静止事件 */
+ this->th->set_stop( [](Thread& th) -> void {
+
+ /* 由线程提供的等待状态机发生改变信号的方法 */
+ th.suspend();
+ });
+
+ /* start callback 唤醒事件 */
+ this->th->set_wake( [this](Thread& th) -> void {
+ name = std::to_string(getpid()); /* 以进程名构建消息队列 */
+ mq = std::make_unique (name, msglen, msgcnt, Mq::CREATOR);
+ th.run();
+ });
+
+
+ /* loop callback 循环事件 */
+ this->th->set_loop( [this](Thread& th) -> void {
+
+ /* 第一个是接收成功的处理事件,第二个是接收失败的处理事件
+ *
+ * TODO: 作为参数传入延时
+ * TODO: 使用标准库的线程延时*/
+ mq->recv(*callback, []() { usleep(10000); });
+
+ });
+
+
+ /* clean callback 清理事件 */
+ this->th->set_clear( [this] (Thread& th) -> void {
+
+ /* 直接重置指针 */
+ mq.reset();
+ });
+
+
+ }
+}
diff --git a/core/src/main/pmc_mtd.cpp b/core/src/main/pmc_mtd.cpp
new file mode 100644
index 0000000..7ac9b6c
--- /dev/null
+++ b/core/src/main/pmc_mtd.cpp
@@ -0,0 +1,132 @@
+
+
+#include
+#include
+#include
+#include "main/PPool.hh"
+#include "main/pmc_mtd.hh"
+
+namespace qing {
+
+/* -------- 用于存放子进程的进程池 -------- */
+static PPool ppool;
+
+/*-------------------------------------------------------------------------*/
+
+/* --------【pmc method子进程操作】集合 -------- */
+namespace pmc_mtd {
+
+/*
+ * 列举出所有子进程。
+ *
+ * {
+ * "pipe": "",
+ * "type": "list",
+ * } */
+auto list() -> std::string {
+ boost::json::array processes;
+
+ /* 遍历子进程池
+ *
+ * FIXME: 子进程池的迭代器完成后,改为使用for-in迭代 */
+ //ppool.clr() /* 保留已经跑完的进程,因为可能会涉及到输出的提取 *?
+ for (int i = 0; i < ppool.size(); ++i) {
+ processes.push_back({ /* 向json中推入对象 */
+ {"index", i},
+ {"pid", ppool[i].pid()},
+ {"status", ppool[i].check()}
+ });
+ }
+
+ /* 返回序列化的json对象 */
+ return boost::json::serialize(processes);
+}
+
+/*
+ * 删除一个子进程,需要提供pid
+ *
+ * {
+ * "pipe": "",
+ * "type": "kill",
+ * "kill":
+ * } */
+auto kill(const int pid) -> bool {
+
+ /* 遍历子进程池对比pid */
+ for (int i=0; i",
+ * "type": "exec",
+ * "exec": ""
+ * } */
+auto exec(const std::string& cmd) -> bool try
+{
+ //ppool.clr(); /* 保留跑完的子进程 */
+ ppool.crtp(cmd);
+ return true; /* 成功返回逻辑真 */
+}
+
+/* 如果出现任何异常,返回假 */
+catch(std::exception& exp) {
+ return false;
+}
+
+
+
+/* 解析自启动列表、添加自启动项
+ *
+ * 如果在解析过程中出错,只是打印异常? */
+void parse_self_init_list(std::string &path)
+try {
+
+ std::ifstream file(path);
+ if (!file.is_open()) { /* ---- 没能打开自启动文件 ---- */
+ std::cerr << "Failed to open self-init list" << std::endl;
+ return;
+ }
+
+ std::string row = "";
+ char ch;
+ while (file.get(ch))
+
+ if (ch == '\n') {
+
+ auto pos = row.find("#");
+ if (pos != -1)
+ row = row.substr(0, pos);
+ if (row != "") { /* trim() */
+ ppool.clr();
+ ppool.crtp(row); /* 创建进程 */
+ row = "";
+ }
+ }
+
+ else row += ch;
+
+ file.close();
+
+}
+catch (std::exception &exp) {
+ std::cerr << "Exception at: parse_self_init_list()" << std::endl;
+ std::cerr << "Exception type: " << typeid(exp).name() << std::endl;
+ std::cerr << "Exception info: " << exp.what() << std::endl;
+}
+
+
+}
+
+
+
+
+}
diff --git a/core/src/main/subsys_call.cpp b/core/src/main/subsys_call.cpp
new file mode 100644
index 0000000..9a7d13a
--- /dev/null
+++ b/core/src/main/subsys_call.cpp
@@ -0,0 +1,163 @@
+
+#include "iostream"
+#include "fstream"
+#include
+#include "tt/Mq.h"
+#include "tt/Pipe.h"
+#include "main/subsys_call.hh"
+
+namespace qing {
+namespace subsys_call {
+
+
+/*-------------------------------------------------------------------------*/
+
+
+/* -------- 向pmc的消息队列发送启动命令并且从管道接收回复 -------- */
+std::string send_start_and_recv_pipe(const std::string& name_mq, const std::string& exec)
+try {
+
+ auto name_pipe = std::to_string(getpid());
+ auto mq = Mq(name_mq, 2048, 100, Mq::USER); /* 放在这里避免管道文件的残留 */
+
+ boost::json::object obj;
+ obj["pipe"] = name_pipe;
+ obj["type"] = "exec";
+ obj["exec"] = exec;
+ auto jsonstr = boost::json::serialize(obj);
+
+
+ auto pipe = Pipe(name_pipe, Pipe::CREATOR); /* FIXME: 创建管道文件到/tmp下面 */
+ if (!pipe.openForRead(true)) {
+ std::cerr << "Failed to open pipe" << std::endl;
+ return "ERR";
+ }
+
+ mq.send(jsonstr);
+ if (!pipe.waitForRead(1, 0)) {
+ std::cerr << "Pipe Read Timeout" << std::endl;
+ return "ERR";
+ }
+
+ std::string res = "";
+ if (pipe.readPipe(&res) < 0) {
+ std::cerr << "Failed to read pipe" << std::endl;
+ return "ERR";
+ }
+
+ return res;
+}
+
+//catch (boost::interprocess::interprocess_exception &exp) {
+// std::cerr << "Target Pmc Is Not Found" << std::endl;
+// return 1;
+//}
+
+catch (std::exception &exp) {
+ std::cerr << "Exception at: send_start_and_recv_pipe()" << std::endl;
+ std::cerr << "Exception type: " << typeid(exp).name() << std::endl;
+ std::cerr << "Exception info: " << exp.what() << std::endl;
+ return "ERR";
+}
+
+
+
+/* -------- 向目标子系统发送列举命令并收集结果 -------- */
+std::string send_list_and_recv_pipe(const std::string& name_mq)
+try {
+
+ auto name_pipe = std::to_string(getpid());
+ auto mq = Mq(name_mq, 2048, 100, Mq::USER);
+
+ boost::json::object obj;
+ obj["pipe"] = name_pipe;
+ obj["type"] = "list";
+ auto jsonstr = boost::json::serialize(obj);
+ auto pipe = Pipe(name_pipe, Pipe::CREATOR);
+
+ if (!pipe.openForRead(true)) {
+ std::cerr << "Failed to open pipe" << std::endl;
+ return "ERR";
+ }
+
+
+ mq.send(jsonstr);
+ if (!pipe.waitForRead(1, 0)) {
+ std::cerr << "Pipe Read Timeout" << std::endl;
+ return "ERR";
+ }
+
+ std::string res = "";
+ if (pipe.readPipe(&res) < 0) {
+ std::cerr << "Failed to read pipe" << std::endl;
+ return "ERR";
+ }
+
+
+ return res;
+
+}
+
+//catch (boost::interprocess::interprocess_exception &exp) {
+// std::cerr << "Target Pmc Is Not Found" << std::endl;
+// return 1;
+//}
+
+catch (std::exception &exp) {
+ std::cerr << "Exception at: send_list_and_recv_pipe()" << std::endl;
+ std::cerr << "Exception type: " << typeid(exp).name() << std::endl;
+ std::cerr << "Exception info: " << exp.what() << std::endl;
+ return "ERR";
+}
+
+/* -------- 删除操作调用 -------- */
+std::string send_kill_and_recv_pipe(const std::string& name_mq, const int kill)
+try{
+
+ auto name_pipe = std::to_string(getpid());
+ auto mq = Mq(name_mq, 2048, 100, Mq::USER);
+
+ boost::json::object obj;
+ obj["pipe"] = name_pipe;
+ obj["type"] = "kill";
+ obj["kill"] = kill;
+ auto jsonstr = boost::json::serialize(obj);
+
+ auto pipe = Pipe(name_pipe, Pipe::CREATOR);
+ if (!pipe.openForRead(true)) {
+ std::cerr << "Failed to open pipe" << std::endl;
+ return "ERR";
+ }
+
+ mq.send(jsonstr);
+ if (!pipe.waitForRead(1, 0)) {
+ std::cerr << "Pipe Read Timeout" << std::endl;
+ return "ERR";
+ }
+
+ std::string res = "";
+ if (pipe.readPipe(&res) < 0) {
+ std::cerr << "Failed to read pipe" << std::endl;
+ return "ERR";
+ }
+ else return res;
+
+}
+
+/* 没有打开目标子系统的消息队列时,会触发这个异常
+ * 但是实际上这里捕获的是进程间通信通用异常(旧版) */
+//catch (boost::interprocess::interprocess_exception &exp) {
+// std::cerr << "Target Pmc Is Not Found" << std::endl;
+// return 1;
+//}
+
+/* 这些函数抛出异常后可能导致管道文件残留 */
+catch (std::exception &exp) {
+ std::cerr << "Exception at: send_kill_and_recv_pipe()" << std::endl;
+ std::cerr << "Exception type: " << typeid(exp).name() << std::endl;
+ std::cerr << "Exception info: " << exp.what() << std::endl;
+ return "ERR";
+}
+
+}
+}
diff --git a/gateway/.gitignore b/gateway/.gitignore
new file mode 100644
index 0000000..8b604b6
--- /dev/null
+++ b/gateway/.gitignore
@@ -0,0 +1,74 @@
+#PRJ
+*.db
+*.crt
+*.key
+
+# Prerequisites
+*.d
+
+# Compiled Object files
+*.slo
+*.lo
+*.o
+*.obj
+
+# Precompiled Headers
+*.gch
+*.pch
+
+# Linker files
+*.ilk
+
+# Debugger Files
+*.pdb
+
+# Compiled Dynamic libraries
+*.so
+*.dylib
+*.dll
+*.so.*
+
+
+# Fortran module files
+*.mod
+*.smod
+
+# Compiled Static libraries
+*.lai
+*.la
+*.a
+*.lib
+
+# Executables
+*.exe
+*.out
+*.app
+
+# Build directories
+build/
+Build/
+build-*/
+
+# CMake generated files
+CMakeFiles/
+CMakeCache.txt
+cmake_install.cmake
+#Makefile
+install_manifest.txt
+compile_commands.json
+
+# Temporary files
+*.tmp
+*.log
+*.bak
+*.swp
+
+# vcpkg
+vcpkg_installed/
+
+# debug information files
+*.dwo
+
+# test output & cache
+Testing/
+.cache/
diff --git a/gateway/LICENSE b/gateway/LICENSE
new file mode 100644
index 0000000..eee83e1
--- /dev/null
+++ b/gateway/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 dashun
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/gateway/Makefile b/gateway/Makefile
new file mode 100644
index 0000000..a6c49ef
--- /dev/null
+++ b/gateway/Makefile
@@ -0,0 +1,19 @@
+VERSION := 0.0.1
+APP_NAME := gateway
+INSTL_DIR := /usr/local/bin
+CPP := g++
+INCS := -I inc/
+MY_LIBS := -L/usr/lib -lus_http -lus_crypt
+LIBS := -lcurl -lssl -lsqlite3 -lz -lcrypto -lboost_json -lboost_program_options
+CPPFLAGS := --std=c++20 -pipe # -Wall -Werror
+BUILD_DIR = build
+$(shell mkdir -p $(BUILD_DIR))
+
+#--------
+all: $(BUILD_DIR)/$(APP_NAME).out
+$(BUILD_DIR)/$(APP_NAME).out: $(BUILD_DIR)/main.o
+ $(CPP) $^ $(LIBS) $(MY_LIBS) -o $@
+$(BUILD_DIR)/main.o: src/main.cpp
+ $(CPP) $(CPPFLAGS) -c $^ $(INCS) -o $@
+clear:
+ @rm -rvf build/
diff --git a/gateway/README.md b/gateway/README.md
new file mode 100644
index 0000000..3b71a42
--- /dev/null
+++ b/gateway/README.md
@@ -0,0 +1,7 @@
+# UniServe_gateway2
+US Framework gateway C++ version
+
+# Dependancy
+
+libboost
+libcurl
diff --git a/gateway/_gen.sh b/gateway/_gen.sh
new file mode 100644
index 0000000..bd188d6
--- /dev/null
+++ b/gateway/_gen.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+cd "$(dirname "$0")" || exit
+openssl req -x509 -newkey rsa:2048 -nodes -keyout server.key -out server.crt -days 365 -subj "/CN=localhost"
diff --git a/gateway/_run.sh b/gateway/_run.sh
new file mode 100644
index 0000000..df8a225
--- /dev/null
+++ b/gateway/_run.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+cd "$(dirname "$0")" || exit
+exec ./build/gateway.out -i example.ini #1>/dev/null
diff --git a/gateway/_set.sh b/gateway/_set.sh
new file mode 100644
index 0000000..95ae6ae
--- /dev/null
+++ b/gateway/_set.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+cd "$(dirname "$0")" || exit
+make clear && make $@
diff --git a/gateway/example.ini b/gateway/example.ini
new file mode 100644
index 0000000..2898c53
--- /dev/null
+++ b/gateway/example.ini
@@ -0,0 +1,9 @@
+[Server]
+address = 0.0.0.0
+port = 9201
+
+[Proxy]
+default = http://127.0.0.1:9200
+
+[Database]
+path = sqlite3.db
diff --git a/gateway/inc/Conf.hpp b/gateway/inc/Conf.hpp
new file mode 100644
index 0000000..6e8ce6c
--- /dev/null
+++ b/gateway/inc/Conf.hpp
@@ -0,0 +1,42 @@
+#pragma once
+#include
+#include
+#include
+#include
+namespace property_tree = boost::property_tree;
+using ptree = property_tree::ptree;
+namespace qing {
+
+ class ConfIni {
+ public:
+ ConfIni(const std::string &filename) {
+ try {
+ std::cout << "open and parse ini file: " << filename << std::endl;
+ property_tree::ini_parser::read_ini(filename, pt);
+ }
+ catch (const boost::property_tree::ini_parser_error& e) {
+ std::cerr << "INI parsing error: " << e.what() << std::endl;
+ throw IniConfigureFileParseException("INI parsing error!");
+ }
+ }
+
+ template
+ T get(const std::string &path, const T &_defaut) {
+ return pt.get(path, _defaut);
+ }
+
+ class IniConfigureFileParseException: public std::exception {
+ public:
+ explicit IniConfigureFileParseException(const std::string &msg)
+ : message(msg) {}
+ const char* what() const noexcept override {
+ return message.c_str();
+ }
+ private:
+ std::string message;
+ };
+
+ private:
+ ptree pt;
+ };
+}
diff --git a/gateway/inc/ExpBase.hpp b/gateway/inc/ExpBase.hpp
new file mode 100644
index 0000000..8531cf6
--- /dev/null
+++ b/gateway/inc/ExpBase.hpp
@@ -0,0 +1,402 @@
+#ifndef EXCEPTION_BASE_H
+#define EXCEPTION_BASE_H
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+/**
+ * @brief 通用异常基类
+ *
+ * 特性:
+ * 1. 完整的错误信息管理(错误码、消息、位置信息)
+ * 2. 支持异常链(嵌套异常)
+ * 3. 多态支持(clone、自定义消息)
+ * 4. 线程安全的 what() 缓存
+ * 5. 支持 C++20 source_location
+ */
+class ExceptionBase : public std::exception {
+public:
+ // ============ 构造函数 ============
+
+ explicit ExceptionBase(
+ int code = 0,
+ const std::string& message = "",
+ const std::source_location& location = std::source_location::current()
+ ) noexcept
+ : m_code(code)
+ , m_message(message)
+ , m_file(location.file_name())
+ , m_line(location.line())
+ , m_function(location.function_name())
+ , m_what_cache()
+ {
+ }
+
+ // 支持从字符串字面量构造
+ explicit ExceptionBase(
+ const std::string& message,
+ const std::source_location& location = std::source_location::current()
+ ) noexcept
+ : m_code(0)
+ , m_message(message)
+ , m_file(location.file_name())
+ , m_line(location.line())
+ , m_function(location.function_name())
+ , m_what_cache()
+ {
+ }
+
+ // ============ 拷贝和移动 ============
+
+ ExceptionBase(const ExceptionBase& other) noexcept
+ : std::exception(other)
+ , m_code(other.m_code)
+ , m_message(other.m_message)
+ , m_file(other.m_file)
+ , m_line(other.m_line)
+ , m_function(other.m_function)
+ , m_nested(other.m_nested ? other.m_nested->clone() : nullptr)
+ , m_what_cache()
+ {
+ }
+
+ ExceptionBase(ExceptionBase&& other) noexcept
+ : std::exception(std::move(other))
+ , m_code(other.m_code)
+ , m_message(std::move(other.m_message))
+ , m_file(std::move(other.m_file))
+ , m_line(other.m_line)
+ , m_function(std::move(other.m_function))
+ , m_nested(std::move(other.m_nested))
+ , m_what_cache(std::move(other.m_what_cache))
+ {
+ other.m_code = 0;
+ other.m_line = 0;
+ }
+
+ virtual ~ExceptionBase() noexcept = default;
+
+ // ============ 赋值运算符 ============
+
+ ExceptionBase& operator=(const ExceptionBase& other) noexcept {
+ if (this != &other) {
+ m_code = other.m_code;
+ m_message = other.m_message;
+ m_file = other.m_file;
+ m_line = other.m_line;
+ m_function = other.m_function;
+ m_nested = other.m_nested ? other.m_nested->clone() : nullptr;
+ m_what_cache.clear();
+ }
+ return *this;
+ }
+
+ ExceptionBase& operator=(ExceptionBase&& other) noexcept {
+ if (this != &other) {
+ m_code = other.m_code;
+ m_message = std::move(other.m_message);
+ m_file = std::move(other.m_file);
+ m_line = other.m_line;
+ m_function = std::move(other.m_function);
+ m_nested = std::move(other.m_nested);
+ m_what_cache = std::move(other.m_what_cache);
+ other.m_code = 0;
+ other.m_line = 0;
+ }
+ return *this;
+ }
+
+ // ============ 访问器 ============
+
+ int code() const noexcept { return m_code; }
+ const std::string& message() const noexcept { return m_message; }
+ const std::string& file() const noexcept { return m_file; }
+ int line() const noexcept { return m_line; }
+ const std::string& function() const noexcept { return m_function; }
+ const ExceptionBase* nested() const noexcept { return m_nested.get(); }
+
+ // ============ 异常链操作 ============
+
+ void set_nested(std::unique_ptr nested) noexcept {
+ m_nested = std::move(nested);
+ m_what_cache.clear();
+ }
+
+ template
+ void set_nested(const ExType& nested_ex) noexcept {
+ static_assert(std::is_base_of::value,
+ "ExType must inherit from ExceptionBase");
+ m_nested = std::make_unique(nested_ex);
+ m_what_cache.clear();
+ }
+
+ // ============ std::exception 接口 ============
+
+ const char* what() const noexcept override {
+ if (m_what_cache.empty()) {
+ build_what_message();
+ }
+ return m_what_cache.c_str();
+ }
+
+ // ============ 多态支持 ============
+
+ virtual std::unique_ptr clone() const {
+ return std::make_unique(*this);
+ }
+
+ // ============ 重新抛出 ============
+
+ [[noreturn]] void rethrow() const {
+ throw *this;
+ }
+
+protected:
+ // ============ 可重写的消息构建方法 ============
+
+ virtual std::string build_message() const {
+ std::string result;
+
+ // 错误码
+ if (m_code != 0) {
+ result += "[Error " + std::to_string(m_code) + "] ";
+ }
+
+ // 错误消息
+ result += m_message;
+
+ // 位置信息
+ if (!m_file.empty()) {
+ result += " (at " + m_file;
+ if (m_line > 0) {
+ result += ":" + std::to_string(m_line);
+ }
+ if (!m_function.empty()) {
+ result += " in " + m_function;
+ }
+ result += ")";
+ }
+
+ // 嵌套异常
+ if (m_nested) {
+ result += "\n Caused by: " + std::string(m_nested->what());
+ }
+
+ return result;
+ }
+
+private:
+ // ============ 内部方法 ============
+
+ void build_what_message() const noexcept {
+ try {
+ m_what_cache = build_message();
+ } catch (...) {
+ // 降级处理
+ m_what_cache = "Exception: " + m_message;
+ }
+ }
+
+private:
+ // ============ 成员变量 ============
+
+ int m_code;
+ std::string m_message;
+ std::string m_file;
+ int m_line;
+ std::string m_function;
+ std::unique_ptr m_nested;
+ mutable std::string m_what_cache;
+};
+
+// ============================================================================
+// 宏定义 - 方案二完整版
+// ============================================================================
+
+/**
+ * @brief 抛出指定类型的异常(自动添加 source_location)
+ *
+ * 适用场景:子类构造函数与 ExceptionBase 相同
+ *
+ * 使用示例:
+ * THROW_EX(NetworkException, 404, "Server not found")
+ * THROW_EX(DatabaseException, 100, "Connection timeout")
+ */
+#define THROW_EX(ExType, code, msg) \
+ throw ExType(code, msg, std::source_location::current())
+
+/**
+ * @brief 抛出异常(仅消息,不传错误码)
+ *
+ * 适用场景:子类支持只传消息的构造函数
+ *
+ * 使用示例:
+ * THROW_EX_MSG(ValidationException, "Invalid input data")
+ */
+#define THROW_EX_MSG(ExType, msg) \
+ throw ExType(msg, std::source_location::current())
+
+/**
+ * @brief 抛出异常(支持任意构造函数参数)
+ *
+ * 适用场景:子类有额外的构造函数参数
+ *
+ * 使用示例:
+ * // 子类定义
+ * class FileException : public ExceptionBase {
+ * public:
+ * FileException(int code, const std::string& msg,
+ * const std::string& filename,
+ * const std::source_location& loc = std::source_location::current())
+ * : ExceptionBase(code, msg, loc), m_filename(filename) {}
+ * };
+ *
+ * // 使用
+ * THROW_EX_CUSTOM(FileException, 404, "File not found", "/etc/config.txt")
+ */
+#define THROW_EX_CUSTOM(ExType, ...) \
+ throw ExType(__VA_ARGS__, std::source_location::current())
+
+/**
+ * @brief 抛出异常并携带嵌套异常
+ *
+ * 适用场景:需要保留原始异常信息
+ *
+ * 使用示例:
+ * try {
+ * connect_to_server();
+ * } catch (const NetworkException& e) {
+ * THROW_EX_NESTED(ServiceException, 500, "Service failed", e)
+ * }
+ */
+#define THROW_EX_NESTED(ExType, code, msg, nested_ex) \
+ do { \
+ auto ex = ExType(code, msg, std::source_location::current()); \
+ ex.set_nested(nested_ex); \
+ throw ex; \
+ } while(0)
+
+/**
+ * @brief 抛出异常并携带嵌套异常(支持自定义参数)
+ *
+ * 使用示例:
+ * THROW_EX_NESTED_CUSTOM(FileException, 500, "Read failed",
+ * original_ex, "/data/file.txt")
+ */
+#define THROW_EX_NESTED_CUSTOM(ExType, code, msg, nested_ex, ...) \
+ do { \
+ auto ex = ExType(code, msg, __VA_ARGS__, std::source_location::current()); \
+ ex.set_nested(nested_ex); \
+ throw ex; \
+ } while(0)
+
+/**
+ * @brief 检查条件,失败则抛出异常
+ *
+ * 使用示例:
+ * THROW_IF(ptr == nullptr, NullPointerException, 100, "Pointer is null")
+ * THROW_IF(data.empty(), ValidationException, 200, "Data cannot be empty")
+ */
+#define THROW_IF(cond, ExType, code, msg) \
+ do { \
+ if (cond) { \
+ THROW_EX(ExType, code, msg); \
+ } \
+ } while(0)
+
+/**
+ * @brief 检查条件,失败则抛出异常(仅消息)
+ */
+#define THROW_IF_MSG(cond, ExType, msg) \
+ do { \
+ if (cond) { \
+ THROW_EX_MSG(ExType, msg); \
+ } \
+ } while(0)
+
+/**
+ * @brief 检查条件,失败则抛出异常(自定义参数)
+ */
+#define THROW_IF_CUSTOM(cond, ExType, ...) \
+ do { \
+ if (cond) { \
+ THROW_EX_CUSTOM(ExType, __VA_ARGS__); \
+ } \
+ } while(0)
+
+/**
+ * @brief 检查条件,失败则抛出异常(带嵌套异常)
+ */
+#define THROW_IF_NESTED(cond, ExType, code, msg, nested_ex) \
+ do { \
+ if (cond) { \
+ THROW_EX_NESTED(ExType, code, msg, nested_ex); \
+ } \
+ } while(0)
+
+/**
+ * @brief 检查条件,失败则抛出异常(带嵌套异常和自定义参数)
+ */
+#define THROW_IF_NESTED_CUSTOM(cond, ExType, code, msg, nested_ex, ...) \
+ do { \
+ if (cond) { \
+ THROW_EX_NESTED_CUSTOM(ExType, code, msg, nested_ex, __VA_ARGS__); \
+ } \
+ } while(0)
+
+// ============================================================================
+// 辅助宏 - 用于格式化错误消息
+// ============================================================================
+
+/**
+ * @brief 格式化错误消息(使用流式语法)
+ *
+ * 使用示例:
+ * THROW_EX_FMT(NetworkException, 404, "Failed to connect to " << host << ":" << port)
+ */
+#define THROW_EX_FMT(ExType, code, msg_expr) \
+ do { \
+ std::ostringstream _oss; \
+ _oss << msg_expr; \
+ THROW_EX(ExType, code, _oss.str()); \
+ } while(0)
+
+/**
+ * @brief 格式化错误消息(使用 printf 风格)
+ *
+ * 使用示例:
+ * THROW_EX_PRINTF(NetworkException, 404, "Failed to connect to %s:%d", host.c_str(), port)
+ */
+#define THROW_EX_PRINTF(ExType, code, fmt, ...) \
+ do { \
+ char _buf[1024]; \
+ snprintf(_buf, sizeof(_buf), fmt, __VA_ARGS__); \
+ THROW_EX(ExType, code, std::string(_buf)); \
+ } while(0)
+
+/**
+ * @brief 条件检查 + 格式化消息
+ */
+#define THROW_IF_FMT(cond, ExType, code, msg_expr) \
+ do { \
+ if (cond) { \
+ THROW_EX_FMT(ExType, code, msg_expr); \
+ } \
+ } while(0)
+
+/**
+ * @brief 条件检查 + printf 风格格式化
+ */
+#define THROW_IF_PRINTF(cond, ExType, code, fmt, ...) \
+ do { \
+ if (cond) { \
+ THROW_EX_PRINTF(ExType, code, fmt, __VA_ARGS__); \
+ } \
+ } while(0)
+
+#endif // EXCEPTION_BASE_H
diff --git a/gateway/src/main.cpp b/gateway/src/main.cpp
new file mode 100644
index 0000000..d2c5262
--- /dev/null
+++ b/gateway/src/main.cpp
@@ -0,0 +1,523 @@
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include "ExpBase.hpp"
+#include "Conf.hpp"
+
+using namespace pmc::net;
+using namespace qing;
+namespace json = boost::json;
+namespace po = boost::program_options;
+
+constexpr const char *_VER = "0.2.1";
+
+
+class DatabaseException: public ExceptionBase {
+public:
+ using ExceptionBase::ExceptionBase;
+
+ std::string build_message() const override {
+ return "[Database]" + ExceptionBase::build_message();
+ }
+};
+
+class HttpException: public ExceptionBase {
+public:
+ HttpException(int code, const std::string& msg,
+ int http_status, const std::string& url,
+ const std::source_location& loc = std::source_location::current())
+ : ExceptionBase(code, msg, loc)
+ , m_http_status(http_status)
+ , m_url(url) {}
+ std::string build_message() const override {
+ return "[Http]" + ExceptionBase::build_message();
+ }
+ int status() const {
+ return m_http_status;
+ }
+ const std::string& url() const {
+ return m_url;
+ }
+private:
+ int m_http_status;
+ std::string m_url;
+};
+
+void db_init();
+void registerRoutes(HttpServer &server);
+
+http::response wrapperHttp(
+ const http::request& req,
+ const std::unordered_map& params,
+ HttpRequestHandler _main);
+
+http::response handleProxy(
+ const http::request& req,
+ const std::unordered_map& params,
+ const char *method
+);
+
+http::response handleLogin(
+ const http::request& req,
+ const std::unordered_map& params);
+
+http::response handleRegister(
+ const http::request& req,
+ const std::unordered_map& params);
+
+
+/* headers can't processed */
+bool is_special_header(const std::string &header);
+
+/* configure items */
+static std::string _ADDR;
+static int _PORT;
+static std::string _DEFT_URL;
+static std::string _DB_PATH;
+static std::string _DEFT_ADMIN_USER = "admin";
+static std::string _DEFT_ADMIN_PASS = "44112233";
+
+/* instance items */
+static std::unique_ptr _SERVE;
+static std::unique_ptr _KEYGEN;
+static std::unique_ptr _SQLDB;
+
+void signalHandler(int signum) {
+
+ std::cout << "Receive close signal, prepare to shutdown...\n";
+ if (_SERVE) {
+ _SERVE->stop();
+ }
+}
+
+void set_signal_action() {
+
+ struct sigaction sa;
+ sa.sa_handler = signalHandler;
+ sigemptyset(&sa.sa_mask);
+ sa.sa_flags = 0;
+ sigaction(SIGINT, &sa, nullptr);
+ sigaction(SIGTERM, &sa, nullptr);
+}
+
+int main(int argc, char **argv) {
+ po::options_description desc("cpp language web gateway");
+ desc.add_options()
+ ("help,h", "output help message")
+ ("version,v", "output version message")
+ ("input,i", po::value(), "input a configure text file")
+ ;
+ po::variables_map vm;
+ /* parse commandline params */
+ {
+ try {
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ po::notify(vm);
+ }
+
+ catch (const std::exception &e) {
+ std::cerr << "ERROR: " << e.what() << std::endl;
+ std::cerr << "using --help to check options message" << std::endl;
+ throw e;
+ }
+ }
+
+ if (vm.count("help")) {
+ std::cout << desc << std::endl;
+ return 0;
+ }
+
+ if (!vm.count("input")) {
+ std::cerr << "Please input configure file via -i" << std::endl;
+ return 0;
+ }
+
+ /* parse configure file */
+ {
+ try {
+
+ ConfIni cf(vm["input"].as());
+ _ADDR = cf.get("Server.address", "");
+ _PORT = cf.get ("Server.port", -1);
+ _DEFT_URL = cf.get("Proxy.default", "");
+ _DB_PATH = cf.get("Database.path", "");
+ }
+ catch (ConfIni::IniConfigureFileParseException &e) {
+ std::cerr << "ERROR: " << e.what() << std::endl;
+ std::cerr << "ini format input file error" << std::endl;
+ return 1;
+ }
+ }
+
+ if (_ADDR == "" || _PORT == -1) {
+ std::cerr << "Please setup addree and port in Serve section in configure file";
+ std::cerr << std::endl;
+ return 0;
+ }
+
+ _SERVE = std::make_unique (_ADDR, _PORT, "full_chain.crt", "server.key", 4);
+ _KEYGEN = std::make_unique ();
+ _SQLDB = std::make_unique (_DB_PATH);
+
+ db_init();
+ registerRoutes(*_SERVE);
+ set_signal_action();
+
+ _SERVE->start();
+ _SERVE->run();
+
+}
+
+void db_init() {
+
+ std::string sql = "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='Users'";
+
+ auto flag = false;
+ {
+ auto stmt = _SQLDB->stmt(sql);
+ if (stmt.step()) {
+ auto num = stmt.read_int(0);
+ if (num == 0) {
+ flag = true;
+ }
+ }
+ }
+
+ if (flag) {
+ std::cout << "Start database init..." << std::endl;
+ std::string sql_crtt = "-- create users table, username as email\n"
+ "CREATE TABLE Users (\n"
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,\n"
+ "email TEXT UNIQUE NOT NULL,\n"
+ "password_hash TEXT NOT NULL,\n"
+ "create_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n"
+ "last_login DATETIME,\n"
+ "is_active BOOLEAN DEFAULT 1\n"
+ ");\n\n"
+
+ "CREATE INDEX idx_users_email ON users(email);\n";
+
+ _SQLDB->exec(sql_crtt);
+
+ {
+ auto password_hash = SHA256::sha256(_DEFT_ADMIN_PASS);
+ std::cout << password_hash << std::endl;
+ std::string sql_crta = "INSERT INTO Users(email, password_hash, last_login) VALUES (?, ?, datetime('now', 'localtime'))";
+ auto stmt = _SQLDB->stmt(sql_crta);
+ stmt.bind_text(1, _DEFT_ADMIN_USER);
+ stmt.bind_text(2, password_hash);
+ if (stmt.step()) {
+ std::cout << stmt.read_text(1) << std::endl;
+ }
+ }
+
+ std::cout << "done" << std::endl;
+ }
+
+ else {
+ std::cout << "The database already init" << std::endl;
+ }
+}
+
+
+
+void registerRoutes(HttpServer &server) {
+
+ server.post("/login", [](
+ const http::request& req,
+ const std::unordered_map& params
+ ) -> http::response {
+ return wrapperHttp(req, params, [](
+ const auto& req, const auto& params
+ ) {
+ return handleLogin(req, params);
+ });
+ });
+
+ server.post("/register", [](const auto& req, const auto& params) {
+ return handleRegister(req, params);
+ });
+
+ server.get("*", [](const auto& req, const auto& params) {
+ return handleProxy(req, params, "get");
+ });
+
+ server.post("*", [](const auto& req, const auto& params) {
+ return handleProxy(req, params, "post");
+ });
+}
+
+http::response wrapperHttp(
+ const http::request& req,
+ const std::unordered_map& params,
+ HttpRequestHandler _main)
+
+try {
+
+ return _main(req, params);
+}
+
+catch (const std::exception& e) {
+
+ http::response res;
+ res.version(req.version());
+ const auto& ti = typeid(e);
+ json::value jv_r = {
+ {"success", false},
+ {"message", std::string("<") + ti.name() + "> " + e.what()}
+ };
+ res.set(http::field::content_type, "text/plain");
+ res.result(http::status::internal_server_error);
+ res.body() = json::serialize(jv_r);
+ res.prepare_payload();
+ return res;
+}
+
+/* curl -X POST http://127.0.0.1:9201/login -d '{"username": "qing", "password": "12345678"}' */
+http::response handleLogin(
+ const http::request& req,
+ const std::unordered_map& params)
+{
+ http::response res;
+ res.version(req.version());
+
+ try {
+ //std::cout << req.body() << std::endl;
+ json::value jv;
+ try {
+ jv = json::parse(req.body());
+ }
+ catch (const boost::wrapexcept& e) {
+ THROW_EX_CUSTOM(HttpException, 2001, "Invalid_json_Argument",
+ 400, "/login");
+ }
+
+
+ if (!jv.is_object()) {
+ THROW_EX_CUSTOM(HttpException, 2002, "Invalid_json_object_Argument",
+ 400, "/login");
+ }
+ auto& obj = jv.as_object();
+ auto username = std::string(obj.at("username").as_string());
+ auto password = std::string(obj.at("password").as_string());
+ auto password_hash = SHA256::sha256(password);
+ std::cout << username << " " << password_hash << std::endl;
+
+ std::string sql = "SELECT COUNT(*) FROM Users WHERE email=? AND password_hash=?;";
+ auto stmt = _SQLDB->stmt(sql);
+ stmt.bind_text(1, username);
+ stmt.bind_text(2, password_hash);
+ if (stmt.step() && stmt.read_int(0) == 1) {
+ //update
+ }
+
+ else {
+ THROW_EX_CUSTOM(HttpException, 2101, "Invalid Username or Password",
+ 401, "/login");
+ }
+
+ auto _PRIV = MyRSA::Private_Key::from_pem(_KEYGEN->get_private_key_pem());
+
+
+ //int created_at = 0;
+ int keep_time = 3600; // second
+
+ json::value jv_r = {
+ {"user", username},
+ //{"created_at", created_at},
+ {"keep_time", keep_time}
+ };
+
+ std::string data = json::serialize(jv_r);
+ std::string token = Base64::base64_encode(data);
+ std::string sign = _PRIV.Sign(data);
+
+ res.set("Connection", "close");
+ res.result(http::status::ok);
+ res.body() = token + "_" + sign;
+ }
+
+ catch (const HttpException& e) {
+
+ json::value jv_r = {
+ {"success", false},
+ {"message", e.what()}
+ };
+ res.set(http::field::content_type, "application/json");
+ res.result(e.status());
+ res.body() = json::serialize(jv_r);
+ }
+
+ res.prepare_payload();
+ return res;
+}
+
+/* curl -X POST http://127.0.0.1:9201/register -d '{"username": "qing", "password": "12345678"}' */
+/* FIXME: strong password check */
+http::response handleRegister(
+ const http::request& req,
+ const std::unordered_map& params)
+{
+ http::response res;
+ res.version(req.version());
+
+ try {
+
+ auto jv = json::parse(req.body());
+ if (!jv.is_object()) {
+ throw std::runtime_error("400");
+ }
+ auto& obj = jv.as_object();
+ auto username = std::string(obj.at("username").as_string());
+ auto password = std::string(obj.at("password").as_string());
+
+ auto password_hash = SHA256::sha256(password);
+
+ std::string sql = "INSERT INTO Users (email, password_hash, last_login) VALUES (?, ?, datetime('now', 'localtime'));";
+ auto stmt = _SQLDB->stmt(sql);
+ stmt.bind_text(1, username);
+ stmt.bind_text(2, password_hash);
+ stmt.step();
+
+ json::value jv_r = {{"success", true}};
+ res.result(http::status::ok);
+ res.body() = json::serialize(jv_r);
+ }
+ //catch
+
+ catch (const std::exception& e) {
+ const auto& ti = typeid(e);
+ res.set(http::field::content_type, "text/plain");
+ res.result(http::status::internal_server_error);
+ res.body() = std::string("<") + ti.name() + "> " + e.what();
+ }
+
+ res.prepare_payload();
+ return res;
+}
+
+/* curl -H "Target-Url: https://www.baidu.com" http://127.0.0.1:9201 -X GET */
+http::response handleProxy(
+ const http::request& req,
+ const std::unordered_map& params,
+ const char *method)
+{
+ http::response res;
+ res.version(req.version());
+
+ try {
+ auto _PUBL = MyRSA::Public_Key::from_pem(_KEYGEN->get_public_key_pem());
+
+ std::string url = "";
+ auto flag = false;
+ {
+ auto it = req.base().find("Target-Url");
+ if (it != req.base().end()) {
+ url = req["Target-Url"];
+ }
+
+ it = req.base().find("target-url");
+ if (it != req.base().end()) {
+ url = req["target-url"];
+ }
+
+ if (url == "") {
+ url = _DEFT_URL;
+ flag = true;
+ }
+
+ url += "/";
+ url += req.target();
+ }
+
+ /* check auth */
+ std::string auth = "";
+ {
+ auto it = req.base().find("Authorization");
+ if (it == req.base().end() && !flag) {
+ throw std::runtime_error("401");
+ }
+ std::string raw = req["Authorization"];
+ if (raw.substr(0, 7) == "Bearer ") {
+ raw = raw.substr(7, raw.size() - 7);
+ size_t idx = raw.find("_");
+ if (idx == std::string::npos) {
+ throw std::runtime_error("Header 400 Bad Request");
+ }
+ std::string data = raw.substr(0, idx);
+ std::string sign = raw.substr(idx+1, raw.size()-idx-1);
+ auth = Base64::base64_decode_to_string(data);
+ if (!_PUBL.Verify(auth, sign)) {
+ throw std::runtime_error("Header 401 Unauthorized");
+ }
+ std::cout << "auth data: " << auth << std::endl;
+ }
+ }
+
+ auto callback = [&res](const auto& ret) {
+ res.body() += ret; // TODO: too big file
+ };
+
+
+ auto client = HttpClient();
+ for (auto const& field: req) {
+ if (is_special_header(field.name_string()))
+ continue;
+ auto h = std::string();
+ h += field.name_string();
+ h += ": ";
+ h += field.value();
+ client.set_header(h);
+ }
+
+
+ if (method == "get")
+ client.get_stream_sync(url, callback);
+
+ else if (method == "post") {
+ std::string payload = req.body();
+ client.post_stream_sync(url, payload, callback);
+ }
+
+
+ for (const auto& pair: client.get_response_headers() ) {
+ res.set(pair.first, pair.second);
+ }
+ res.set("Connection", "close");
+ res.result(client.get_response_code());
+ }
+ //catch
+
+ catch (const std::exception& e) {
+ const auto& ti = typeid(e);
+ res.set(http::field::content_type, "text/plain");
+ res.result(http::status::internal_server_error);
+ json::value jv_r = {
+ {"success", false},
+ {"err_name", ti.name()},
+ {"err_message", e.what()}
+ };
+ res.body() = json::serialize(jv_r);
+ }
+
+ res.prepare_payload();
+ return res;
+}
+
+/* they are special because they point to raw request */
+bool is_special_header(const std::string &header) {
+
+ return header == "Host" || header == "connection"
+ || header == "Accept-Encoding";
+}
+
diff --git a/libcrypt/.gitignore b/libcrypt/.gitignore
new file mode 100644
index 0000000..f152158
--- /dev/null
+++ b/libcrypt/.gitignore
@@ -0,0 +1,69 @@
+# Prerequisites
+*.d
+
+# Compiled Object files
+*.slo
+*.lo
+*.o
+*.obj
+
+# Precompiled Headers
+*.gch
+*.pch
+
+# Linker files
+*.ilk
+
+# Debugger Files
+*.pdb
+
+# Compiled Dynamic libraries
+*.so
+*.dylib
+*.dll
+*.so.*
+
+
+# Fortran module files
+*.mod
+*.smod
+
+# Compiled Static libraries
+*.lai
+*.la
+*.a
+*.lib
+
+# Executables
+*.exe
+*.out
+*.app
+
+# Build directories
+build/
+Build/
+build-*/
+
+# CMake generated files
+CMakeFiles/
+CMakeCache.txt
+cmake_install.cmake
+#Makefile
+install_manifest.txt
+compile_commands.json
+
+# Temporary files
+*.tmp
+*.log
+*.bak
+*.swp
+
+# vcpkg
+vcpkg_installed/
+
+# debug information files
+*.dwo
+
+# test output & cache
+Testing/
+.cache/
diff --git a/libcrypt/LICENSE b/libcrypt/LICENSE
new file mode 100644
index 0000000..d63a519
--- /dev/null
+++ b/libcrypt/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 建昌风物大顺脚本
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/libcrypt/Makefile b/libcrypt/Makefile
new file mode 100644
index 0000000..48c4608
--- /dev/null
+++ b/libcrypt/Makefile
@@ -0,0 +1,45 @@
+VERSION := 0.0.1
+FRAMEWORK_NAME := us
+LIB_NAME := libus_crypt
+INSTL_TDIR := /lib
+INCLU_TDIR := /usr/include
+INCLU_SDIR := inc
+CPP := g++
+INCS := -I inc
+CPPFLAGS := --std=c++20 -O3 -pipe -Wall -Werror
+LIBS :=
+BUILD_TDIR := build
+$(shell mkdir -p $(BUILD_TDIR))
+
+#--------
+all: $(BUILD_TDIR)/$(LIB_NAME).so
+
+$(BUILD_TDIR)/$(LIB_NAME).so: $(BUILD_TDIR)/Crypto_Basic.o
+ $(CPP) -shared $^ $(LIBS) -o $@
+
+$(BUILD_TDIR)/Crypto_Basic.o: src/Crypto_Basic.cpp
+ $(CPP) $(CPPFLAGS) -fPIC -c $^ $(INCS) -o $@
+
+clear:
+ @rm -rvf $(BUILD_TDIR)
+
+install:
+ @echo "install UniServe_libcrypt..."
+ @mkdir -vp $(INCLU_TDIR)/$(FRAMEWORK_NAME)
+ @cp -vf $(INCLU_SDIR)/$(FRAMEWORK_NAME)/Crypto_Basic.hpp $(INCLU_TDIR)/$(FRAMEWORK_NAME)/
+ @cp -vf $(INCLU_SDIR)/$(FRAMEWORK_NAME)/Base64.hpp $(INCLU_TDIR)/$(FRAMEWORK_NAME)/
+ @cp -vf $(INCLU_SDIR)/$(FRAMEWORK_NAME)/SHA256.hpp $(INCLU_TDIR)/$(FRAMEWORK_NAME)/
+ @cp -vf $(INCLU_SDIR)/$(FRAMEWORK_NAME)/AES_CBC.hpp $(INCLU_TDIR)/$(FRAMEWORK_NAME)/
+ @cp -vf $(INCLU_SDIR)/$(FRAMEWORK_NAME)/MyRSA.hpp $(INCLU_TDIR)/$(FRAMEWORK_NAME)/
+ @cp -vf $(BUILD_TDIR)/$(LIB_NAME).so $(INSTL_TDIR)/
+ @echo "done."
+
+uninstall:
+ @echo "uninstall UniServe_libcrypt..."
+ @rm -vf $(INCLU_TDIR)/$(FRAMEWORK_NAME)/Crypto_Basic.hpp
+ @rm -vf $(INCLU_TDIR)/$(FRAMEWORK_NAME)/Base64.hpp
+ @rm -vf $(INCLU_TDIR)/$(FRAMEWORK_NAME)/SHA256.hpp
+ @rm -vf $(INCLU_TDIR)/$(FRAMEWORK_NAME)/AES_CBC.hpp
+ @rm -vf $(INCLU_TDIR)/$(FRAMEWORK_NAME)/MyRSA.hpp
+ @rm -vf $(INSTL_TDIR)/$(LIB_NAME).so
+ @echo "done."
diff --git a/libcrypt/README.md b/libcrypt/README.md
new file mode 100644
index 0000000..404df36
--- /dev/null
+++ b/libcrypt/README.md
@@ -0,0 +1,2 @@
+# UniServe_libcrypt
+UniServe Framework Cryption Library
diff --git a/libcrypt/_set.sh b/libcrypt/_set.sh
new file mode 100644
index 0000000..312f67c
--- /dev/null
+++ b/libcrypt/_set.sh
@@ -0,0 +1,5 @@
+#!/bin/bash
+cd "$(dirname "$0")" || exit
+make clear
+make
+make install
diff --git a/libcrypt/inc/us/AES_CBC.hpp b/libcrypt/inc/us/AES_CBC.hpp
new file mode 100644
index 0000000..6ed2d29
--- /dev/null
+++ b/libcrypt/inc/us/AES_CBC.hpp
@@ -0,0 +1,140 @@
+#include "Crypto_Basic.hpp"
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace qing {
+ class AES_CBC: public qing::Crypto_Basic {
+ public:
+ /* 构造函数 初始化一个随即的密钥和初始化向量 */
+ AES_CBC() {
+ generate_key_iv(key, iv);
+ }
+ AES_CBC(std::vector &key, std::vector &iv) {
+ this->key = key;
+ this->iv = iv;
+ }
+ std::string get_key() {
+ return bytes_to_hex(key);
+ }
+ std::string get_iv() {
+ return bytes_to_hex(iv);
+ }
+
+ std::string encrypt(std::string original_text) {
+ std::vector plaintext(original_text.begin(), original_text.end());
+ std::vector ciphertext = aes_encrypt(plaintext, key, iv);
+
+ // hex-bytes转换测试
+ /*std::string hex = bytes_to_hex(ciphertext);
+ std::vector cipher2 = hex_to_bytes(hex);
+ print_bytes(ciphertext);
+ print_bytes(cipher2);*/
+
+ return bytes_to_hex(ciphertext);
+ }
+
+ std::string decrypt(std::string cipher_hex) {
+ std::vector ciphertext = hex_to_bytes(cipher_hex);
+ std::vector decrypted = aes_decrypt(ciphertext, key, iv);
+ return std::string(decrypted.begin(), decrypted.end());
+ }
+
+ static void print_bytes(std::vector& bytes) {
+ for (unsigned char byte : bytes) {
+ std::cerr << std::setw(2) << static_cast(byte);
+ }
+ std::cerr << std::endl;
+ }
+
+ private:
+ std::vector key;
+ std::vector iv;
+ // 生成随机密钥和IV
+ static void generate_key_iv(std::vector& key,
+ std::vector& iv) {
+ key.resize(32); // AES-256 需要 32 字节密钥
+ iv.resize(16); // AES 块大小 16 字节(128-bit)
+
+ // 生成随即密钥
+ CRYPTO_CHECK(RAND_bytes(key.data(), key.size()) == 1, "密钥生成失败");
+
+ // 生成随即IV
+ CRYPTO_CHECK(RAND_bytes(iv.data(), iv.size()) == 1, "IV生成失败");
+ }
+
+ // AES-256-CBC 加密
+ static std::vector aes_encrypt(const std::vector& plaintext,
+ const std::vector& key,
+ const std::vector& iv) {
+ // 创建上下文
+ EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
+ CRYPTO_CHECK(ctx != nullptr, "无法创建加密上下文");
+
+ // 初始化加密操作
+ CRYPTO_CHECK(EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr,
+ key.data(), iv.data()) , "加密初始化失败");
+
+ // 输出缓冲区 (密文可能比明文长一个块)
+ std::vector ciphertext(plaintext.size() + EVP_CIPHER_CTX_block_size(ctx));
+ int len = 0;
+ int ciphertext_len = 0;
+
+ // 提供明文数据
+ CRYPTO_CHECK(EVP_EncryptUpdate(ctx, ciphertext.data(), &len,
+ plaintext.data(), plaintext.size()) == 1, "加载更新失败");
+ ciphertext_len = len;
+
+ // 完成加密(处理填充)
+ CRYPTO_CHECK(EVP_EncryptFinal_ex(ctx, ciphertext.data() + len, &len) == 1, "加密结束失败");
+ ciphertext_len += len;
+
+ // 调整到实际密文长度
+ ciphertext.resize(ciphertext_len);
+
+ // 处理上下文
+ EVP_CIPHER_CTX_free(ctx);
+
+ return ciphertext;
+
+ }
+
+ // AES-256-CBC
+ static std::vector aes_decrypt(const std::vector& ciphertext,
+ const std::vector& key,
+ const std::vector& iv) {
+ // 创建上下文
+ EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
+ CRYPTO_CHECK(ctx != nullptr, "无法创建解密上下文");
+
+ // 初始化解密操作
+ CRYPTO_CHECK(EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr,
+ key.data(), iv.data()) == 1, "解密初始化失败");
+
+ // 输出缓冲区(明文可能比密文短,但最大为密文长度)
+ std::vector