From 19cf285cb7e2517f54ae5075df027b7478021843 Mon Sep 17 00:00:00 2001 From: "Christopher M. Punches" Date: Sun, 9 Aug 2026 18:00:05 -0400 Subject: [PATCH] Initial commit: DPM core library, CLI, bundled info module, and tests --- .gitignore | 3 + CMakeLists.txt | 242 ++++++++++++ LICENSE | 235 +++++++++++ data/core.conf | 7 + docs/BUILD.md | 92 +++++ docs/CONSUMERS.md | 119 ++++++ docs/DESIGN.md | 276 +++++++++++++ docs/MODULES.md | 88 +++++ include/dpm/core.h | 335 ++++++++++++++++ include/internal/context.hpp | 74 ++++ include/internal/modules.hpp | 74 ++++ include/internal/version.hpp | 45 +++ src/bundled-modules/info/include/commands.hpp | 86 ++++ src/bundled-modules/info/info.cpp | 147 +++++++ src/bundled-modules/info/src/commands.cpp | 185 +++++++++ src/cli/dpm.cpp | 265 +++++++++++++ src/context.cpp | 336 ++++++++++++++++ src/libdpm-core.map | 18 + src/modules.cpp | 370 ++++++++++++++++++ src/version.cpp | 83 ++++ tests/fixtures/conf/core.conf | 6 + tests/fixtures/conf/testmod.conf | 5 + tests/fixtures/src/bad_magic.cpp | 95 +++++ tests/fixtures/src/bad_version.cpp | 69 ++++ tests/fixtures/src/core_too_new.cpp | 70 ++++ tests/fixtures/src/good.cpp | 96 +++++ tests/fixtures/src/lying_manifest.cpp | 72 ++++ tests/fixtures/src/missing_symbols.cpp | 33 ++ tests/test_core.cpp | 196 ++++++++++ 29 files changed, 3722 insertions(+) create mode 100644 .gitignore create mode 100644 CMakeLists.txt create mode 100644 LICENSE create mode 100644 data/core.conf create mode 100644 docs/BUILD.md create mode 100644 docs/CONSUMERS.md create mode 100644 docs/DESIGN.md create mode 100644 docs/MODULES.md create mode 100644 include/dpm/core.h create mode 100644 include/internal/context.hpp create mode 100644 include/internal/modules.hpp create mode 100644 include/internal/version.hpp create mode 100644 src/bundled-modules/info/include/commands.hpp create mode 100644 src/bundled-modules/info/info.cpp create mode 100644 src/bundled-modules/info/src/commands.cpp create mode 100644 src/cli/dpm.cpp create mode 100644 src/context.cpp create mode 100644 src/libdpm-core.map create mode 100644 src/modules.cpp create mode 100644 src/version.cpp create mode 100644 tests/fixtures/conf/core.conf create mode 100644 tests/fixtures/conf/testmod.conf create mode 100644 tests/fixtures/src/bad_magic.cpp create mode 100644 tests/fixtures/src/bad_version.cpp create mode 100644 tests/fixtures/src/core_too_new.cpp create mode 100644 tests/fixtures/src/good.cpp create mode 100644 tests/fixtures/src/lying_manifest.cpp create mode 100644 tests/fixtures/src/missing_symbols.cpp create mode 100644 tests/test_core.cpp diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ca59ed2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +cmake-build-debug/ +.cmake/ +.idea/ diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..d900672 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,242 @@ +cmake_minimum_required(VERSION 3.22) +project(dpm-core VERSION 0.1.0 LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +# --------------------------------------------------------------------- +# libdpm-core.so — the core library (C ABI) +# --------------------------------------------------------------------- +add_library(dpm-core SHARED + src/context.cpp + src/modules.cpp + src/version.cpp +) + +target_include_directories(dpm-core PUBLIC + $ + $ +) + +target_compile_definitions(dpm-core PRIVATE + DPM_CORE_VERSION_STR="${PROJECT_VERSION}" +) + +# The public C API is the library's entire exported surface; internals +# stay hidden. The version script pins the export list and versions the +# symbols. +target_compile_options(dpm-core PRIVATE + -fvisibility=hidden + -fvisibility-inlines-hidden +) +target_link_options(dpm-core PRIVATE + -Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/src/libdpm-core.map +) +set_property(TARGET dpm-core APPEND PROPERTY + LINK_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/libdpm-core.map +) + +target_link_libraries(dpm-core PRIVATE ${CMAKE_DL_LIBS}) + +set_target_properties(dpm-core PROPERTIES + OUTPUT_NAME "dpm-core" + VERSION ${PROJECT_VERSION} + SOVERSION 1 + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib +) + +# --------------------------------------------------------------------- +# dpm — the CLI (thin client of libdpm-core) +# --------------------------------------------------------------------- +add_executable(dpm src/cli/dpm.cpp) + +target_link_libraries(dpm PRIVATE dpm-core) + +set_target_properties(dpm PROPERTIES + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin + BUILD_RPATH "$ORIGIN/../lib" +) + +# --------------------------------------------------------------------- +# info — the bundled module (tests and reports core functionality) +# --------------------------------------------------------------------- +add_library(info MODULE + src/bundled-modules/info/info.cpp + src/bundled-modules/info/src/commands.cpp +) + +target_include_directories(info PRIVATE src/bundled-modules/info/include) + +# The one permitted link dependency: libdpm-core. +target_link_libraries(info PRIVATE dpm-core) + +set_target_properties(info PROPERTIES + PREFIX "" + SUFFIX ".so" + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/modules +) + +# The module bundles with core, so building the CLI builds it too: after a +# clean, running dpm from the build tree finds a module directory that is +# populated. This orders the build only — the CLI does not link the module. +add_dependencies(dpm info) + +# --------------------------------------------------------------------- +# Test fixture modules: one known-good stub, five deliberately broken +# --------------------------------------------------------------------- +enable_testing() + +set(FIXTURE_MODULE_DIR ${CMAKE_BINARY_DIR}/tests/fixtures) + +foreach(fixture good missing_symbols bad_magic lying_manifest core_too_new bad_version) + add_library(fixture_${fixture} MODULE tests/fixtures/src/${fixture}.cpp) + set_target_properties(fixture_${fixture} PROPERTIES + PREFIX "" + SUFFIX ".so" + OUTPUT_NAME ${fixture} + LIBRARY_OUTPUT_DIRECTORY ${FIXTURE_MODULE_DIR} + ) +endforeach() + +# --------------------------------------------------------------------- +# Core API test binary — drives libdpm-core through its public C API +# --------------------------------------------------------------------- +add_executable(test_core tests/test_core.cpp) + +target_link_libraries(test_core PRIVATE dpm-core) + +target_compile_definitions(test_core PRIVATE + TEST_FIXTURE_MODULES="${FIXTURE_MODULE_DIR}" + TEST_FIXTURE_CONF="${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/conf" + DPM_CORE_VERSION_EXPECTED="${PROJECT_VERSION}" +) + +set_target_properties(test_core PROPERTIES + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests + BUILD_RPATH "$ORIGIN/../lib" +) + +foreach(fixture good missing_symbols bad_magic lying_manifest core_too_new bad_version) + add_dependencies(test_core fixture_${fixture}) +endforeach() + +add_test(NAME core_api COMMAND test_core) + +# --------------------------------------------------------------------- +# CLI end-to-end tests (the CLI is core's cheapest full-stack client) +# --------------------------------------------------------------------- +add_test(NAME cli_help COMMAND dpm --help) +set_tests_properties(cli_help PROPERTIES PASS_REGULAR_EXPRESSION "Usage: dpm") + +add_test(NAME cli_list + COMMAND dpm -c ${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/conf + -m ${CMAKE_BINARY_DIR}/modules --list-modules) +set_tests_properties(cli_list PROPERTIES PASS_REGULAR_EXPRESSION "info") + +add_test(NAME cli_info_version + COMMAND dpm -c ${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/conf + -m ${CMAKE_BINARY_DIR}/modules -L INFO info version) +set_tests_properties(cli_info_version PROPERTIES + PASS_REGULAR_EXPRESSION "libdpm-core Version: ${PROJECT_VERSION}") + +add_test(NAME cli_module_not_found + COMMAND dpm -c ${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/conf + -m ${CMAKE_BINARY_DIR}/modules nonexistent) +set_tests_properties(cli_module_not_found PROPERTIES WILL_FAIL TRUE) + +add_test(NAME cli_rejects_invalid_module + COMMAND dpm -c ${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/conf + -m ${FIXTURE_MODULE_DIR} missing_symbols) +set_tests_properties(cli_rejects_invalid_module PROPERTIES WILL_FAIL TRUE) + +# --------------------------------------------------------------------- +# Code reference (Doxygen) — optional 'docs' target +# --------------------------------------------------------------------- +option(DPM_DOCS_HTML "Generate the code reference in HTML" OFF) +option(DPM_DOCS_PDF "Generate the code reference as PDF (requires LaTeX)" ON) + +find_package(Doxygen) +if(DOXYGEN_FOUND) + set(DOXYGEN_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/docs) + set(DOXYGEN_EXTRACT_ALL YES) + set(DOXYGEN_EXTRACT_STATIC YES) + set(DOXYGEN_QUIET YES) + set(DOXYGEN_WARN_IF_UNDOCUMENTED NO) + set(DOXYGEN_JAVADOC_AUTOBRIEF YES) + + if(DPM_DOCS_HTML) + set(DOXYGEN_GENERATE_HTML YES) + else() + set(DOXYGEN_GENERATE_HTML NO) + endif() + + if(DPM_DOCS_PDF) + set(DOXYGEN_GENERATE_LATEX YES) + set(DOXYGEN_USE_PDFLATEX YES) + set(DOXYGEN_PDF_HYPERLINKS YES) + else() + set(DOXYGEN_GENERATE_LATEX NO) + endif() + + doxygen_add_docs(docs + ${CMAKE_CURRENT_SOURCE_DIR}/include + ${CMAKE_CURRENT_SOURCE_DIR}/src + COMMENT "Generating code reference with Doxygen" + ) + + if(DPM_DOCS_PDF) + find_program(PDFLATEX_EXECUTABLE pdflatex) + if(PDFLATEX_EXECUTABLE) + add_custom_target(docs-pdf + COMMAND make -C ${CMAKE_BINARY_DIR}/docs/latex + COMMENT "Building PDF code reference" + ) + add_dependencies(docs-pdf docs) + else() + message(WARNING "DPM_DOCS_PDF is ON but pdflatex was not found; the docs-pdf target is unavailable") + endif() + endif() +endif() + +# --------------------------------------------------------------------- +# Clean +# --------------------------------------------------------------------- +# clean empties the build directory: every artifact, every generated tree, +# and the generated build system itself, so that building again requires +# regenerating the directory first. +# +# Order is load-bearing. This list becomes one script run by cmake -P: it is +# parsed whole before it executes, but a removal that fails aborts the rest, +# so anything named after that point survives. Leaves that nothing depends +# on come first, and the entries most likely to be held by an outside +# process — the IDE's file-API directory — come last, where a failure +# costs nothing. The build system make is running from is named late for +# the same reason, since by then the script is already in memory. +set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_CLEAN_FILES + ${CMAKE_BINARY_DIR}/Testing + ${CMAKE_BINARY_DIR}/bin + ${CMAKE_BINARY_DIR}/lib + ${CMAKE_BINARY_DIR}/modules + ${CMAKE_BINARY_DIR}/tests + ${CMAKE_BINARY_DIR}/docs + ${CMAKE_BINARY_DIR}/CMakeDoxyfile.in + ${CMAKE_BINARY_DIR}/CMakeDoxyfile.tpl + ${CMAKE_BINARY_DIR}/CMakeDoxygenDefaults.cmake + ${CMAKE_BINARY_DIR}/Doxyfile.docs + ${CMAKE_BINARY_DIR}/compile_commands.json + ${CMAKE_BINARY_DIR}/cmake_install.cmake + ${CMAKE_BINARY_DIR}/CTestTestfile.cmake + ${CMAKE_BINARY_DIR}/CMakeCache.txt + ${CMAKE_BINARY_DIR}/Makefile + ${CMAKE_BINARY_DIR}/CMakeFiles + ${CMAKE_BINARY_DIR}/.cmake +) + +# --------------------------------------------------------------------- +# Installation +# --------------------------------------------------------------------- +install(TARGETS dpm RUNTIME DESTINATION bin) +install(TARGETS dpm-core LIBRARY DESTINATION lib) +install(TARGETS info LIBRARY DESTINATION lib/dpm/modules) +install(DIRECTORY include/dpm DESTINATION include) +install(FILES data/core.conf DESTINATION /etc/dpm/conf.d) diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4226400 --- /dev/null +++ b/LICENSE @@ -0,0 +1,235 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 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 Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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. + +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. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero 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. + + DPM-Core + Copyright (C) 2025 Dark-Horse-Linux + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. + +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 AGPL, see . diff --git a/data/core.conf b/data/core.conf new file mode 100644 index 0000000..b80dc20 --- /dev/null +++ b/data/core.conf @@ -0,0 +1,7 @@ +[logging] +log_level = INFO +write_to_log = false +log_file = /var/log/dpm/dpm.log + +[modules] +path = /usr/lib/dpm/modules diff --git a/docs/BUILD.md b/docs/BUILD.md new file mode 100644 index 0000000..a15ed8a --- /dev/null +++ b/docs/BUILD.md @@ -0,0 +1,92 @@ +# Building DPM Core + +## Prerequisites + +- GCC/G++ supporting C++20 +- CMake 3.22 or later +- Make +- Doxygen (optional, for the code reference) +- pdflatex and makeindex (optional, for the PDF code reference) + +The library itself depends only on libc, libstdc++, and libdl, so it builds and runs on a minimal system. + +## Building for development + +``` +cmake -B -DCMAKE_BUILD_TYPE=Debug +cmake --build +``` + +Artifacts land in: + +``` +/bin/dpm the CLI +/lib/libdpm-core.so the core library +/modules/info.so the bundled info module +``` + +The dpm binary built here finds the locally built libdpm-core.so on its own — an embedded library search path points it at the lib/ directory next to it in the build tree, so running it directly uses the core you just built with nothing to set up first. This is only the default: LD_LIBRARY_PATH takes precedence over the embedded path, so the binary can be pointed at any other core, including the system-installed one. + +### Running the tests + +``` +ctest --test-dir --output-on-failure +``` + +This runs the core API test binary (which exercises the full load-time validation matrix against the fixture modules in tests/fixtures/) and the CLI end-to-end tests. + +### Running the CLI from the build tree + +The build tree plus the test fixtures form a complete self-contained environment; no installation is required. Point the CLI at local paths with its override flags: + +``` +/bin/dpm --config-dir ./tests/fixtures/conf --module-path /modules info version +``` + +The flags --config-dir, --module-path, --root, and --log-level each redirect the corresponding system default; --root sets the target root that package-operation modules act on. + +## Generating the code reference + +When Doxygen is present, the build offers a docs target that generates the API and source reference from the documentation comments carried in the headers and sources. Two output formats are available as configure-time options: + +- **-DDPM_DOCS_PDF** (default ON) — PDF reference, via Doxygen's native LaTeX output; requires pdflatex and makeindex +- **-DDPM_DOCS_HTML** (default OFF) — HTML reference + +Generate and compile the PDF reference: + +``` +cmake --build --target docs-pdf +``` + +The PDF lands at /docs/latex/refman.pdf. + +With DPM_DOCS_HTML enabled at configure time, the docs target additionally produces the HTML reference in /docs/html: + +``` +cmake -B -DDPM_DOCS_HTML=ON +cmake --build --target docs +``` + +## Building, testing, and installing a release + +One build tree carries the whole sequence — the test suite builds and runs in any configuration, so the artifacts that get tested are the artifacts that get installed: + +``` +cmake -B -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr +cmake --build +ctest --test-dir --output-on-failure +cmake --install +``` + +This is the packaging flow: configure once, build once, test what was built, install what was tested. Omit -DCMAKE_INSTALL_PREFIX=/usr for a /usr/local install. Under the install prefix this installs: + +``` +bin/dpm the CLI +lib/libdpm-core.so the core library +lib/dpm/modules/info.so the bundled info module +include/dpm/ the public header +``` + +Core configuration installs to /etc/dpm/conf.d/core.conf regardless of prefix. + + diff --git a/docs/CONSUMERS.md b/docs/CONSUMERS.md new file mode 100644 index 0000000..2c17d7c --- /dev/null +++ b/docs/CONSUMERS.md @@ -0,0 +1,119 @@ +# Consuming libdpm-core + +Programs link libdpm-core to operate the package manager directly: build systems, installers, image builders, system tooling, and foreign-language bindings all use the same library the dpm CLI is built on. A program holding a default context is operating the installed package manager itself — system configuration, system module path, system tree, system locking — identically to invoking the installed dpm command. + +## Compiling and linking + +With core installed, include the public header and link the library: + +``` +#include +``` + +``` +g++ myprog.cpp -ldpm-core +``` + +The header installs to the standard include path and the library to the standard lib path, so no additional flags are required. The interface is a C ABI: every function is extern "C", every type crossing the boundary is a C type, and state passes through opaque handles — callable from C, C++, or any language with C FFI. + +## The context + +All work happens through a context handle: + +``` +dpm_ctx* ctx = dpm_open(NULL); +... +dpm_close(ctx); +``` + +dpm_open(NULL) reads the system configuration (/etc/dpm/conf.d/), resolves the system module path, and targets the root filesystem. dpm_close releases every handle the context issued; all pointers obtained through the context are invalid after it. + +To point a context elsewhere, pass overrides — every field is optional: + +``` +dpm_open_overrides ov = { + "/path/to/conf.d", /* config_dir: NULL = /etc/dpm/conf.d/ */ + "/path/to/modules", /* module_path: NULL = config, then default */ + "/path/to/root", /* root: target root for package operations */ + -1 /* log_level: -1 = from config */ +}; +dpm_ctx* ctx = dpm_open(&ov); +``` + +The root override is what makes chroot builds, image assembly, and sysroot management work: package operations act on the given tree instead of the running system. Multiple simultaneous contexts with different roots are legal. + +## Acquiring and using modules + +**dpm_require** loads a module by name, on demand, with an optional minimum version: + +``` +dpm_module* mod = dpm_require(ctx, "mymodule", "1.0.0"); +``` + +Core validates the module completely at load; a handle is returned only for a fully valid module. NULL means the module is absent, invalid, or below the minimum — dpm_last_error(ctx) carries the precise reason. Modules load at most once per context; repeated calls return the same handle. + +**dpm_execute** drives a module the way the CLI does — a command name and arguments: + +``` +int rc = dpm_execute(ctx, mod, "command", argc, argv); +``` + +**dpm_get_api** returns a module's typed function table for direct calls: + +``` +const mymodule_api_v1_s* api = (const mymodule_api_v1_s*)dpm_get_api(ctx, mod, "mymodule", 1); +``` + +The returned table was validated at load and is usable for the life of the context. NULL means the module does not provide that API at that version. + +## Enumerating modules + +``` +dpm_cursor* cur = dpm_list_modules(ctx); +dpm_module_info info; +while (dpm_cursor_next(cur, &info) == 0) { + /* info.name, info.version, info.description, info.core_min */ +} +dpm_cursor_free(cur); +``` + +The cursor covers every valid module in the module path; invalid candidates are excluded and logged. + +## Services + +- **dpm_core_version()** — core's version; callable without a context. +- **dpm_config_get(ctx, module, section, key)** — a value from a module's configuration namespace, or NULL if unset. +- **dpm_log(ctx, level, message)** — writes to the context's configured log targets; levels are DPM_LOG_FATAL through DPM_LOG_DEBUG. +- **dpm_module_path(ctx)** — the resolved module directory. +- **dpm_last_error(ctx)** — a human-readable description of the most recent failure on the context, or NULL. + +## Ownership and errors + +Strings returned by the library are owned by the context (or by the module that produced them) and remain valid until dpm_close; callers never free them. Functions returning int use 0 for success. Functions returning pointers use NULL for failure, with detail available from dpm_last_error. + +## Complete example + +``` +#include +#include + +int main(void) { + dpm_ctx* ctx = dpm_open(NULL); + if (!ctx) { + fprintf(stderr, "failed to initialize\n"); + return 1; + } + + dpm_module* mod = dpm_require(ctx, "info", NULL); + if (!mod) { + fprintf(stderr, "%s\n", dpm_last_error(ctx)); + dpm_close(ctx); + return 1; + } + + int rc = dpm_execute(ctx, mod, "version", 0, NULL); + + dpm_close(ctx); + return rc; +} +``` diff --git a/docs/DESIGN.md b/docs/DESIGN.md new file mode 100644 index 0000000..fd8793c --- /dev/null +++ b/docs/DESIGN.md @@ -0,0 +1,276 @@ +# DPM — Dark Horse Package Manager: Design + +## Constraints + +- Must be able to operate in a barren environment providing libc and libstdc++ — the standard build runs there as-is, no special variants. On a fully populated system the same binaries simply have more modules loadable. +- Capability grows in layers: each layer installs the dependencies of the next using only what already works. +- Every implementation exists exactly once, and is consumable by the CLI, by other layers, and by external programs (build systems, Dark Horse tooling) through C interfaces. + +## Architecture overview + +``` + dpm CLI build systems / DHL tools / other languages + \ / + v v + libdpm-core.so + (discovery, validation, routing, + version negotiation, config, logging) + | | + v v + raw module pkg module ... future modules (repo, source, ...) + (one .so) (one .so) + | | + v v + backing tree sqlite3 + (source of truth) (derived cache) +``` + +libdpm-core.so is the single entry point for everything. Modules are shared objects that implement package functionality. All routing — core-to-module and module-to-module — passes through core. No consumer touches dlopen, dlsym, or module discovery itself. + +## Versioning model + +Compatibility is directional, and the module is the one that declares it: + +- **Each module reports the minimum core version it supports** (a reserved contract symbol). At load, core compares its own version against that minimum: running core is older → refuse with an explicit "core too old for this module" report; otherwise load. Core never rejects a module for being old, because core's contract evolves append-only — a newer core supports everything an older core did. +- **Consumers state only minimums**, never maximums: require("raw", min 1.2) means "raw at 1.2 or anything newer." Module APIs evolve append-only (new table versions beside old ones), so newer is always acceptable and an update can never render a consumer's requirement unsatisfiable. +- **Updates only add satisfiable states**: because bounds are minimums and evolution is append-only, updating core or any module preserves every previously working combination. The single possible load refusal — module requires a newer core — names its own remedy. + +## libdpm-core.so + +Dependencies: libc, libstdc++, libdl. Never more — core must remain loadable in the barren case forever, so package logic never leaks into it. Core routes and hosts; modules implement. + +Core provides: + +- **Discovery**: module path resolution, enumeration of installed module .so's. +- **Validation**: the full load-time contract enforcement described below. Core is the sole authority on what a valid module is; the contract definition lives inside core as data. There is no SDK package — the interface is specified by this document and enforced by core's validator. +- **Routing**: + - generic dispatch — execute a command string with arguments against a named module (what the CLI uses); + - typed access — a consumer requests a module's API at a version and receives a C function table (what modules and external programs use). +- **Version negotiation**: require resolves a module by name, checks the requested minimum, loads, and returns a handle, or reports precisely why it can't. +- **Common services**: configuration access (per-module namespaces from /etc/dpm/conf.d/), logging, module-path queries. + +## Core C API + +All functions are extern "C". All returned strings are owned by core (or by the module that produced them), are valid until the context is closed, and are never freed by the caller. All functions returning int use 0 for success and nonzero error codes; details of the most recent failure are retrievable per-context. + +### Context lifecycle + +**dpm_ctx\* dpm_open(const dpm_open_overrides\* overrides)** +Creates a core context. Reads configuration from /etc/dpm/conf.d/ (or the config directory named in overrides), resolves the module path (overrides take precedence over config, config over the built-in default), and initializes logging per configuration. Performs no module loading. Returns NULL only on allocation failure or an unreadable/invalid explicit override; a missing config directory is not an error — defaults apply. `overrides` may be NULL, and may specify: config directory, module path, target root (for chroot/image/sysroot operation), and log level. Multiple simultaneous contexts with different roots are legal. + +**void dpm_close(dpm_ctx\* ctx)** +Releases the context: unloads every module handle it issued, closes log targets, frees all memory owned by the context. All handles and strings obtained through the context are invalid after this call. NULL is a no-op. + +### Module acquisition + +**dpm_module\* dpm_require(dpm_ctx\* ctx, const char\* name, const char\* min_version)** +Resolves the module `name` in the module path, runs the full load-time validation sequence (see Load-time enforcement) if the module is not already loaded in this context, and checks that the module's version is ≥ `min_version` (X.Y.Z comparison; NULL means "any version"). On success returns a module handle owned by the context (repeated calls return the same handle — modules are loaded at most once per context). On failure returns NULL and records the precise reason: not found, validation step failed (with the step and detail), or version below minimum (with both versions). + +**const void\* dpm_get_api(dpm_ctx\* ctx, dpm_module\* mod, const char\* api_name, int table_version)** +Returns the API table `api_name` at `table_version` from a loaded module — the pointer the module exported for that table, already validated (manifest cross-check, magic, minimum size) at load. The caller casts it to the table struct type for that API and version as defined in the module's documented API. Returns NULL if the module does not provide that api/version pair; that fact is known from the manifest without further probing. The table is valid for the life of the context. + +**int dpm_execute(dpm_ctx\* ctx, dpm_module\* mod, const char\* command, int argc, char\*\* argv)** +Generic dispatch: invokes the module's dpm_module_execute with the context, `command`, and the argument vector. Returns the module's return value verbatim (0 = success). Core adds nothing to the call besides delivery; argument semantics beyond "argv[0] is the command" are the module's to define. + +### Enumeration + +**dpm_cursor\* dpm_list_modules(dpm_ctx\* ctx)** +Scans the module path and returns a cursor over all *valid* modules (each candidate .so is validated on first scan; failures are logged and excluded). Returns NULL on an unreadable module path. + +**int dpm_cursor_next(dpm_cursor\* cur, dpm_module_info\* out)** +Advances the cursor. Fills `out` with the next module's name, version, description, and minimum-core version (string pointers valid until context close). Returns 0 and fills `out` while entries remain; returns nonzero at end. + +**void dpm_cursor_free(dpm_cursor\* cur)** +Releases the cursor. NULL is a no-op. + +### Services (available to modules and external consumers alike) + +**const char\* dpm_core_version(void)** +Returns core's own version as a static X.Y.Z string. Callable without a context. + +**const char\* dpm_config_get(dpm_ctx\* ctx, const char\* module, const char\* section, const char\* key)** +Returns the configured value for `key` in `section` of the named module's config namespace (/etc/dpm/conf.d/<module>.conf; "core" names core's own file). Returns NULL if unset. String valid until context close. + +**void dpm_log(dpm_ctx\* ctx, int level, const char\* message)** +Writes `message` at `level` (FATAL=0, ERROR=1, WARN=2, INFO=3, DEBUG=4) to the context's configured log targets (console and/or file). Messages above the configured level are dropped. NULL message is a no-op. + +**const char\* dpm_module_path(dpm_ctx\* ctx)** +Returns the resolved module directory path for this context. + +**const char\* dpm_last_error(dpm_ctx\* ctx)** +Returns a human-readable description of the most recent failure recorded on this context, or NULL if none. Overwritten by the next failing call on the same context. + +## Module contract + +A module is one .so in the module directory. It exports, as extern "C", the following reserved symbols. Returned strings are static or module-owned, non-NULL, and valid for the lifetime of the loaded module; core and consumers never free them. + +**int dpm_module_execute(dpm_ctx\* ctx, const char\* command, int argc, char\*\* argv)** +The module's generic command entry point. `ctx` is the host context that dispatched the call — the module reaches every core service (dpm_log, dpm_config_get, dpm_module_path, ...) through it. `command` is the subcommand name (equal to argv[0] when argc > 0); argc/argv are the remaining CLI-style arguments. NULL or empty `command` must behave as the module's help command. Returns 0 on success, nonzero on failure. This is the only entry the CLI path ever uses; it must be callable immediately after load with no other setup. + +**const char\* dpm_module_version(void)** +Returns the module's own version as an X.Y.Z string. Must be constant for the life of the module and must match the version by which consumers state minimums. + +**const char\* dpm_module_description(void)** +Returns a one-line human-readable description, used in module listings. + +**const char\* dpm_module_core_min(void)** +Returns the minimum core version (X.Y.Z) this module supports — the oldest core whose contract and services the module was written against. Core refuses to load the module if its own version is lower, and says so. + +**const dpm_manifest\* dpm_module_manifest(void)** +Returns a pointer to a static manifest table declaring the module's entire functional surface: an entry count and, per entry, the API name, its table version, and the exact exported symbol that carries the table (e.g. { "raw", 1, "raw_api_v1" }). Core trusts nothing it doesn't verify: every declared symbol is resolved at load, and only manifest-declared tables are ever handed to consumers. An API absent from the manifest does not exist, even if its symbol does. + +**API tables** (the module's functional surface): for each API version, one exported symbol (e.g. raw_api_v1) pointing to a plain C struct of function pointers. Every table opens with two fixed members: a magic constant (a fixed value defined by this spec, confirming the exporter agrees on table layout conventions) and the struct size in bytes (populated by the module, letting consumers accept tail-extended revisions of the same version). All parameters and returns are C types only; state passes through opaque handles; errors are int codes. + +**Symbol naming**: functional exports are prefixed with the module's name (raw_\*, pkg_\*); the dpm_ prefix is reserved for the contract and core. + +## Load-time enforcement + +Core is the sole authority on module validity; the contract above is enforced by core's validator, not by any SDK. Validation is all-or-nothing; a module is registered only after passing every step: + +1. **Resolve all reserved contract symbols.** Any missing → refuse, log the exact list, dlclose. +2. **Core-minimum handshake.** dpm_module_core_min() must be ≤ core's version. If core is too old, refuse and say so — the remedy is updating core, and the message names it. Old modules on newer core always pass. +3. **Probe the cheap calls.** dpm_module_version() and dpm_module_description() are invoked immediately; NULL or malformed returns → refuse. +4. **Cross-check the manifest.** Every API the module declares must actually resolve via dlsym. A module advertising an API it doesn't export is refused. Core validates the module's entire declared surface at load, before offering any of it. +5. **Table sanity.** Check each declared table's magic constant (catches modules built against a stale or wrong layout) and minimum size for its version. + +Failures happen at install/load time, loudly and itemized. Consumers never receive a partially valid module: if core handed out a handle, the contract already validated. The residual C-ABI limit — dlsym cannot verify signatures — is covered in practice by the magic, size, core-minimum handshake, and probes; defeating those requires deliberate lying, which is a package-signing concern upstream of the loader. + +## Module: raw — the file-based installer + +Ships with the base system alongside core. Depends on the baseline only; archive decompression is vendored in, and the package format is chosen to keep that small. This is what makes barren-environment operation possible: core + raw function with nothing else present. + +- **Owns the backing tree** (/var/lib/dpm/): one directory per installed package holding manifest, metadata, and hooks. The tree is the database at this layer. +- **Operations** (exposed both as commands and in raw_api_v1): install a package file, remove, verify, and queries answered by walking the tree — slow but always correct, zero dependencies. +- **Owns the lock file and an append-only transaction journal** with a generation counter. Every mutation in the entire system ultimately passes through raw, so locking and journaling are implemented exactly once and inherited by every layer above. + +## Module: pkg — the full package manager + +Ships as a package, installed by raw once sqlite3 is installed. Requires raw (via core, minimum version) and libsqlite3. + +- Never touches the tree directly: every filesystem mutation is a call into raw's API table, obtained from core, in-process — shared locking, real error propagation, no output parsing. +- **The sqlite database is a derived cache** under one invariant: it contains nothing that cannot be rebuilt by scanning the tree. It records the last journal generation it applied; on open, if the tree is ahead (someone used raw directly — explicitly allowed, that's the escape hatch for broken systems), it replays or rebuilds. Self-healing by construction. +- Adds what the cache enables: fast queries, dependency resolution against the installed set, multi-package transactions with rollback. +- Exposes pkg_api_v1 for consumers that want dependency-aware operations; they transitively get raw's guarantees because there is no second code path to the tree. + +## The CLI + +`dpm` is argument parsing and printing. It links libdpm-core, enumerates modules, and forwards subcommands through generic dispatch. Its command surface is exactly the set of loadable modules — in the barren case that's raw's commands; on a full system, everything installed. No capability logic lives in the CLI. + +## External consumers + +Build systems and Dark Horse components link libdpm-core.so — the same library, the same path as everything else: + +- open a context (optionally against an alternate root), +- require the layer they need at a minimum version, +- fetch its API table, +- call C functions directly. + +Core installs its header to the standard include path and its library to the standard lib path: a consumer writes #include <dpm/core.h>, links -ldpm-core, and calls package manager module functions. A consumer that opens a default context (no overrides) is operating the installed package manager itself — system configuration, system module path, system tree, system locking — exactly as if it were invoking the installed dpm command, because the CLI is just another caller of the same library. Overrides redirect individual paths only when a caller explicitly sets them. Whether a consumer targets raw only (image builders that just deploy trees) or pkg (dependency-aware tooling) is their choice of require(); behavior is identical to the CLI's because it is the same implementation. + +## Bootstrap chain + +``` +minimal start: dpm + libdpm-core.so + raw module (baseline deps only) +raw installs: sqlite3 package +raw installs: dpm-pkg package (drops the pkg module .so) +now: core discovers pkg, validates it, full management is live +``` + +Every layer is a package installed and upgraded by the layer beneath it; the package manager maintains itself with the same mechanism it offers the OS. Future modules follow the identical pattern — a repo/network module declares its requirements (pkg, a TLS library), lands as a package, and the capability appears on next discovery. + +## Repository structure + +Modules are developed independently from each other and independently from core — one repository per module, plus the core repository. Each repo owns its source, build, and tests, and produces exactly one artifact: + +- **Core repository**: libdpm-core.so and the dpm CLI. Contains no module code. Its test fixtures include deliberately broken stub modules for validating the loader, and one known-good stub — never a real package module. +- **The exception**: an info module that bundles with core, used for testing and reporting functionality of core. +- **One repository per module** (raw, pkg, and every future module): produces that module's .so. Links libdpm-core.so — the only cross-repo build dependency in the system — and nothing else from DPM. Peer modules never appear in a module's repository, build, or test environment; peers are runtime concerns, faked at test time (contract fakes and stub modules) and real only at distribution-level integration. + +No repository can block another's development: a module builds and its full pre-integration test surface (unit, contract, module-hosting) runs with nothing present but its own checkout and an installed or vendored libdpm-core. Release coordination happens through the versioning model — minimums only — rather than through lockstep builds. + +### Core repository layout + +``` +include/dpm/ public headers — installed to the system include path; the + dpm/ directory is the consumer namespace, so an installed + consumer writes #include +include/internal/ library-private headers — used only by src/, never installed +src/ implementations of the core library +src/cli/ the dpm CLI entry point +src/bundled-modules/info/ the bundled info module +data/ files installed as-is (core.conf) +tests/ fixture modules, the core API test binary, CLI tests +docs/ project documentation +``` + +Every header lives under include/: include/dpm/ is the published API surface and defines what consumers see; include/internal/ is the implementation's own headers, invisible outside the repo because the install rule ships only include/dpm/. + +## Artifacts + +Terminology: **DPM Core** names the dpm CLI binary; **libdpm-core** names the library. + +| Artifact | Location on system | +|---|---| +| dpm | /usr/bin/dpm | +| libdpm-core.so | /usr/lib/libdpm-core.so | +| info.so | /usr/lib/dpm/modules/info.so | +| modules (raw.so, pkg.so, repo.so, source.so, ...) | /usr/lib/dpm/modules/<name>.so | + +## Development and testing + +Development works because the design has no build-time coupling between peers: nothing links against a peer module, ever. "Not all the pieces are there" is the normal, permanent condition at build time. What remains resolves into four test layers, each needing strictly less than the full system. + +### What a build requires + +- A module compiles against its own declarations (written to the spec — the externs it exports, the table structs it consumes) plus **libdpm-core.so, the one real link dependency** — and core is by definition the stable, always-present, baseline-only piece. Cheap to have in every dev environment, trivially vendorable as a checkout. +- Peer modules are reached at runtime through core's require/get_api. Building pkg does not require raw to exist anywhere. The compile-time knowledge of raw is just the raw_api_v1 struct layout, which is spec, not artifact. + +A module repo therefore builds self-contained, always. + +### Test layers + +**1. Unit tests — need nothing.** The module's implementation compiles once as an object library, linked into both the .so and a test binary. Pure logic, error paths, parsing — no core, no peers. + +**2. Contract tests — need a struct, not a module.** Because every dependency is an API table — a plain struct of function pointers — a fake is just a struct the test fills in with functions that record calls and return canned results. pkg's logic is exercised against a fake raw_api_v1 (verifying it calls install/remove/query correctly, handles raw's error codes, honors the journal-generation protocol) with raw nowhere on the machine. Injection is built into the architecture; no linker seams required. + +**3. Module-hosting tests — need core only.** A harness links the real libdpm-core, points the module path at the build output plus fixtures, and has core load the just-built .so exactly as production would — full five-step validation included, so contract violations fail here, in CI, not on a user's system. Where the module needs a peer, the fixture directory contains a **stub module**: a tiny .so exporting the reserved symbols and a fake table, which core validates and serves like the real thing. The harness then drives dpm_module_execute end to end against fixture config and data. This layer runs on a bare builder with nothing installed. + +**4. Integration — the only layer that needs everything, and it builds itself.** Real core + real raw, then the actual bootstrap chain into a scratch root: dpm_open against an alternate root, raw installs sqlite3 and the pkg package into it, core discovers pkg, real operations run against the throwaway tree. Because alternate roots are first-class in the API, this needs a directory, not a VM. Full-distribution CI does the same with real packages. + +### Day-to-day workflow + +- Working on **pkg**: edit, run unit + contract tests (instant, zero environment), harness run before merge. A real raw is never needed, or even possessed, until integration. +- Working on **raw**: same, except its fakes point the other way — its tests need only fixture package files and a scratch tree. +- Working on **core**: its test fixtures are deliberately broken modules — missing symbols, wrong magic, lying manifests, too-new core-min — plus one known-good stub. Core development never needs any real package module. +- **Debugging** is the layer-3 harness under a debugger — it is the "run the module without the system" mechanism, so no separate standalone build exists or is maintained. + +The discipline that keeps this honest: fakes and stubs are written to the spec, and layer-3 validation plus the layer-4 bootstrap run in CI, so a fake that drifts from reality is caught by the first integration pass rather than shipped. + +## Development capabilities + +During development the CLI must be pointable at a local libdpm-core, and that core must be configurable to local paths (module path, config dir, etc.). Two mechanisms provide this: + +- **Pointing the CLI at a local libdpm-core** is dynamic-linker territory, needing no DPM mechanism: development builds of the CLI carry an rpath to their own build tree's lib/ directory, so the locally built binary resolves the locally built core (LD_LIBRARY_PATH pointed at that lib/ directory achieves the same). The system core is never touched. +- **Pointing that core at local paths** is what the dpm_open overrides exist for: config directory, module path, and target root are all fields of the overrides struct, and the CLI exposes them as flags. A dev invocation: + +``` +./build/bin/dpm --config-dir ./tests/fixtures/conf --module-path ./build/modules raw install ./fixture.dpm +``` + +The config-dir override matters most: once the context reads config from the local conf dir, everything configurable — log file, module path defaults, per-module settings — resolves locally, so a checkout plus its fixtures is a complete self-contained environment. Adding --root at a scratch directory makes even real install operations land in a throwaway tree. + +**Rule**: every field of the dpm_open overrides struct must be exposed as a CLI flag, so anything a linked consumer can redirect, a developer at the shell can redirect too. This holds for any future override field — nothing ships reachable from code but not from the command line. + +## Evolution rules + +- **Append-only ABI**: breaking a module API means exporting a new table (raw_api_v2) beside the old one, never mutating v1. Old tables remain until consumers are gone. +- **Append-only core contract**: newer core loads everything older core did; a module's only version assertion against core is its minimum. +- **Minimums only, everywhere**: modules declare the minimum core they support; consumers declare the minimum module version they need. No maximums, no exact-match constraints — an update can never make a previously working combination refuse to load. + +## Invariants + +1. Core routes and hosts; modules implement. No package logic in core, ever. +2. Writes flow down, never sideways: a layer mutates the system only through the layer beneath it, in-process through core-mediated APIs. +3. Truth lives in the tree; everything above is regenerable cache or convenience. +4. Dropping down a layer by hand is always legal; layers above detect it and reconcile. +5. A module is either fully valid or not loaded — no partial states, no consumer-side defense. diff --git a/docs/MODULES.md b/docs/MODULES.md new file mode 100644 index 0000000..cccd8ff --- /dev/null +++ b/docs/MODULES.md @@ -0,0 +1,88 @@ +# Developing DPM Modules + +A DPM module is one shared object in the module directory. Core loads it, validates it completely, routes CLI commands to it, and serves its functions to other modules and to programs linked against libdpm-core. This document covers writing, building, testing, and installing a module. + +## The module contract + +Every module exports the following symbols as extern "C". All returned strings must be non-NULL, static or module-owned, and valid for the lifetime of the loaded module; callers never free them. + +**int dpm_module_execute(dpm_ctx\* ctx, const char\* command, int argc, char\*\* argv)** +The generic command entry point. `ctx` is the host context that dispatched the call; the module reaches every core service (dpm_log, dpm_config_get, dpm_module_path, ...) through it. `command` is the subcommand name, equal to argv[0] when argc > 0. NULL or empty `command` must behave as the module's help command. Returns 0 on success, nonzero on failure. It must be callable immediately after load with no other setup. + +**const char\* dpm_module_version(void)** +The module's own version as an X.Y.Z string. Consumers state minimum-version requirements against this value. + +**const char\* dpm_module_description(void)** +A one-line human-readable description, shown in module listings. + +**const char\* dpm_module_core_min(void)** +The minimum core version (X.Y.Z) the module supports — the oldest core whose contract and services it was written against. Core refuses to load the module if its own version is lower, and the refusal message says so. + +**const dpm_manifest\* dpm_module_manifest(void)** +A static table declaring the module's entire functional surface: an entry count and, per entry, the API name, its table version, and the exact exported symbol carrying the table — for example { "mymodule", 1, "mymodule_api_v1" }. Only manifest-declared tables are ever handed to consumers; an API absent from the manifest does not exist, even if its symbol does. A module providing no API tables returns a manifest with a count of zero. + +The dpm_manifest and dpm_manifest_entry types, the table header, and the core service declarations all come from the installed public header: + +``` +#include +``` + +## API tables + +A module's functions are published to consumers as API tables: one exported symbol per API version (mymodule_api_v1), pointing to a plain C struct of function pointers. Every table opens with a dpm_api_table_header — the DPM_API_TABLE_MAGIC constant, then the table struct's size in bytes as the module compiled it. Later revisions of the same version may append fields at the tail; the size field lets consumers detect what is present. + +All parameters and return values crossing a table are C types only. State passes through opaque handles; errors are int codes. + +**Symbol naming**: every functional export is prefixed with the module's name (mymodule_\*). The dpm_ prefix is reserved for the contract symbols and core. + +## Validation at load + +Core is the sole authority on module validity, and validation is all-or-nothing. Before a module is offered to anyone, core verifies, in order: every reserved contract symbol resolves; the core-minimum handshake passes; the version and description probes return well-formed values; every manifest-declared symbol resolves; and every declared table carries the correct magic and a sane size. A module failing any step is refused with an itemized reason, visible in the load-failure output. A module that loads is fully valid — consumers never defend against partial states. + +## Building + +A module repository builds with CMake: + +``` +cmake_minimum_required(VERSION 3.22) +project(mymodule) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +add_library(mymodule MODULE mymodule.cpp) + +set_target_properties(mymodule PROPERTIES + PREFIX "" + SUFFIX ".so" +) + +target_link_libraries(mymodule PRIVATE dpm-core) + +install(TARGETS mymodule LIBRARY DESTINATION lib/dpm/modules) +``` + +``` +cmake -B +cmake --build +``` + +libdpm-core is the only DPM link dependency a module ever has. Dependencies on other modules are runtime concerns, resolved through core's require/get_api — a peer module is never linked and never needs to be present to build. + +## Running and testing locally + +Load the freshly built module through a locally run dpm without installing anything: + +``` +dpm --module-path mymodule +``` + +Core runs the full validation sequence on every load, so a contract mistake surfaces here, immediately and itemized, rather than after installation. The --config-dir flag points the module's configuration namespace at local files during development, and --root directs package operations at a scratch tree. + +## Installing + +Modules install to lib/dpm/modules under the install prefix (/usr/lib/dpm/modules on a distribution install). Core discovers the module on its next scan; no registration step exists beyond the file being present and valid. + +## Reference implementation + +The info module bundled with the core repository at src/bundled-modules/info/ is a complete working example of the contract, an API table, and this build structure. diff --git a/include/dpm/core.h b/include/dpm/core.h new file mode 100644 index 0000000..5315d92 --- /dev/null +++ b/include/dpm/core.h @@ -0,0 +1,335 @@ +/** + * @file core.h + * @brief Public C API for libdpm-core + * + * The single entry point for all DPM consumers: the dpm CLI, modules, + * and external programs (build systems, Dark Horse tooling). All types + * crossing this boundary are C types; state passes through opaque + * handles; errors are int codes with per-context detail strings. + * + * @copyright Copyright (c) 2026 SILO GROUP LLC + * @author Chris Punches + * + * Part of the Dark Horse Linux Package Manager (DPM) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#ifndef DPM_CORE_H +#define DPM_CORE_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------------------------------------------------------ */ +/* Export annotation */ +/* ------------------------------------------------------------------ */ + +/** + * Marks the public API visible. The library is compiled with hidden + * default symbol visibility; these functions are its entire exported + * surface. + */ +#ifndef DPM_API +#define DPM_API __attribute__((visibility("default"))) +#endif + +/* ------------------------------------------------------------------ */ +/* Opaque handles */ +/* ------------------------------------------------------------------ */ + +typedef struct dpm_ctx dpm_ctx; +typedef struct dpm_module dpm_module; +typedef struct dpm_cursor dpm_cursor; + +/* ------------------------------------------------------------------ */ +/* Log levels */ +/* ------------------------------------------------------------------ */ + +enum { + DPM_LOG_FATAL = 0, + DPM_LOG_ERROR = 1, + DPM_LOG_WARN = 2, + DPM_LOG_INFO = 3, + DPM_LOG_DEBUG = 4 +}; + +/* ------------------------------------------------------------------ */ +/* Context configuration overrides */ +/* ------------------------------------------------------------------ */ + +/** + * Overrides for dpm_open(). Any field may be left NULL (or -1 for + * log_level) to accept configuration-file values and built-in defaults. + * Every field here is exposed as a dpm CLI flag. + */ +typedef struct dpm_open_overrides { + const char* config_dir; /* NULL = /etc/dpm/conf.d/ */ + const char* module_path; /* NULL = config value, then built-in */ + const char* root; /* NULL = "/" (target root for pkg ops) */ + int log_level; /* -1 = config value; else DPM_LOG_* */ +} dpm_open_overrides; + +/* ------------------------------------------------------------------ */ +/* Module information (enumeration results) */ +/* ------------------------------------------------------------------ */ + +typedef struct dpm_module_info { + const char* name; /* module name (filename minus .so) */ + const char* version; /* module's own X.Y.Z */ + const char* description; /* one-line description */ + const char* core_min; /* minimum core version it supports */ +} dpm_module_info; + +/* ------------------------------------------------------------------ */ +/* Module contract structures (layout fixed by the DPM spec) */ +/* ------------------------------------------------------------------ */ + +/** Magic constant opening every module API table. */ +#define DPM_API_TABLE_MAGIC 0x314D5044u /* "DPM1" */ + +/** + * Every module API table begins with this header: the magic constant, + * then the full size in bytes of the table struct as the exporting + * module compiled it (permits tail-extension within a table version). + */ +typedef struct dpm_api_table_header { + uint32_t magic; + uint32_t size; +} dpm_api_table_header; + +/** One entry of a module's declared functional surface. */ +typedef struct dpm_manifest_entry { + const char* api_name; /* e.g. "raw" */ + int table_version; /* e.g. 1 */ + const char* symbol; /* exact exported symbol carrying the + table, e.g. "raw_api_v1" */ +} dpm_manifest_entry; + +/** A module's manifest: its entire declared functional surface. */ +typedef struct dpm_manifest { + uint32_t count; + const dpm_manifest_entry* entries; +} dpm_manifest; + +/* ------------------------------------------------------------------ */ +/* Context lifecycle */ +/* ------------------------------------------------------------------ */ + +/** + * @brief Creates a core context + * + * Reads configuration from /etc/dpm/conf.d/ (or the overridden config + * directory), resolves the module path (override > config > built-in + * default), and initializes logging per configuration. Performs no + * module loading. Multiple simultaneous contexts with different roots + * are legal. + * + * @param overrides Optional overrides; NULL accepts configuration + * values and built-in defaults + * @return A context handle, or NULL on allocation failure or an + * unreadable/invalid explicit override (a missing default + * config directory is not an error) + */ +DPM_API dpm_ctx* dpm_open(const dpm_open_overrides* overrides); + +/** + * @brief Releases a core context + * + * Unloads every module handle the context issued, closes log targets, + * and frees all memory owned by the context. All handles and strings + * obtained through the context are invalid after this call. + * + * @param ctx The context to release; NULL is a no-op + */ +DPM_API void dpm_close(dpm_ctx* ctx); + +/* ------------------------------------------------------------------ */ +/* Module acquisition */ +/* ------------------------------------------------------------------ */ + +/** + * @brief Loads and returns a validated module + * + * Resolves the named module in the module path and runs the full + * load-time validation sequence if it is not already loaded in this + * context. Modules are loaded at most once per context; repeated + * calls return the same handle. + * + * @param ctx The core context + * @param name The module name (its filename minus .so) + * @param min_version Minimum acceptable module version as X.Y.Z; + * NULL accepts any version + * @return A module handle owned by the context, or NULL on failure + * with the precise reason retrievable via dpm_last_error() + */ +DPM_API dpm_module* dpm_require(dpm_ctx* ctx, const char* name, + const char* min_version); + +/** + * @brief Returns a module's API table for direct typed calls + * + * The table was already validated (manifest cross-check, magic, + * minimum size) at module load. The caller casts the pointer to the + * table struct type for that API and version. The table is valid for + * the life of the context. + * + * @param ctx The core context + * @param mod A module handle from dpm_require() + * @param api_name The API name as declared in the module's manifest + * @param table_version The table version to retrieve + * @return The table pointer, or NULL if the module does not provide + * that api/version pair + */ +DPM_API const void* dpm_get_api(dpm_ctx* ctx, dpm_module* mod, + const char* api_name, int table_version); + +/** + * @brief Dispatches a command to a module + * + * Invokes the module's dpm_module_execute with the context, the + * command, and the argument vector. argv[0] is the command when + * argc > 0; semantics beyond that are the module's to define. + * + * @param ctx The core context + * @param mod A module handle from dpm_require() + * @param command The command name; NULL or empty behaves as the + * module's help command + * @param argc Number of arguments + * @param argv Argument vector + * @return The module's return value verbatim; 0 on success + */ +DPM_API int dpm_execute(dpm_ctx* ctx, dpm_module* mod, const char* command, + int argc, char** argv); + +/* ------------------------------------------------------------------ */ +/* Enumeration */ +/* ------------------------------------------------------------------ */ + +/** + * @brief Enumerates the valid modules in the module path + * + * Scans the module path and validates each candidate .so; failures + * are logged and excluded from the results. + * + * @param ctx The core context + * @return A cursor over all valid modules, or NULL on an unreadable + * module path + */ +DPM_API dpm_cursor* dpm_list_modules(dpm_ctx* ctx); + +/** + * @brief Advances an enumeration cursor + * + * Fills `out` with the next module's name, version, description, and + * minimum-core version; the string pointers remain valid until + * context close. + * + * @param cur The cursor from dpm_list_modules() + * @param out Receives the next module's information + * @return 0 while entries remain; nonzero at end + */ +DPM_API int dpm_cursor_next(dpm_cursor* cur, dpm_module_info* out); + +/** + * @brief Releases an enumeration cursor + * + * @param cur The cursor to release; NULL is a no-op + */ +DPM_API void dpm_cursor_free(dpm_cursor* cur); + +/* ------------------------------------------------------------------ */ +/* Services (available to modules and external consumers alike) */ +/* ------------------------------------------------------------------ */ + +/** + * @brief Returns core's own version + * + * @return Core's version as a static X.Y.Z string; callable without + * a context + */ +DPM_API const char* dpm_core_version(void); + +/** + * @brief Returns a configuration value from a module's namespace + * + * A module's configuration namespace is its own .conf file under the + * context's configuration directory; "core" names core's own file. + * + * @param ctx The core context + * @param module The configuration namespace to read + * @param section The section name within the file + * @param key The key within the section + * @return The configured value, or NULL if unset; valid until + * context close + */ +DPM_API const char* dpm_config_get(dpm_ctx* ctx, const char* module, + const char* section, const char* key); + +/** + * @brief Writes a message to the context's configured log targets + * + * Targets are the console and, when configured, the log file. + * Messages above the configured level are dropped. + * + * @param ctx The core context + * @param level The severity (DPM_LOG_FATAL through DPM_LOG_DEBUG) + * @param message The message to log; NULL is a no-op + */ +DPM_API void dpm_log(dpm_ctx* ctx, int level, const char* message); + +/** + * @brief Returns the resolved module directory path + * + * @param ctx The core context + * @return The module directory path this context resolved + */ +DPM_API const char* dpm_module_path(dpm_ctx* ctx); + +/** + * @brief Returns the most recent failure recorded on the context + * + * @param ctx The core context + * @return A human-readable description of the most recent failure, or + * NULL if none; overwritten by the next failing call + */ +DPM_API const char* dpm_last_error(dpm_ctx* ctx); + +/* ------------------------------------------------------------------ */ +/* Module contract (implemented by modules, called by core) */ +/* ------------------------------------------------------------------ */ + +/* + * Every module exports, as extern "C": + * + * int dpm_module_execute(dpm_ctx* ctx, const char* command, + * int argc, char** argv); + * const char* dpm_module_version(void); + * const char* dpm_module_description(void); + * const char* dpm_module_core_min(void); + * const dpm_manifest* dpm_module_manifest(void); + * + * plus one exported table symbol per manifest entry. Core refuses to + * load any module that does not validate completely (see the DPM + * specification: load-time enforcement). + */ + +#ifdef __cplusplus +} +#endif + +#endif /* DPM_CORE_H */ diff --git a/include/internal/context.hpp b/include/internal/context.hpp new file mode 100644 index 0000000..b3d9c36 --- /dev/null +++ b/include/internal/context.hpp @@ -0,0 +1,74 @@ +/** + * @file context.hpp + * @brief The core context: configuration, logging, module registry + * + * @copyright Copyright (c) 2026 SILO GROUP LLC + * @author Chris Punches + * + * Part of the Dark Horse Linux Package Manager (DPM) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#pragma once + +#include + +#include +#include +#include + +#include "internal/modules.hpp" + +/** @brief A core context: configuration, logging, and the module registry */ +struct dpm_ctx { + std::string config_dir; + std::string module_path; + std::string root; + + int log_level = DPM_LOG_INFO; + bool write_to_log = false; + std::string log_file; + + /* config[module][section][key] = value */ + std::map>> config; + + /* validated modules, keyed by name; loaded at most once per ctx */ + std::map> modules; + + std::string last_error; +}; + +namespace dpmcore { + +/** + * @brief Records a failure reason on the context + * + * @param ctx The core context; NULL is a no-op + * @param msg The failure description + */ +void set_error(dpm_ctx* ctx, const std::string& msg); + +/** + * @brief Loads all configuration files into the context + * + * Parses every .conf file in the context's configuration directory + * into the context's configuration store. + * + * @param ctx The core context + */ +void load_config_dir(dpm_ctx* ctx); + +} // namespace dpmcore diff --git a/include/internal/modules.hpp b/include/internal/modules.hpp new file mode 100644 index 0000000..cd8acfa --- /dev/null +++ b/include/internal/modules.hpp @@ -0,0 +1,74 @@ +/** + * @file modules.hpp + * @brief Module handle, cursor, and loader declarations + * + * @copyright Copyright (c) 2026 SILO GROUP LLC + * @author Chris Punches + * + * Part of the Dark Horse Linux Package Manager (DPM) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#pragma once + +#include + +#include +#include +#include + +/** @brief A loaded, fully validated module */ +struct dpm_module { + std::string name; + void* handle = nullptr; + std::string version; + std::string description; + std::string core_min; + const dpm_manifest* manifest = nullptr; + int (*execute)(dpm_ctx*, const char*, int, char**) = nullptr; +}; + +/** @brief Enumeration cursor over validated modules */ +struct dpm_cursor { + std::vector infos; + size_t idx = 0; +}; + +/** + * @brief Closes a dlopen handle + * + * Keeps handle release beside the loader in one translation unit. + * + * @param handle The handle to close; NULL is a no-op + */ +void dpm_internal_unload(void* handle); + +namespace dpmcore { + +/** + * @brief Runs the full load-time validation sequence against a module + * + * Loads the named module's .so from the context's module path and + * verifies the complete contract. + * + * @param ctx The core context + * @param name The module name + * @param reason Receives the refusal reason on failure + * @return The validated module (caller owns), or nullptr on failure + */ +std::unique_ptr validate_and_load(dpm_ctx* ctx, + const std::string& name, + std::string& reason); + +} // namespace dpmcore diff --git a/include/internal/version.hpp b/include/internal/version.hpp new file mode 100644 index 0000000..f3b3e94 --- /dev/null +++ b/include/internal/version.hpp @@ -0,0 +1,45 @@ +/** + * @file version.hpp + * @brief X.Y.Z version parsing and comparison + * + * @copyright Copyright (c) 2026 SILO GROUP LLC + * @author Chris Punches + * + * Part of the Dark Horse Linux Package Manager (DPM) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#pragma once + +namespace dpmcore { + +/** + * @brief Parses a strict X.Y.Z version string + * + * @param s The version string + * @param out Receives the three parsed components + * @return true on success; false on any malformation + */ +bool parse_version(const char* s, long out[3]); + +/** + * @brief Compares two valid X.Y.Z version strings + * + * @param a First version + * @param b Second version + * @return -1 if a < b, 0 if equal, 1 if a > b + */ +int compare_versions(const char* a, const char* b); + +} // namespace dpmcore diff --git a/src/bundled-modules/info/include/commands.hpp b/src/bundled-modules/info/include/commands.hpp new file mode 100644 index 0000000..be6960c --- /dev/null +++ b/src/bundled-modules/info/include/commands.hpp @@ -0,0 +1,86 @@ +/** + * @file commands.hpp + * @brief Command handlers for the info module + * + * @copyright Copyright (c) 2026 SILO GROUP LLC + * @author Chris Punches + * + * Part of the Dark Horse Linux Package Manager (DPM) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#pragma once + +#include + +/** + * @enum Command + * @brief Commands supported by the info module + */ +enum Command { + CMD_UNKNOWN, /**< Unknown or unsupported command */ + CMD_HELP, /**< Display help information */ + CMD_VERSION, /**< Display core and module versions */ + CMD_SYSTEM, /**< Display system information */ + CMD_CONFIG, /**< Display configuration information */ +}; + +/** + * @brief Parses a command string into a Command enum value + * + * @param cmd_str The command string to parse (NULL/empty means help) + * @return The corresponding Command enum value + */ +Command parse_command(const char* cmd_str); + +/** + * @brief Displays the info module's help text + * + * @param ctx Host core context + * @return 0 on success + */ +int cmd_help(dpm_ctx* ctx); + +/** + * @brief Reports the running core version and the info module version + * + * @param ctx Host core context + * @return 0 on success + */ +int cmd_version(dpm_ctx* ctx); + +/** + * @brief Reports operating system and architecture information + * + * @param ctx Host core context + * @return 0 on success + */ +int cmd_system(dpm_ctx* ctx); + +/** + * @brief Reports core configuration as resolved by the running context + * + * @param ctx Host core context + * @return 0 on success + */ +int cmd_config(dpm_ctx* ctx); + +/** + * @brief Reports an unrecognized command + * + * @param ctx Host core context + * @param command The unrecognized command string + * @return 1 to indicate failure + */ +int cmd_unknown(dpm_ctx* ctx, const char* command); diff --git a/src/bundled-modules/info/info.cpp b/src/bundled-modules/info/info.cpp new file mode 100644 index 0000000..164f6e2 --- /dev/null +++ b/src/bundled-modules/info/info.cpp @@ -0,0 +1,147 @@ +/** + * @file info.cpp + * @brief The info module: contract symbols and command routing + * + * Bundles with core; used for testing and reporting functionality of + * core. Implements the full DPM module contract: the five reserved + * symbols plus a manifest-declared API table. + * + * @copyright Copyright (c) 2026 SILO GROUP LLC + * @author Chris Punches + * + * Part of the Dark Horse Linux Package Manager (DPM) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#include "commands.hpp" + +#define INFO_MODULE_VERSION "0.1.0" +#define INFO_CORE_MIN "0.1.0" + +/* ------------------------------------------------------------------ */ +/* info_api_v1 — typed access surface */ +/* ------------------------------------------------------------------ */ + +/** + * @brief Version 1 API table for the info module + * + * Lets consumers exercise core's typed-access path (require → get_api + * → call) end to end, which is part of this module's purpose of + * testing core functionality. + */ +struct info_api_v1_s { + dpm_api_table_header hdr; + const char* (*version)(void); /**< info module version */ + const char* (*description)(void); /**< info module description */ +}; + +static const char* api_version(void) +{ + return INFO_MODULE_VERSION; +} + +static const char* api_description(void) +{ + return "Reports and tests DPM core functionality."; +} + +extern "C" { + extern const struct info_api_v1_s info_api_v1; + const struct info_api_v1_s info_api_v1 = { + { DPM_API_TABLE_MAGIC, sizeof(struct info_api_v1_s) }, + api_version, + api_description, + }; +} + +/* ------------------------------------------------------------------ */ +/* Reserved contract symbols */ +/* ------------------------------------------------------------------ */ + +/** + * @brief Returns the module's own version + */ +extern "C" const char* dpm_module_version(void) +{ + return INFO_MODULE_VERSION; +} + +/** + * @brief Returns the module's one-line description + */ +extern "C" const char* dpm_module_description(void) +{ + return "Reports and tests DPM core functionality."; +} + +/** + * @brief Returns the minimum core version this module supports + */ +extern "C" const char* dpm_module_core_min(void) +{ + return INFO_CORE_MIN; +} + +/** + * @brief Declares the module's entire functional surface + */ +extern "C" const dpm_manifest* dpm_module_manifest(void) +{ + static const dpm_manifest_entry entries[] = { + { "info", 1, "info_api_v1" }, + }; + static const dpm_manifest manifest = { 1, entries }; + return &manifest; +} + +/** + * @brief Generic command entry point + * + * Routes the command to the appropriate handler. NULL or empty + * command behaves as help. + * + * @param ctx Host core context (reaches core services) + * @param command The command string to execute + * @param argc Number of arguments + * @param argv Array of argument strings (argv[0] is the command) + * @return 0 on success, non-zero on failure + */ +extern "C" int dpm_module_execute(dpm_ctx* ctx, const char* command, + int argc, char** argv) +{ + (void)argc; + (void)argv; + + dpm_log(ctx, DPM_LOG_DEBUG, "Info module execution started."); + + Command cmd = parse_command(command); + + switch (cmd) { + case CMD_VERSION: + return cmd_version(ctx); + + case CMD_SYSTEM: + return cmd_system(ctx); + + case CMD_CONFIG: + return cmd_config(ctx); + + case CMD_HELP: + return cmd_help(ctx); + + case CMD_UNKNOWN: + default: + return cmd_unknown(ctx, command); + } +} diff --git a/src/bundled-modules/info/src/commands.cpp b/src/bundled-modules/info/src/commands.cpp new file mode 100644 index 0000000..a436356 --- /dev/null +++ b/src/bundled-modules/info/src/commands.cpp @@ -0,0 +1,185 @@ +/** + * @file commands.cpp + * @brief Implementation of the info module command handlers + * + * Reports on, and thereby exercises, core functionality: version, + * system details, and configuration as resolved by the host context. + * + * @copyright Copyright (c) 2026 SILO GROUP LLC + * @author Chris Punches + * + * Part of the Dark Horse Linux Package Manager (DPM) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#include "commands.hpp" + +#include +#include +#include +#include + +#define INFO_VERSION "0.1.0" + +namespace { + +std::string detect_architecture() +{ + struct utsname system_info; + if (uname(&system_info) == -1) { + return "Unknown"; + } + return system_info.machine; +} + +std::string detect_os() +{ + struct utsname system_info; + if (uname(&system_info) == -1) { + return "Unknown"; + } + + std::string os = system_info.sysname; + + if (os == "Linux") { + std::ifstream os_release("/etc/os-release"); + if (os_release.is_open()) { + std::string line; + std::string distro_name; + std::string distro_version; + + while (std::getline(os_release, line)) { + if (line.rfind("NAME=", 0) == 0) { + distro_name = line.substr(5); + if (distro_name.size() >= 2 && + distro_name.front() == '"' && + distro_name.back() == '"') { + distro_name = + distro_name.substr(1, distro_name.length() - 2); + } + } + if (line.rfind("VERSION_ID=", 0) == 0) { + distro_version = line.substr(11); + if (distro_version.size() >= 2 && + distro_version.front() == '"' && + distro_version.back() == '"') { + distro_version = + distro_version.substr(1, + distro_version.length() - 2); + } + } + } + + if (!distro_name.empty()) { + os += " (" + distro_name; + if (!distro_version.empty()) { + os += " " + distro_version; + } + os += ")"; + } + } + } + + return os; +} + +} // namespace + +Command parse_command(const char* cmd_str) +{ + if (cmd_str == nullptr || std::strlen(cmd_str) == 0) { + return CMD_HELP; + } + if (std::strcmp(cmd_str, "help") == 0) { + return CMD_HELP; + } + if (std::strcmp(cmd_str, "version") == 0) { + return CMD_VERSION; + } + if (std::strcmp(cmd_str, "system") == 0) { + return CMD_SYSTEM; + } + if (std::strcmp(cmd_str, "config") == 0) { + return CMD_CONFIG; + } + return CMD_UNKNOWN; +} + +int cmd_help(dpm_ctx* ctx) +{ + dpm_log(ctx, DPM_LOG_INFO, "DPM Info Module - Reports and tests DPM core functionality."); + dpm_log(ctx, DPM_LOG_INFO, ""); + dpm_log(ctx, DPM_LOG_INFO, "Available commands:"); + dpm_log(ctx, DPM_LOG_INFO, ""); + dpm_log(ctx, DPM_LOG_INFO, " version - Display core and module version information"); + dpm_log(ctx, DPM_LOG_INFO, " system - Display system information"); + dpm_log(ctx, DPM_LOG_INFO, " config - Display configuration as resolved by core"); + dpm_log(ctx, DPM_LOG_INFO, " help - Display this help message"); + dpm_log(ctx, DPM_LOG_INFO, ""); + return 0; +} + +int cmd_version(dpm_ctx* ctx) +{ + std::string core_msg = "libdpm-core Version: "; + core_msg += dpm_core_version(); + dpm_log(ctx, DPM_LOG_INFO, core_msg.c_str()); + + std::string info_msg = "Info Module Version: "; + info_msg += INFO_VERSION; + dpm_log(ctx, DPM_LOG_INFO, info_msg.c_str()); + + return 0; +} + +int cmd_system(dpm_ctx* ctx) +{ + dpm_log(ctx, DPM_LOG_INFO, "System Information:"); + + std::string os_msg = " OS: "; + os_msg += detect_os(); + dpm_log(ctx, DPM_LOG_INFO, os_msg.c_str()); + + std::string arch_msg = " Architecture: "; + arch_msg += detect_architecture(); + dpm_log(ctx, DPM_LOG_INFO, arch_msg.c_str()); + + return 0; +} + +int cmd_config(dpm_ctx* ctx) +{ + dpm_log(ctx, DPM_LOG_INFO, "Configuration Information:"); + + const char* configured_path = dpm_config_get(ctx, "core", "modules", "path"); + std::string configured_msg = " Configured module path (core.conf): "; + configured_msg += configured_path ? configured_path : "not configured"; + dpm_log(ctx, DPM_LOG_INFO, configured_msg.c_str()); + + const char* active_path = dpm_module_path(ctx); + std::string active_msg = " Active module path: "; + active_msg += active_path ? active_path : "unknown"; + dpm_log(ctx, DPM_LOG_INFO, active_msg.c_str()); + + return 0; +} + +int cmd_unknown(dpm_ctx* ctx, const char* command) +{ + std::string msg = "Unknown command: "; + msg += (command ? command : ""); + dpm_log(ctx, DPM_LOG_WARN, msg.c_str()); + dpm_log(ctx, DPM_LOG_WARN, "Run 'dpm info help' for a list of available commands"); + return 1; +} diff --git a/src/cli/dpm.cpp b/src/cli/dpm.cpp new file mode 100644 index 0000000..ac65491 --- /dev/null +++ b/src/cli/dpm.cpp @@ -0,0 +1,265 @@ +/** + * @file dpm.cpp + * @brief The dpm CLI: argument parsing and printing over libdpm-core + * + * Thin client of libdpm-core. Every field of the dpm_open_overrides + * struct is exposed as a flag; subcommands map onto library calls; the + * command surface is exactly the set of loadable modules. + * + * @copyright Copyright (c) 2026 SILO GROUP LLC + * @author Chris Punches + * + * Part of the Dark Horse Linux Package Manager (DPM) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#include + +#include +#include +#include +#include +#include + +namespace { + +/** + * @brief Prints the CLI usage message + */ +void show_help() +{ + std::printf( + "Usage: dpm [options] [module] [module args...]\n" + "\n" + "Options:\n" + " -c, --config-dir PATH Configuration directory (default /etc/dpm/conf.d/)\n" + " -m, --module-path PATH Module directory (overrides configuration)\n" + " -r, --root PATH Target root for package operations (default /)\n" + " -L, --log-level LEVEL FATAL, ERROR, WARN, INFO, or DEBUG\n" + " -l, --list-modules List available modules\n" + " -h, --help Show this help message\n" + "\n" + "For module-specific help, use: dpm help\n"); +} + +/** + * @brief Parses a log level name + * + * @param name The level name (case-insensitive) + * @return The DPM_LOG_* level, or -1 if unrecognized + */ +int level_from_name(const char* name) +{ + if (strcasecmp(name, "FATAL") == 0) { return DPM_LOG_FATAL; } + if (strcasecmp(name, "ERROR") == 0) { return DPM_LOG_ERROR; } + if (strcasecmp(name, "WARN") == 0) { return DPM_LOG_WARN; } + if (strcasecmp(name, "INFO") == 0) { return DPM_LOG_INFO; } + if (strcasecmp(name, "DEBUG") == 0) { return DPM_LOG_DEBUG; } + return -1; +} + +/** + * @brief Matches an argument against an option's short and long forms + * + * Recognizes the separate-value forms and the --option=value form. + * + * @param arg The command-line argument to test + * @param short_form The option's short form (e.g. "-c") + * @param long_form The option's long form (e.g. "--config-dir") + * @param inline_value Receives the text after '=' for the inline + * form, or NULL when the value is in the next + * argument + * @return true if the argument is this option + */ +bool option_matches(const char* arg, const char* short_form, + const char* long_form, const char** inline_value) +{ + if (std::strcmp(arg, short_form) == 0 || + std::strcmp(arg, long_form) == 0) { + *inline_value = nullptr; + return true; + } + + size_t len = std::strlen(long_form); + if (std::strncmp(arg, long_form, len) == 0 && arg[len] == '=') { + *inline_value = arg + len + 1; + return true; + } + + return false; +} + +/** + * @brief Prints the table of available modules + * + * @param ctx The core context + * @return 0 on success, 1 on failure + */ +int list_modules(dpm_ctx* ctx) +{ + dpm_cursor* cur = dpm_list_modules(ctx); + if (!cur) { + const char* err = dpm_last_error(ctx); + std::fprintf(stderr, "dpm: %s\n", err ? err : "module listing failed"); + return 1; + } + + std::vector infos; + dpm_module_info info; + while (dpm_cursor_next(cur, &info) == 0) { + infos.push_back(info); + } + dpm_cursor_free(cur); + + if (infos.empty()) { + std::printf("No valid modules found in %s\n", dpm_module_path(ctx)); + return 0; + } + + size_t name_w = std::strlen("MODULE"); + size_t version_w = std::strlen("VERSION"); + for (const auto& i : infos) { + name_w = std::max(name_w, std::strlen(i.name)); + version_w = std::max(version_w, std::strlen(i.version)); + } + + std::printf("Available DPM modules:\n\n"); + std::printf("%-*s %-*s %s\n", + static_cast(name_w), "MODULE", + static_cast(version_w), "VERSION", + "DESCRIPTION"); + for (const auto& i : infos) { + std::printf("%-*s %-*s %s\n", + static_cast(name_w), i.name, + static_cast(version_w), i.version, + i.description); + } + std::printf("\nUse 'dpm help' for module-specific help.\n"); + + return 0; +} + +} // namespace + +int main(int argc, char** argv) +{ + dpm_open_overrides overrides = {nullptr, nullptr, nullptr, -1}; + bool list = false; + + /* Holders for --opt=value forms. */ + std::string config_dir; + std::string module_path; + std::string root; + + int i = 1; + for (; i < argc; i++) { + const char* arg = argv[i]; + if (arg[0] != '-') { + break; + } + + /* Yields the option's value: the inline "=value" text if + present, otherwise the next argument. Prints an error and + returns nullptr when no value exists. */ + const char* inline_value = nullptr; + auto take_value = [&]() -> const char* { + if (inline_value) { + return inline_value; + } + if (i + 1 < argc) { + return argv[++i]; + } + std::fprintf(stderr, "dpm: option '%s' requires a value\n", arg); + return nullptr; + }; + + if (option_matches(arg, "-c", "--config-dir", &inline_value)) { + const char* v = take_value(); + if (!v) { return 1; } + config_dir = v; + overrides.config_dir = config_dir.c_str(); + } else if (option_matches(arg, "-m", "--module-path", &inline_value)) { + const char* v = take_value(); + if (!v) { return 1; } + module_path = v; + overrides.module_path = module_path.c_str(); + } else if (option_matches(arg, "-r", "--root", &inline_value)) { + const char* v = take_value(); + if (!v) { return 1; } + root = v; + overrides.root = root.c_str(); + } else if (option_matches(arg, "-L", "--log-level", &inline_value)) { + const char* v = take_value(); + if (!v) { return 1; } + int level = level_from_name(v); + if (level < 0) { + std::fprintf(stderr, + "dpm: unknown log level '%s' (use FATAL, ERROR, " + "WARN, INFO, or DEBUG)\n", v); + return 1; + } + overrides.log_level = level; + } else if (std::strcmp(arg, "-l") == 0 || + std::strcmp(arg, "--list-modules") == 0) { + list = true; + } else if (std::strcmp(arg, "-h") == 0 || + std::strcmp(arg, "--help") == 0) { + show_help(); + return 0; + } else { + std::fprintf(stderr, "dpm: unknown option '%s'\n\n", arg); + show_help(); + return 1; + } + } + + dpm_ctx* ctx = dpm_open(&overrides); + if (!ctx) { + std::fprintf(stderr, + "dpm: initialization failed — check that override paths " + "exist and are readable\n"); + return 1; + } + + if (list) { + int rc = list_modules(ctx); + dpm_close(ctx); + return rc; + } + + if (i >= argc) { + show_help(); + dpm_close(ctx); + return 0; + } + + const char* module_name = argv[i]; + char** module_argv = &argv[i + 1]; + int module_argc = argc - i - 1; + + dpm_module* mod = dpm_require(ctx, module_name, nullptr); + if (!mod) { + const char* err = dpm_last_error(ctx); + std::fprintf(stderr, "dpm: %s\n", + err ? err : "module could not be loaded"); + dpm_close(ctx); + return 1; + } + + const char* command = module_argc > 0 ? module_argv[0] : nullptr; + int rc = dpm_execute(ctx, mod, command, module_argc, module_argv); + + dpm_close(ctx); + return rc; +} diff --git a/src/context.cpp b/src/context.cpp new file mode 100644 index 0000000..52ec7a4 --- /dev/null +++ b/src/context.cpp @@ -0,0 +1,336 @@ +/** + * @file context.cpp + * @brief Context lifecycle, configuration, logging, and services + * + * @copyright Copyright (c) 2026 SILO GROUP LLC + * @author Chris Punches + * + * Part of the Dark Horse Linux Package Manager (DPM) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#include "internal/context.hpp" + +#include "internal/version.hpp" + +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +#ifndef DPM_CORE_VERSION_STR +#define DPM_CORE_VERSION_STR "0.0.0" +#endif + +namespace { + +const char* DEFAULT_CONFIG_DIR = "/etc/dpm/conf.d/"; +const char* DEFAULT_MODULE_PATH = "/usr/lib/dpm/modules/"; +const char* DEFAULT_LOG_FILE = "/var/log/dpm/dpm.log"; + +std::string trim(const std::string& s) +{ + const char* ws = " \t\r\n\f\v"; + size_t start = s.find_first_not_of(ws); + if (start == std::string::npos) { + return ""; + } + size_t end = s.find_last_not_of(ws); + return s.substr(start, end - start + 1); +} + +std::string with_trailing_slash(std::string s) +{ + if (!s.empty() && s.back() != '/') { + s += '/'; + } + return s; +} + +bool parse_bool(const std::string& v, bool fallback) +{ + std::string lower; + for (char c : v) { + lower += static_cast(std::tolower(static_cast(c))); + } + if (lower == "true" || lower == "yes" || lower == "1" || lower == "on") { + return true; + } + if (lower == "false" || lower == "no" || lower == "0" || lower == "off") { + return false; + } + return fallback; +} + +int level_from_string(const std::string& v, int fallback) +{ + if (v == "FATAL") { return DPM_LOG_FATAL; } + if (v == "ERROR") { return DPM_LOG_ERROR; } + if (v == "WARN") { return DPM_LOG_WARN; } + if (v == "INFO") { return DPM_LOG_INFO; } + if (v == "DEBUG") { return DPM_LOG_DEBUG; } + return fallback; +} + +const char* level_name(int level) +{ + switch (level) { + case DPM_LOG_FATAL: return "FATAL"; + case DPM_LOG_ERROR: return "ERROR"; + case DPM_LOG_WARN: return "WARN"; + case DPM_LOG_INFO: return "INFO"; + case DPM_LOG_DEBUG: return "DEBUG"; + default: return "UNKNOWN"; + } +} + +void parse_config_file(dpm_ctx* ctx, const fs::path& file, + const std::string& module_name) +{ + std::ifstream in(file); + if (!in.is_open()) { + return; + } + + std::string line; + std::string section = "main"; + + while (std::getline(in, line)) { + line = trim(line); + + if (line.empty() || line[0] == '#' || line[0] == ';') { + continue; + } + + if (line.front() == '[' && line.back() == ']') { + std::string name = trim(line.substr(1, line.length() - 2)); + section = name.empty() ? "main" : name; + continue; + } + + size_t eq = line.find('='); + if (eq == std::string::npos) { + continue; + } + + std::string key = trim(line.substr(0, eq)); + std::string value = trim(line.substr(eq + 1)); + if (key.empty()) { + continue; + } + + ctx->config[module_name][section][key] = value; + } +} + +} // namespace + +namespace dpmcore { + +void set_error(dpm_ctx* ctx, const std::string& msg) +{ + if (ctx) { + ctx->last_error = msg; + } +} + +void load_config_dir(dpm_ctx* ctx) +{ + std::error_code ec; + if (!fs::is_directory(ctx->config_dir, ec)) { + return; + } + + for (const auto& entry : fs::directory_iterator(ctx->config_dir, ec)) { + if (ec) { + break; + } + if (!entry.is_regular_file()) { + continue; + } + if (entry.path().extension() != ".conf") { + continue; + } + parse_config_file(ctx, entry.path(), entry.path().stem().string()); + } +} + +} // namespace dpmcore + +extern "C" { + +dpm_ctx* dpm_open(const dpm_open_overrides* overrides) +{ + /* Validate explicit overrides before allocating anything. */ + if (overrides) { + if (overrides->config_dir && *overrides->config_dir) { + std::error_code ec; + if (!fs::is_directory(overrides->config_dir, ec)) { + return nullptr; + } + } + if (overrides->log_level < -1 || overrides->log_level > DPM_LOG_DEBUG) { + return nullptr; + } + } + + dpm_ctx* ctx = new (std::nothrow) dpm_ctx; + if (!ctx) { + return nullptr; + } + + /* Config directory: override > default. */ + ctx->config_dir = DEFAULT_CONFIG_DIR; + if (overrides && overrides->config_dir && *overrides->config_dir) { + ctx->config_dir = with_trailing_slash(overrides->config_dir); + } + + dpmcore::load_config_dir(ctx); + + /* Logging: config, then override. */ + ctx->log_level = DPM_LOG_INFO; + ctx->write_to_log = false; + ctx->log_file = DEFAULT_LOG_FILE; + + if (const char* v = dpm_config_get(ctx, "core", "logging", "log_level")) { + ctx->log_level = level_from_string(v, DPM_LOG_INFO); + } + if (const char* v = dpm_config_get(ctx, "core", "logging", "write_to_log")) { + ctx->write_to_log = parse_bool(v, false); + } + if (const char* v = dpm_config_get(ctx, "core", "logging", "log_file")) { + ctx->log_file = v; + } + if (overrides && overrides->log_level >= 0) { + ctx->log_level = overrides->log_level; + } + + /* Module path: override > config > default. */ + ctx->module_path = DEFAULT_MODULE_PATH; + if (const char* v = dpm_config_get(ctx, "core", "modules", "path")) { + ctx->module_path = with_trailing_slash(v); + } + if (overrides && overrides->module_path && *overrides->module_path) { + ctx->module_path = with_trailing_slash(overrides->module_path); + } + + /* Target root: override > default. */ + ctx->root = "/"; + if (overrides && overrides->root && *overrides->root) { + ctx->root = overrides->root; + } + + return ctx; +} + +void dpm_close(dpm_ctx* ctx) +{ + if (!ctx) { + return; + } + /* dpm_module destructors do not dlclose; do it here so the + registry teardown order is explicit. */ + for (auto& [name, mod] : ctx->modules) { + if (mod->handle) { + dpm_internal_unload(mod->handle); + } + } + delete ctx; +} + +const char* dpm_core_version(void) +{ + return DPM_CORE_VERSION_STR; +} + +const char* dpm_config_get(dpm_ctx* ctx, const char* module, + const char* section, const char* key) +{ + if (!ctx || !module || !section || !key) { + return nullptr; + } + + auto mod_it = ctx->config.find(module); + if (mod_it == ctx->config.end()) { + return nullptr; + } + + auto sec_it = mod_it->second.find(section); + if (sec_it == mod_it->second.end()) { + return nullptr; + } + + auto key_it = sec_it->second.find(key); + if (key_it == sec_it->second.end()) { + return nullptr; + } + + return key_it->second.c_str(); +} + +void dpm_log(dpm_ctx* ctx, int level, const char* message) +{ + if (!ctx || !message) { + return; + } + if (level < DPM_LOG_FATAL || level > DPM_LOG_DEBUG) { + level = DPM_LOG_INFO; + } + if (level > ctx->log_level) { + return; + } + + if (level <= DPM_LOG_WARN) { + std::fprintf(stderr, "%s: %s\n", level_name(level), message); + } else { + std::fprintf(stdout, "%s\n", message); + } + + if (ctx->write_to_log) { + std::ofstream out(ctx->log_file, std::ios::app); + if (out.is_open()) { + char stamp[32]; + std::time_t now = std::time(nullptr); + std::strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", + std::localtime(&now)); + out << stamp << " [" << level_name(level) << "] " + << message << "\n"; + } else { + /* Log-file trouble never fails the operation; disable and + continue on console alone. */ + ctx->write_to_log = false; + } + } +} + +const char* dpm_module_path(dpm_ctx* ctx) +{ + if (!ctx) { + return nullptr; + } + return ctx->module_path.c_str(); +} + +const char* dpm_last_error(dpm_ctx* ctx) +{ + if (!ctx || ctx->last_error.empty()) { + return nullptr; + } + return ctx->last_error.c_str(); +} + +} /* extern "C" */ diff --git a/src/libdpm-core.map b/src/libdpm-core.map new file mode 100644 index 0000000..6f35a89 --- /dev/null +++ b/src/libdpm-core.map @@ -0,0 +1,18 @@ +DPM_CORE_1.0 { + global: + dpm_open; + dpm_close; + dpm_require; + dpm_get_api; + dpm_execute; + dpm_list_modules; + dpm_cursor_next; + dpm_cursor_free; + dpm_core_version; + dpm_config_get; + dpm_log; + dpm_module_path; + dpm_last_error; + local: + *; +}; diff --git a/src/modules.cpp b/src/modules.cpp new file mode 100644 index 0000000..0d09136 --- /dev/null +++ b/src/modules.cpp @@ -0,0 +1,370 @@ +/** + * @file modules.cpp + * @brief Module discovery, load-time validation, routing, enumeration + * + * Implements the load-time enforcement sequence: core is the sole + * authority on module validity. A module is either fully valid or not + * loaded — no partial states. + * + * @copyright Copyright (c) 2026 SILO GROUP LLC + * @author Chris Punches + * + * Part of the Dark Horse Linux Package Manager (DPM) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#include "internal/context.hpp" + +#include "internal/version.hpp" + +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +#ifndef DPM_CORE_VERSION_STR +#define DPM_CORE_VERSION_STR "0.0.0" +#endif + +/* dlclose wrapper referenced from context.cpp so handle release stays + in one translation unit with the loader. */ +void dpm_internal_unload(void* handle) +{ + if (handle) { + dlclose(handle); + } +} + +namespace { + +using execute_fn = int (*)(dpm_ctx*, const char*, int, char**); +using string_fn = const char* (*)(void); +using manifest_fn = const dpm_manifest* (*)(void); + +/** dlsym with dlerror() discipline; returns nullptr on any error. */ +void* resolve(void* handle, const char* symbol) +{ + dlerror(); + void* addr = dlsym(handle, symbol); + if (dlerror() != nullptr) { + return nullptr; + } + return addr; +} + +} // namespace + +namespace dpmcore { + +std::unique_ptr validate_and_load(dpm_ctx* ctx, + const std::string& name, + std::string& reason) +{ + std::string so_path = ctx->module_path + name + ".so"; + + std::error_code ec; + if (!fs::exists(so_path, ec)) { + reason = "not found at " + so_path; + return nullptr; + } + + void* handle = dlopen(so_path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!handle) { + const char* err = dlerror(); + reason = std::string("dlopen failed: ") + (err ? err : "unknown"); + return nullptr; + } + + /* Step 1: resolve all reserved contract symbols. */ + static const char* required[] = { + "dpm_module_execute", + "dpm_module_version", + "dpm_module_description", + "dpm_module_core_min", + "dpm_module_manifest", + }; + + std::string missing; + for (const char* sym : required) { + if (!resolve(handle, sym)) { + if (!missing.empty()) { + missing += ", "; + } + missing += sym; + } + } + if (!missing.empty()) { + reason = "missing required contract symbols: " + missing; + dlclose(handle); + return nullptr; + } + + auto exec_f = reinterpret_cast(resolve(handle, "dpm_module_execute")); + auto version_f = reinterpret_cast(resolve(handle, "dpm_module_version")); + auto desc_f = reinterpret_cast(resolve(handle, "dpm_module_description")); + auto core_min_f = reinterpret_cast(resolve(handle, "dpm_module_core_min")); + auto manifest_f = reinterpret_cast(resolve(handle, "dpm_module_manifest")); + + /* Step 2: core-minimum handshake. */ + const char* core_min = core_min_f(); + long parsed[3]; + if (!core_min || !parse_version(core_min, parsed)) { + reason = "dpm_module_core_min() returned a malformed version"; + dlclose(handle); + return nullptr; + } + if (compare_versions(core_min, DPM_CORE_VERSION_STR) > 0) { + reason = std::string("requires core >= ") + core_min + + ", running core is " DPM_CORE_VERSION_STR " — update core"; + dlclose(handle); + return nullptr; + } + + /* Step 3: probe the cheap calls. */ + const char* version = version_f(); + if (!version || !parse_version(version, parsed)) { + reason = "dpm_module_version() returned a malformed version"; + dlclose(handle); + return nullptr; + } + const char* description = desc_f(); + if (!description || !*description) { + reason = "dpm_module_description() returned nothing"; + dlclose(handle); + return nullptr; + } + + /* Step 4: cross-check the manifest. */ + const dpm_manifest* manifest = manifest_f(); + if (!manifest) { + reason = "dpm_module_manifest() returned NULL"; + dlclose(handle); + return nullptr; + } + if (manifest->count > 0 && !manifest->entries) { + reason = "manifest declares entries but the entry table is NULL"; + dlclose(handle); + return nullptr; + } + + for (uint32_t i = 0; i < manifest->count; i++) { + const dpm_manifest_entry& entry = manifest->entries[i]; + + if (!entry.api_name || !*entry.api_name || + !entry.symbol || !*entry.symbol || entry.table_version < 1) { + reason = "manifest entry " + std::to_string(i) + " is malformed"; + dlclose(handle); + return nullptr; + } + + void* table = resolve(handle, entry.symbol); + if (!table) { + reason = std::string("manifest declares API '") + entry.api_name + + "' v" + std::to_string(entry.table_version) + + "' at symbol '" + entry.symbol + + "' but the symbol does not resolve"; + dlclose(handle); + return nullptr; + } + + /* Step 5: table sanity. */ + auto* header = static_cast(table); + if (header->magic != DPM_API_TABLE_MAGIC) { + reason = std::string("API table '") + entry.symbol + + "' has a bad magic constant"; + dlclose(handle); + return nullptr; + } + if (header->size < sizeof(dpm_api_table_header)) { + reason = std::string("API table '") + entry.symbol + + "' reports an impossible size"; + dlclose(handle); + return nullptr; + } + } + + auto mod = std::make_unique(); + mod->name = name; + mod->handle = handle; + mod->version = version; + mod->description = description; + mod->core_min = core_min; + mod->manifest = manifest; + mod->execute = exec_f; + return mod; +} + +} // namespace dpmcore + +extern "C" { + +dpm_module* dpm_require(dpm_ctx* ctx, const char* name, + const char* min_version) +{ + if (!ctx || !name || !*name) { + return nullptr; + } + + long parsed[3]; + if (min_version && !dpmcore::parse_version(min_version, parsed)) { + dpmcore::set_error(ctx, std::string("malformed minimum version: ") + + min_version); + return nullptr; + } + + dpm_module* mod = nullptr; + auto it = ctx->modules.find(name); + if (it != ctx->modules.end()) { + mod = it->second.get(); + } else { + std::string reason; + auto loaded = dpmcore::validate_and_load(ctx, name, reason); + if (!loaded) { + dpmcore::set_error(ctx, std::string("module '") + name + + "': " + reason); + return nullptr; + } + mod = loaded.get(); + ctx->modules[name] = std::move(loaded); + } + + if (min_version && + dpmcore::compare_versions(mod->version.c_str(), min_version) < 0) { + dpmcore::set_error(ctx, std::string("module '") + name + + "' is version " + mod->version + + ", below required minimum " + min_version); + return nullptr; + } + + return mod; +} + +const void* dpm_get_api(dpm_ctx* ctx, dpm_module* mod, + const char* api_name, int table_version) +{ + if (!ctx || !mod || !api_name) { + return nullptr; + } + + for (uint32_t i = 0; i < mod->manifest->count; i++) { + const dpm_manifest_entry& entry = mod->manifest->entries[i]; + if (entry.table_version == table_version && + std::string(entry.api_name) == api_name) { + dlerror(); + void* table = dlsym(mod->handle, entry.symbol); + if (dlerror() != nullptr || !table) { + dpmcore::set_error(ctx, std::string("API table symbol '") + + entry.symbol + "' vanished after load"); + return nullptr; + } + return table; + } + } + + dpmcore::set_error(ctx, std::string("module '") + mod->name + + "' does not provide API '" + api_name + + "' v" + std::to_string(table_version)); + return nullptr; +} + +int dpm_execute(dpm_ctx* ctx, dpm_module* mod, const char* command, + int argc, char** argv) +{ + if (!ctx || !mod || !mod->execute) { + return 1; + } + return mod->execute(ctx, command, argc, argv); +} + +dpm_cursor* dpm_list_modules(dpm_ctx* ctx) +{ + if (!ctx) { + return nullptr; + } + + std::error_code ec; + if (!fs::is_directory(ctx->module_path, ec)) { + dpmcore::set_error(ctx, "module path is not a readable directory: " + + ctx->module_path); + return nullptr; + } + + std::set names; + for (const auto& entry : fs::directory_iterator(ctx->module_path, ec)) { + if (ec) { + break; + } + if (!entry.is_regular_file() && !entry.is_symlink()) { + continue; + } + if (entry.path().extension() != ".so") { + continue; + } + names.insert(entry.path().stem().string()); + } + + auto* cur = new (std::nothrow) dpm_cursor; + if (!cur) { + return nullptr; + } + + for (const std::string& name : names) { + dpm_module* mod = nullptr; + + auto it = ctx->modules.find(name); + if (it != ctx->modules.end()) { + mod = it->second.get(); + } else { + std::string reason; + auto loaded = dpmcore::validate_and_load(ctx, name, reason); + if (!loaded) { + dpm_log(ctx, DPM_LOG_WARN, + ("module '" + name + "' failed validation: " + + reason).c_str()); + continue; + } + mod = loaded.get(); + ctx->modules[name] = std::move(loaded); + } + + dpm_module_info info; + info.name = mod->name.c_str(); + info.version = mod->version.c_str(); + info.description = mod->description.c_str(); + info.core_min = mod->core_min.c_str(); + cur->infos.push_back(info); + } + + return cur; +} + +int dpm_cursor_next(dpm_cursor* cur, dpm_module_info* out) +{ + if (!cur || !out || cur->idx >= cur->infos.size()) { + return 1; + } + *out = cur->infos[cur->idx]; + cur->idx++; + return 0; +} + +void dpm_cursor_free(dpm_cursor* cur) +{ + delete cur; +} + +} /* extern "C" */ diff --git a/src/version.cpp b/src/version.cpp new file mode 100644 index 0000000..6ff1d4b --- /dev/null +++ b/src/version.cpp @@ -0,0 +1,83 @@ +/** + * @file version.cpp + * @brief X.Y.Z version parsing and comparison + * + * @copyright Copyright (c) 2026 SILO GROUP LLC + * @author Chris Punches + * + * Part of the Dark Horse Linux Package Manager (DPM) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#include "internal/version.hpp" + +#include +#include + +namespace dpmcore { + +bool parse_version(const char* s, long out[3]) +{ + if (!s || !*s) { + return false; + } + + const char* p = s; + for (int i = 0; i < 3; i++) { + if (!std::isdigit(static_cast(*p))) { + return false; + } + + char* end = nullptr; + out[i] = std::strtol(p, &end, 10); + if (out[i] < 0) { + return false; + } + + if (i < 2) { + if (*end != '.') { + return false; + } + p = end + 1; + } else { + if (*end != '\0') { + return false; + } + } + } + + return true; +} + +int compare_versions(const char* a, const char* b) +{ + long va[3] = {0, 0, 0}; + long vb[3] = {0, 0, 0}; + + parse_version(a, va); + parse_version(b, vb); + + for (int i = 0; i < 3; i++) { + if (va[i] < vb[i]) { + return -1; + } + if (va[i] > vb[i]) { + return 1; + } + } + + return 0; +} + +} // namespace dpmcore diff --git a/tests/fixtures/conf/core.conf b/tests/fixtures/conf/core.conf new file mode 100644 index 0000000..12f2db2 --- /dev/null +++ b/tests/fixtures/conf/core.conf @@ -0,0 +1,6 @@ +[logging] +log_level = ERROR +write_to_log = false + +[modules] +path = /nonexistent/from/config diff --git a/tests/fixtures/conf/testmod.conf b/tests/fixtures/conf/testmod.conf new file mode 100644 index 0000000..346078c --- /dev/null +++ b/tests/fixtures/conf/testmod.conf @@ -0,0 +1,5 @@ +[main] +key = value + +[section2] +other = 42 diff --git a/tests/fixtures/src/bad_magic.cpp b/tests/fixtures/src/bad_magic.cpp new file mode 100644 index 0000000..2d4cfa8 --- /dev/null +++ b/tests/fixtures/src/bad_magic.cpp @@ -0,0 +1,95 @@ +/** + * @file bad_magic.cpp + * @brief Broken fixture: API table with a wrong magic constant + * + * Contract-complete, but its declared table opens with garbage instead + * of the spec magic. Core must refuse it at validation step 5. + * + * Part of the Dark Horse Linux Package Manager (DPM) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#include + +namespace { + +struct table_header { + uint32_t magic; + uint32_t size; +}; + +struct manifest_entry { + const char* api_name; + int table_version; + const char* symbol; +}; + +struct manifest { + uint32_t count; + const manifest_entry* entries; +}; + +} // namespace + +struct badmagic_api_v1_s { + table_header hdr; + int (*ping)(void); +}; + +static int ping(void) +{ + return 0; +} + +extern "C" { + extern const struct badmagic_api_v1_s badmagic_api_v1; + const struct badmagic_api_v1_s badmagic_api_v1 = { + { 0xDEADBEEFu, sizeof(struct badmagic_api_v1_s) }, + ping, + }; +} + +extern "C" const char* dpm_module_version(void) +{ + return "1.0.0"; +} + +extern "C" const char* dpm_module_description(void) +{ + return "Fixture with a bad table magic."; +} + +extern "C" const char* dpm_module_core_min(void) +{ + return "0.1.0"; +} + +extern "C" const void* dpm_module_manifest(void) +{ + static const manifest_entry entries[] = { + { "badmagic", 1, "badmagic_api_v1" }, + }; + static const manifest m = { 1, entries }; + return &m; +} + +extern "C" int dpm_module_execute(void* ctx, const char* command, + int argc, char** argv) +{ + (void)ctx; + (void)command; + (void)argc; + (void)argv; + return 0; +} diff --git a/tests/fixtures/src/bad_version.cpp b/tests/fixtures/src/bad_version.cpp new file mode 100644 index 0000000..7b5c84d --- /dev/null +++ b/tests/fixtures/src/bad_version.cpp @@ -0,0 +1,69 @@ +/** + * @file bad_version.cpp + * @brief Broken fixture: malformed module version string + * + * Contract-complete, but dpm_module_version() returns something that + * is not X.Y.Z. Core must refuse it at validation step 3. + * + * Part of the Dark Horse Linux Package Manager (DPM) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#include + +namespace { + +struct manifest_entry { + const char* api_name; + int table_version; + const char* symbol; +}; + +struct manifest { + uint32_t count; + const manifest_entry* entries; +}; + +} // namespace + +extern "C" const char* dpm_module_version(void) +{ + return "banana"; +} + +extern "C" const char* dpm_module_description(void) +{ + return "Fixture with a malformed version."; +} + +extern "C" const char* dpm_module_core_min(void) +{ + return "0.1.0"; +} + +extern "C" const void* dpm_module_manifest(void) +{ + static const manifest m = { 0, nullptr }; + return &m; +} + +extern "C" int dpm_module_execute(void* ctx, const char* command, + int argc, char** argv) +{ + (void)ctx; + (void)command; + (void)argc; + (void)argv; + return 0; +} diff --git a/tests/fixtures/src/core_too_new.cpp b/tests/fixtures/src/core_too_new.cpp new file mode 100644 index 0000000..7cff1b0 --- /dev/null +++ b/tests/fixtures/src/core_too_new.cpp @@ -0,0 +1,70 @@ +/** + * @file core_too_new.cpp + * @brief Broken fixture: demands a core newer than any that exists + * + * Contract-complete, but dpm_module_core_min() reports 99.0.0. Core + * must refuse it at validation step 2 with a message naming the + * remedy (update core). + * + * Part of the Dark Horse Linux Package Manager (DPM) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#include + +namespace { + +struct manifest_entry { + const char* api_name; + int table_version; + const char* symbol; +}; + +struct manifest { + uint32_t count; + const manifest_entry* entries; +}; + +} // namespace + +extern "C" const char* dpm_module_version(void) +{ + return "1.0.0"; +} + +extern "C" const char* dpm_module_description(void) +{ + return "Fixture demanding a future core."; +} + +extern "C" const char* dpm_module_core_min(void) +{ + return "99.0.0"; +} + +extern "C" const void* dpm_module_manifest(void) +{ + static const manifest m = { 0, nullptr }; + return &m; +} + +extern "C" int dpm_module_execute(void* ctx, const char* command, + int argc, char** argv) +{ + (void)ctx; + (void)command; + (void)argc; + (void)argv; + return 0; +} diff --git a/tests/fixtures/src/good.cpp b/tests/fixtures/src/good.cpp new file mode 100644 index 0000000..498e1e1 --- /dev/null +++ b/tests/fixtures/src/good.cpp @@ -0,0 +1,96 @@ +/** + * @file good.cpp + * @brief Known-good stub module fixture + * + * A complete, valid DPM module written against the documented module + * contract with its own declarations — no core headers — exactly as a + * standalone module author would. Used to validate core's happy path. + * + * Part of the Dark Horse Linux Package Manager (DPM) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#include + +namespace { + +struct table_header { + uint32_t magic; + uint32_t size; +}; + +struct manifest_entry { + const char* api_name; + int table_version; + const char* symbol; +}; + +struct manifest { + uint32_t count; + const manifest_entry* entries; +}; + +} // namespace + +struct good_api_v1_s { + table_header hdr; + int (*ping)(void); +}; + +static int ping(void) +{ + return 42; +} + +extern "C" { + extern const struct good_api_v1_s good_api_v1; + const struct good_api_v1_s good_api_v1 = { + { 0x314D5044u /* "DPM1" */, sizeof(struct good_api_v1_s) }, + ping, + }; +} + +extern "C" const char* dpm_module_version(void) +{ + return "1.2.3"; +} + +extern "C" const char* dpm_module_description(void) +{ + return "Known-good stub module."; +} + +extern "C" const char* dpm_module_core_min(void) +{ + return "0.1.0"; +} + +extern "C" const void* dpm_module_manifest(void) +{ + static const manifest_entry entries[] = { + { "good", 1, "good_api_v1" }, + }; + static const manifest m = { 1, entries }; + return &m; +} + +extern "C" int dpm_module_execute(void* ctx, const char* command, + int argc, char** argv) +{ + (void)ctx; + (void)command; + (void)argc; + (void)argv; + return 0; +} diff --git a/tests/fixtures/src/lying_manifest.cpp b/tests/fixtures/src/lying_manifest.cpp new file mode 100644 index 0000000..1d628b3 --- /dev/null +++ b/tests/fixtures/src/lying_manifest.cpp @@ -0,0 +1,72 @@ +/** + * @file lying_manifest.cpp + * @brief Broken fixture: manifest declares an API it doesn't export + * + * Contract-complete, but its manifest names a table symbol that does + * not exist in the .so. Core must refuse it at validation step 4. + * + * Part of the Dark Horse Linux Package Manager (DPM) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#include + +namespace { + +struct manifest_entry { + const char* api_name; + int table_version; + const char* symbol; +}; + +struct manifest { + uint32_t count; + const manifest_entry* entries; +}; + +} // namespace + +extern "C" const char* dpm_module_version(void) +{ + return "1.0.0"; +} + +extern "C" const char* dpm_module_description(void) +{ + return "Fixture whose manifest lies."; +} + +extern "C" const char* dpm_module_core_min(void) +{ + return "0.1.0"; +} + +extern "C" const void* dpm_module_manifest(void) +{ + static const manifest_entry entries[] = { + { "ghost", 1, "ghost_api_v1" }, + }; + static const manifest m = { 1, entries }; + return &m; +} + +extern "C" int dpm_module_execute(void* ctx, const char* command, + int argc, char** argv) +{ + (void)ctx; + (void)command; + (void)argc; + (void)argv; + return 0; +} diff --git a/tests/fixtures/src/missing_symbols.cpp b/tests/fixtures/src/missing_symbols.cpp new file mode 100644 index 0000000..beb5f96 --- /dev/null +++ b/tests/fixtures/src/missing_symbols.cpp @@ -0,0 +1,33 @@ +/** + * @file missing_symbols.cpp + * @brief Broken fixture: exports only part of the module contract + * + * Missing dpm_module_execute, dpm_module_core_min, and + * dpm_module_manifest. Core must refuse it at validation step 1 and + * name the missing symbols. + * + * Part of the Dark Horse Linux Package Manager (DPM) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +extern "C" const char* dpm_module_version(void) +{ + return "1.0.0"; +} + +extern "C" const char* dpm_module_description(void) +{ + return "Fixture missing most of the contract."; +} diff --git a/tests/test_core.cpp b/tests/test_core.cpp new file mode 100644 index 0000000..063032f --- /dev/null +++ b/tests/test_core.cpp @@ -0,0 +1,196 @@ +/** + * @file test_core.cpp + * @brief Core test binary: drives libdpm-core through its public C API + * + * Exercises context lifecycle, configuration, the full load-time + * validation matrix against the fixture modules, versioned require, + * typed API access, generic dispatch, and enumeration. Exits nonzero + * on any failure. + * + * @copyright Copyright (c) 2026 SILO GROUP LLC + * @author Chris Punches + * + * Part of the Dark Horse Linux Package Manager (DPM) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#include + +#include +#include +#include + +#ifndef TEST_FIXTURE_MODULES +#error "TEST_FIXTURE_MODULES must be defined" +#endif +#ifndef TEST_FIXTURE_CONF +#error "TEST_FIXTURE_CONF must be defined" +#endif + +static int g_failures = 0; +static int g_checks = 0; + +#define CHECK(cond) \ + do { \ + g_checks++; \ + if (!(cond)) { \ + g_failures++; \ + std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, \ + #cond); \ + } \ + } while (0) + +static bool error_contains(dpm_ctx* ctx, const char* needle) +{ + const char* err = dpm_last_error(ctx); + return err != nullptr && std::strstr(err, needle) != nullptr; +} + +/* Mirror of the good fixture's table layout (consumer-side spec decl). */ +struct good_api_v1_s { + dpm_api_table_header hdr; + int (*ping)(void); +}; + +int main(void) +{ + /* ---- dpm_open: invalid explicit override refuses ---- */ + { + dpm_open_overrides bad = {"/does/not/exist/conf", nullptr, nullptr, -1}; + CHECK(dpm_open(&bad) == nullptr); + + dpm_open_overrides bad_level = {nullptr, nullptr, nullptr, 99}; + CHECK(dpm_open(&bad_level) == nullptr); + } + + /* ---- context with fixture config and fixture module path ---- */ + dpm_open_overrides overrides = {TEST_FIXTURE_CONF, TEST_FIXTURE_MODULES, + nullptr, -1}; + dpm_ctx* ctx = dpm_open(&overrides); + CHECK(ctx != nullptr); + if (!ctx) { + std::fprintf(stderr, "cannot continue without a context\n"); + return 1; + } + + /* ---- services ---- */ + { + CHECK(std::strcmp(dpm_core_version(), DPM_CORE_VERSION_EXPECTED) == 0); + + /* config: values resolve per-module, per-section */ + const char* v = dpm_config_get(ctx, "testmod", "main", "key"); + CHECK(v != nullptr && std::strcmp(v, "value") == 0); + v = dpm_config_get(ctx, "testmod", "section2", "other"); + CHECK(v != nullptr && std::strcmp(v, "42") == 0); + CHECK(dpm_config_get(ctx, "testmod", "main", "absent") == nullptr); + CHECK(dpm_config_get(ctx, "nomodule", "main", "key") == nullptr); + + /* module-path override wins over the config value */ + const char* path = dpm_module_path(ctx); + CHECK(path != nullptr && + std::strncmp(path, TEST_FIXTURE_MODULES, + std::strlen(TEST_FIXTURE_MODULES)) == 0); + } + + /* ---- validation matrix: every broken fixture refused, precisely ---- */ + { + CHECK(dpm_require(ctx, "missing_symbols", nullptr) == nullptr); + CHECK(error_contains(ctx, "missing required contract symbols")); + CHECK(error_contains(ctx, "dpm_module_execute")); + + CHECK(dpm_require(ctx, "core_too_new", nullptr) == nullptr); + CHECK(error_contains(ctx, "update core")); + + CHECK(dpm_require(ctx, "bad_version", nullptr) == nullptr); + CHECK(error_contains(ctx, "malformed version")); + + CHECK(dpm_require(ctx, "lying_manifest", nullptr) == nullptr); + CHECK(error_contains(ctx, "does not resolve")); + + CHECK(dpm_require(ctx, "bad_magic", nullptr) == nullptr); + CHECK(error_contains(ctx, "magic")); + + CHECK(dpm_require(ctx, "nonexistent", nullptr) == nullptr); + CHECK(error_contains(ctx, "not found")); + } + + /* ---- known-good module: require, versions, api, execute ---- */ + { + dpm_module* good = dpm_require(ctx, "good", nullptr); + CHECK(good != nullptr); + + /* loaded at most once per context */ + CHECK(dpm_require(ctx, "good", nullptr) == good); + + /* minimum-version negotiation */ + CHECK(dpm_require(ctx, "good", "1.0.0") == good); + CHECK(dpm_require(ctx, "good", "1.2.3") == good); + CHECK(dpm_require(ctx, "good", "2.0.0") == nullptr); + CHECK(error_contains(ctx, "below required minimum")); + CHECK(dpm_require(ctx, "good", "not.a.version") == nullptr); + CHECK(error_contains(ctx, "malformed minimum version")); + + /* typed access */ + const void* table = dpm_get_api(ctx, good, "good", 1); + CHECK(table != nullptr); + if (table) { + const auto* api = static_cast(table); + CHECK(api->hdr.magic == DPM_API_TABLE_MAGIC); + CHECK(api->hdr.size == sizeof(good_api_v1_s)); + CHECK(api->ping() == 42); + } + + /* absent api/version pairs are known from the manifest */ + CHECK(dpm_get_api(ctx, good, "good", 2) == nullptr); + CHECK(dpm_get_api(ctx, good, "ghost", 1) == nullptr); + + /* generic dispatch */ + CHECK(dpm_execute(ctx, good, nullptr, 0, nullptr) == 0); + } + + /* ---- enumeration: only the valid module surfaces ---- */ + { + dpm_cursor* cur = dpm_list_modules(ctx); + CHECK(cur != nullptr); + if (cur) { + int count = 0; + dpm_module_info info; + while (dpm_cursor_next(cur, &info) == 0) { + count++; + CHECK(std::strcmp(info.name, "good") == 0); + CHECK(std::strcmp(info.version, "1.2.3") == 0); + CHECK(std::strcmp(info.core_min, "0.1.0") == 0); + CHECK(info.description != nullptr && *info.description); + } + CHECK(count == 1); + dpm_cursor_free(cur); + } + + /* unreadable module path refuses with a reason */ + dpm_open_overrides bad_path = {TEST_FIXTURE_CONF, "/does/not/exist", + nullptr, -1}; + dpm_ctx* ctx2 = dpm_open(&bad_path); + CHECK(ctx2 != nullptr); + if (ctx2) { + CHECK(dpm_list_modules(ctx2) == nullptr); + CHECK(error_contains(ctx2, "module path")); + dpm_close(ctx2); + } + } + + dpm_close(ctx); + + std::printf("%d checks, %d failures\n", g_checks, g_failures); + return g_failures == 0 ? 0 : 1; +}