diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..3a3aeb9 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,64 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store + +### Maven ### +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ +target diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml new file mode 100644 index 0000000..a1aa04b --- /dev/null +++ b/.github/workflows/maven.yml @@ -0,0 +1,35 @@ +# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven + +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. + +name: Maven + +on: + push: + branches: [ "develop" ] + pull_request: + branches: [ "develop" ] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up JDK 21 + uses: actions/setup-java@v3 + with: + java-version: '21' + distribution: 'temurin' + cache: maven + - name: Build with Maven + run: mvn -B package --file pom.xml + + # Optional: Uploads the full dependency graph to GitHub to improve the quality of Dependabot alerts this repository can receive + - name: Submit Dependency Snapshot + uses: advanced-security/maven-dependency-submission-action@v3 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3a3aeb9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,64 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store + +### Maven ### +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ +target diff --git a/.java-version b/.java-version new file mode 100644 index 0000000..aabe6ec --- /dev/null +++ b/.java-version @@ -0,0 +1 @@ +21 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..bcc296f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,73 @@ +FROM eclipse-temurin:21 AS app-builder + +ENV DEBIAN_FRONTEND=noninteractive + +RUN mkdir -p /opt/build +WORKDIR /opt/build + +RUN apt update && \ + apt install -y maven && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists/* + +FROM app-builder AS app-build + +COPY tftp/pom.xml tftp/ +COPY common/pom.xml common/ +COPY lib/pom.xml lib/ +COPY client/pom.xml client/ +COPY vclu/pom.xml vclu/ +COPY pom.xml . + +COPY vclu/assembly/jar-with-dependencies.xml vclu/assembly/ + +# https://issues.apache.org/jira/browse/MDEP-689 +#RUN mvn dependency:go-offline +RUN mvn install + +COPY tftp tftp +COPY common common +COPY lib lib +COPY client client +COPY vclu vclu + +RUN mvn package + +FROM eclipse-temurin:21 AS jre-build + +RUN mkdir -p /opt/build +WORKDIR /opt/build + +#COPY --from=app-build /opt/build/vclu/target/vclu.jar . + +RUN $JAVA_HOME/bin/jlink \ + --add-modules java.base,java.xml,java.naming,java.management,jdk.zipfs \ +# --add-modules $(jdeps --ignore-missing-deps --print-module-deps vclu.jar),java.base,java.xml,java.naming,java.management,java.sql,java.instrument,jdk.zipfs,jdk.unsupported \ + --strip-debug \ + --no-man-pages \ + --no-header-files \ + --compress=2 \ + --output /opt/build/jre + +FROM debian:buster-slim AS app-runtime + +ENV JAVA_HOME=/opt/java/openjdk +ENV PATH "${JAVA_HOME}/bin:${PATH}" + +RUN mkdir -p /opt/docker +WORKDIR /opt/docker + +COPY --from=jre-build /opt/build/jre $JAVA_HOME +COPY --from=app-build /opt/build/vclu/target/vclu.jar /opt/docker +COPY runtime . + +ENTRYPOINT [ \ + "java", \ + "-XX:+DisableAttachMechanism", \ + "-server", "-Xshare:off", "-XX:+UseContainerSupport", "-XX:+UseZGC", "-XX:+UseDynamicNumberOfGCThreads", \ + "-XX:+ExitOnOutOfMemoryError", \ + "-Djava.net.preferIPv6Addresses=false", \ +# "-Djava.net.preferIPv4Stack=true", \ + "-Djava.awt.headless=true", "-Dfile.encoding=UTF-8", \ + "-jar", "vclu.jar" \ +] diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..cd6cd11 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,603 @@ +TFTP (under tfp/ directory) is licensed under Apache 2.0. + +Documentation (under docs/ directory) is under CC BY-SA 4.0 license. + +All other code is licensed under GPLv3. + +Datasheets are owned by their respective owners. + +GNU General Public License +========================== + +_Version 3, 29 June 2007_ +_Copyright © 2007 Free Software Foundation, Inc. <>_ + +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +## Preamble + +The GNU General Public License is a free, copyleft license for software and other +kinds of works. + +The licenses for most software and other practical works are designed to take away +your freedom to share and change the works. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change all versions of a +program--to make sure it remains free software for all its users. We, the Free +Software Foundation, use the GNU General Public License for most of our software; it +applies also to any other work released this way by its authors. You can apply it to +your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General +Public Licenses are designed to make sure that you have the freedom to distribute +copies of free software (and charge for them if you wish), that you receive source +code or can get it if you want it, that you can change the software or use pieces of +it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or +asking you to surrender the rights. Therefore, you have certain responsibilities if +you distribute copies of the software, or if you modify it: responsibilities to +respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, +you must pass on to the recipients the same freedoms that you received. You must make +sure that they, too, receive or can get the source code. And you must show them these +terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: **(1)** assert +copyright on the software, and **(2)** offer you this License giving you legal permission +to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is +no warranty for this free software. For both users' and authors' sake, the GPL +requires that modified versions be marked as changed, so that their problems will not +be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of +the software inside them, although the manufacturer can do so. This is fundamentally +incompatible with the aim of protecting users' freedom to change the software. The +systematic pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we have designed +this version of the GPL to prohibit the practice for those products. If such problems +arise substantially in other domains, we stand ready to extend this provision to +those domains in future versions of the GPL, as needed to protect the freedom of +users. + +Finally, every program is threatened constantly by software patents. States should +not allow patents to restrict development and use of software on general-purpose +computers, but in those that do, we wish to avoid the special danger that patents +applied to a free program could make it effectively proprietary. To prevent this, the +GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +## TERMS AND CONDITIONS + +### 0. Definitions + +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this +License. Each licensee is addressed as “you”. “Licensees” and +“recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in +a fashion requiring copyright permission, other than the making of an exact copy. The +resulting work is called a “modified version” of the earlier work or a +work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on +the Program. + +To “propagate” a work means to do anything with it that, without +permission, would make you directly or secondarily liable for infringement under +applicable copyright law, except executing it on a computer or modifying a private +copy. Propagation includes copying, distribution (with or without modification), +making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through a computer +network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the +extent that it includes a convenient and prominently visible feature that **(1)** +displays an appropriate copyright notice, and **(2)** tells the user that there is no +warranty for the work (except to the extent that warranties are provided), that +licensees may convey the work under this License, and how to view a copy of this +License. If the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +### 1. Source Code + +The “source code” for a work means the preferred form of the work for +making modifications to it. “Object code” means any non-source form of a +work. + +A “Standard Interface” means an interface that either is an official +standard defined by a recognized standards body, or, in the case of interfaces +specified for a particular programming language, one that is widely used among +developers working in that language. + +The “System Libraries” of an executable work include anything, other than +the work as a whole, that **(a)** is included in the normal form of packaging a Major +Component, but which is not part of that Major Component, and **(b)** serves only to +enable use of the work with that Major Component, or to implement a Standard +Interface for which an implementation is available to the public in source code form. +A “Major Component”, in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system (if any) on which +the executable work runs, or a compiler used to produce the work, or an object code +interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the +source code needed to generate, install, and (for an executable work) run the object +code and to modify the work, including scripts to control those activities. However, +it does not include the work's System Libraries, or general-purpose tools or +generally available free programs which are used unmodified in performing those +activities but which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for the work, and +the source code for shared libraries and dynamically linked subprograms that the work +is specifically designed to require, such as by intimate data communication or +control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate +automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +### 2. Basic Permissions + +All rights granted under this License are granted for the term of copyright on the +Program, and are irrevocable provided the stated conditions are met. This License +explicitly affirms your unlimited permission to run the unmodified Program. The +output from running a covered work is covered by this License only if the output, +given its content, constitutes a covered work. This License acknowledges your rights +of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without +conditions so long as your license otherwise remains in force. You may convey covered +works to others for the sole purpose of having them make modifications exclusively +for you, or provide you with facilities for running those works, provided that you +comply with the terms of this License in conveying all material for which you do not +control copyright. Those thus making or running the covered works for you must do so +exclusively on your behalf, under your direction and control, on terms that prohibit +them from making any copies of your copyrighted material outside their relationship +with you. + +Conveying under any other circumstances is permitted solely under the conditions +stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +### 3. Protecting Users' Legal Rights From Anti-Circumvention Law + +No covered work shall be deemed part of an effective technological measure under any +applicable law fulfilling obligations under article 11 of the WIPO copyright treaty +adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention +of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of +technological measures to the extent such circumvention is effected by exercising +rights under this License with respect to the covered work, and you disclaim any +intention to limit operation or modification of the work as a means of enforcing, +against the work's users, your or third parties' legal rights to forbid circumvention +of technological measures. + +### 4. Conveying Verbatim Copies + +You may convey verbatim copies of the Program's source code as you receive it, in any +medium, provided that you conspicuously and appropriately publish on each copy an +appropriate copyright notice; keep intact all notices stating that this License and +any non-permissive terms added in accord with section 7 apply to the code; keep +intact all notices of the absence of any warranty; and give all recipients a copy of +this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer +support or warranty protection for a fee. + +### 5. Conveying Modified Source Versions + +You may convey a work based on the Program, or the modifications to produce it from +the Program, in the form of source code under the terms of section 4, provided that +you also meet all of these conditions: + +* **a)** The work must carry prominent notices stating that you modified it, and giving a + relevant date. +* **b)** The work must carry prominent notices stating that it is released under this + License and any conditions added under section 7. This requirement modifies the + requirement in section 4 to “keep intact all notices”. +* **c)** You must license the entire work, as a whole, under this License to anyone who + comes into possession of a copy. This License will therefore apply, along with any + applicable section 7 additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no permission to license the + work in any other way, but it does not invalidate such permission if you have + separately received it. +* **d)** If the work has interactive user interfaces, each must display Appropriate Legal + Notices; however, if the Program has interactive interfaces that do not display + Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are +not by their nature extensions of the covered work, and which are not combined with +it such as to form a larger program, in or on a volume of a storage or distribution +medium, is called an “aggregate” if the compilation and its resulting +copyright are not used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work in an aggregate +does not cause this License to apply to the other parts of the aggregate. + +### 6. Conveying Non-Source Forms + +You may convey a covered work in object code form under the terms of sections 4 and +5, provided that you also convey the machine-readable Corresponding Source under the +terms of this License, in one of these ways: + +* **a)** Convey the object code in, or embodied in, a physical product (including a + physical distribution medium), accompanied by the Corresponding Source fixed on a + durable physical medium customarily used for software interchange. +* **b)** Convey the object code in, or embodied in, a physical product (including a + physical distribution medium), accompanied by a written offer, valid for at least + three years and valid for as long as you offer spare parts or customer support for + that product model, to give anyone who possesses the object code either **(1)** a copy of + the Corresponding Source for all the software in the product that is covered by this + License, on a durable physical medium customarily used for software interchange, for + a price no more than your reasonable cost of physically performing this conveying of + source, or **(2)** access to copy the Corresponding Source from a network server at no + charge. +* **c)** Convey individual copies of the object code with a copy of the written offer to + provide the Corresponding Source. This alternative is allowed only occasionally and + noncommercially, and only if you received the object code with such an offer, in + accord with subsection 6b. +* **d)** Convey the object code by offering access from a designated place (gratis or for + a charge), and offer equivalent access to the Corresponding Source in the same way + through the same place at no further charge. You need not require recipients to copy + the Corresponding Source along with the object code. If the place to copy the object + code is a network server, the Corresponding Source may be on a different server + (operated by you or a third party) that supports equivalent copying facilities, + provided you maintain clear directions next to the object code saying where to find + the Corresponding Source. Regardless of what server hosts the Corresponding Source, + you remain obligated to ensure that it is available for as long as needed to satisfy + these requirements. +* **e)** Convey the object code using peer-to-peer transmission, provided you inform + other peers where the object code and Corresponding Source of the work are being + offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the +Corresponding Source as a System Library, need not be included in conveying the +object code work. + +A “User Product” is either **(1)** a “consumer product”, which +means any tangible personal property which is normally used for personal, family, or +household purposes, or **(2)** anything designed or sold for incorporation into a +dwelling. In determining whether a product is a consumer product, doubtful cases +shall be resolved in favor of coverage. For a particular product received by a +particular user, “normally used” refers to a typical or common use of +that class of product, regardless of the status of the particular user or of the way +in which the particular user actually uses, or expects or is expected to use, the +product. A product is a consumer product regardless of whether the product has +substantial commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, +procedures, authorization keys, or other information required to install and execute +modified versions of a covered work in that User Product from a modified version of +its Corresponding Source. The information must suffice to ensure that the continued +functioning of the modified object code is in no case prevented or interfered with +solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for +use in, a User Product, and the conveying occurs as part of a transaction in which +the right of possession and use of the User Product is transferred to the recipient +in perpetuity or for a fixed term (regardless of how the transaction is +characterized), the Corresponding Source conveyed under this section must be +accompanied by the Installation Information. But this requirement does not apply if +neither you nor any third party retains the ability to install modified object code +on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to +continue to provide support service, warranty, or updates for a work that has been +modified or installed by the recipient, or for the User Product in which it has been +modified or installed. Access to a network may be denied when the modification itself +materially and adversely affects the operation of the network or violates the rules +and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with +this section must be in a format that is publicly documented (and with an +implementation available to the public in source code form), and must require no +special password or key for unpacking, reading or copying. + +### 7. Additional Terms + +“Additional permissions” are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. Additional +permissions that are applicable to the entire Program shall be treated as though they +were included in this License, to the extent that they are valid under applicable +law. If additional permissions apply only to part of the Program, that part may be +used separately under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any +additional permissions from that copy, or from any part of it. (Additional +permissions may be written to require their own removal in certain cases when you +modify the work.) You may place additional permissions on material, added by you to a +covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a +covered work, you may (if authorized by the copyright holders of that material) +supplement the terms of this License with terms: + +* **a)** Disclaiming warranty or limiting liability differently from the terms of + sections 15 and 16 of this License; or +* **b)** Requiring preservation of specified reasonable legal notices or author + attributions in that material or in the Appropriate Legal Notices displayed by works + containing it; or +* **c)** Prohibiting misrepresentation of the origin of that material, or requiring that + modified versions of such material be marked in reasonable ways as different from the + original version; or +* **d)** Limiting the use for publicity purposes of names of licensors or authors of the + material; or +* **e)** Declining to grant rights under trademark law for use of some trade names, + trademarks, or service marks; or +* **f)** Requiring indemnification of licensors and authors of that material by anyone + who conveys the material (or modified versions of it) with contractual assumptions of + liability to the recipient, for any liability that these contractual assumptions + directly impose on those licensors and authors. + +All other non-permissive additional terms are considered “further +restrictions” within the meaning of section 10. If the Program as you received +it, or any part of it, contains a notice stating that it is governed by this License +along with a term that is a further restriction, you may remove that term. If a +license document contains a further restriction but permits relicensing or conveying +under this License, you may add to a covered work material governed by the terms of +that license document, provided that the further restriction does not survive such +relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in +the relevant source files, a statement of the additional terms that apply to those +files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a +separately written license, or stated as exceptions; the above requirements apply +either way. + +### 8. Termination + +You may not propagate or modify a covered work except as expressly provided under +this License. Any attempt otherwise to propagate or modify it is void, and will +automatically terminate your rights under this License (including any patent licenses +granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a +particular copyright holder is reinstated **(a)** provisionally, unless and until the +copyright holder explicitly and finally terminates your license, and **(b)** permanently, +if the copyright holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently +if the copyright holder notifies you of the violation by some reasonable means, this +is the first time you have received notice of violation of this License (for any +work) from that copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of +parties who have received copies or rights from you under this License. If your +rights have been terminated and not permanently reinstated, you do not qualify to +receive new licenses for the same material under section 10. + +### 9. Acceptance Not Required for Having Copies + +You are not required to accept this License in order to receive or run a copy of the +Program. Ancillary propagation of a covered work occurring solely as a consequence of +using peer-to-peer transmission to receive a copy likewise does not require +acceptance. However, nothing other than this License grants you permission to +propagate or modify any covered work. These actions infringe copyright if you do not +accept this License. Therefore, by modifying or propagating a covered work, you +indicate your acceptance of this License to do so. + +### 10. Automatic Licensing of Downstream Recipients + +Each time you convey a covered work, the recipient automatically receives a license +from the original licensors, to run, modify and propagate that work, subject to this +License. You are not responsible for enforcing compliance by third parties with this +License. + +An “entity transaction” is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an organization, or +merging organizations. If propagation of a covered work results from an entity +transaction, each party to that transaction who receives a copy of the work also +receives whatever licenses to the work the party's predecessor in interest had or +could give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if the predecessor +has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or +affirmed under this License. For example, you may not impose a license fee, royalty, +or other charge for exercise of rights granted under this License, and you may not +initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging +that any patent claim is infringed by making, using, selling, offering for sale, or +importing the Program or any portion of it. + +### 11. Patents + +A “contributor” is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The work thus +licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned or +controlled by the contributor, whether already acquired or hereafter acquired, that +would be infringed by some manner, permitted by this License, of making, using, or +selling its contributor version, but do not include claims that would be infringed +only as a consequence of further modification of the contributor version. For +purposes of this definition, “control” includes the right to grant patent +sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license +under the contributor's essential patent claims, to make, use, sell, offer for sale, +import and otherwise run, modify and propagate the contents of its contributor +version. + +In the following three paragraphs, a “patent license” is any express +agreement or commitment, however denominated, not to enforce a patent (such as an +express permission to practice a patent or covenant not to sue for patent +infringement). To “grant” such a patent license to a party means to make +such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the +Corresponding Source of the work is not available for anyone to copy, free of charge +and under the terms of this License, through a publicly available network server or +other readily accessible means, then you must either **(1)** cause the Corresponding +Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the +patent license for this particular work, or **(3)** arrange, in a manner consistent with +the requirements of this License, to extend the patent license to downstream +recipients. “Knowingly relying” means you have actual knowledge that, but +for the patent license, your conveying the covered work in a country, or your +recipient's use of the covered work in a country, would infringe one or more +identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you +convey, or propagate by procuring conveyance of, a covered work, and grant a patent +license to some of the parties receiving the covered work authorizing them to use, +propagate, modify or convey a specific copy of the covered work, then the patent +license you grant is automatically extended to all recipients of the covered work and +works based on it. + +A patent license is “discriminatory” if it does not include within the +scope of its coverage, prohibits the exercise of, or is conditioned on the +non-exercise of one or more of the rights that are specifically granted under this +License. You may not convey a covered work if you are a party to an arrangement with +a third party that is in the business of distributing software, under which you make +payment to the third party based on the extent of your activity of conveying the +work, and under which the third party grants, to any of the parties who would receive +the covered work from you, a discriminatory patent license **(a)** in connection with +copies of the covered work conveyed by you (or copies made from those copies), or **(b)** +primarily for and in connection with specific products or compilations that contain +the covered work, unless you entered into that arrangement, or that patent license +was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied +license or other defenses to infringement that may otherwise be available to you +under applicable patent law. + +### 12. No Surrender of Others' Freedom + +If conditions are imposed on you (whether by court order, agreement or otherwise) +that contradict the conditions of this License, they do not excuse you from the +conditions of this License. If you cannot convey a covered work so as to satisfy +simultaneously your obligations under this License and any other pertinent +obligations, then as a consequence you may not convey it at all. For example, if you +agree to terms that obligate you to collect a royalty for further conveying from +those to whom you convey the Program, the only way you could satisfy both those terms +and this License would be to refrain entirely from conveying the Program. + +### 13. Use with the GNU Affero General Public License + +Notwithstanding any other provision of this License, you have permission to link or +combine any covered work with a work licensed under version 3 of the GNU Affero +General Public License into a single combined work, and to convey the resulting work. +The terms of this License will continue to apply to the part which is the covered +work, but the special requirements of the GNU Affero General Public License, section +13, concerning interaction through a network will apply to the combination as such. + +### 14. Revised Versions of this License + +The Free Software Foundation may publish revised and/or new versions of the GNU +General Public License from time to time. Such new versions will be similar in spirit +to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that +a certain numbered version of the GNU General Public License “or any later +version” applies to it, you have the option of following the terms and +conditions either of that numbered version or of any later version published by the +Free Software Foundation. If the Program does not specify a version number of the GNU +General Public License, you may choose any version ever published by the Free +Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU +General Public License can be used, that proxy's public statement of acceptance of a +version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no +additional obligations are imposed on any author or copyright holder as a result of +your choosing to follow a later version. + +### 15. Disclaimer of Warranty + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER +EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE +QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +### 16. Limitation of Liability + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY +COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS +PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, +INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE +OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE +WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + +### 17. Interpretation of Sections 15 and 16 + +If the disclaimer of warranty and limitation of liability provided above cannot be +given local legal effect according to their terms, reviewing courts shall apply local +law that most closely approximates an absolute waiver of all civil liability in +connection with the Program, unless a warranty or assumption of liability accompanies +a copy of the Program in return for a fee. + +_END OF TERMS AND CONDITIONS_ + +## How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to +the public, the best way to achieve this is to make it free software which everyone +can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them +to the start of each source file to most effectively state the exclusion of warranty; +and each file should have at least the “copyright” line and a pointer to +where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short notice like this +when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type 'show c' for details. + +The hypothetical commands `show w` and `show c` should show the appropriate parts of +the General Public License. Of course, your program's commands might be different; +for a GUI interface, you would use an “about box”. + +You should also get your employer (if you work as a programmer) or school, if any, to +sign a “copyright disclaimer” for the program, if necessary. For more +information on this, and how to apply and follow the GNU GPL, see +<>. + +The GNU General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may consider it +more useful to permit linking proprietary applications with the library. If this is +what you want to do, use the GNU Lesser General Public License instead of this +License. But first, please read +<>. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..9e390c2 --- /dev/null +++ b/README.md @@ -0,0 +1,57 @@ +[![Maven](https://github.com/psobiech/opengr8on/actions/workflows/maven.yml/badge.svg)](https://github.com/psobiech/opengr8on/actions/workflows/maven.yml) + +# Disclaimer + +This project is not endorsed by, directly affiliated with, maintained, authorized, or sponsored by Grenton Sp. z o.o. + +The use of any trade name or trademark is for identification and reference purposes only and does not imply any association with the trademark holder of their product brand. + +Any product names, logos, brands, and other trademarks or images featured or referred to within this page are the property of their respective trademark holders. + +Unless expressly stated otherwise, the person who associated a work with this deed makes no warranties about the work, and disclaims liability for all uses of the work, to the fullest extent permitted by applicable law. + +# Requirements +Java 21 + +# TFTP +It seems that the CLU FTP server is not RFC compliant, this is why we forked the commons-net TFTP library to revert the fix from commons-net (https://issues.apache.org/jira/browse/NET-414), that is breaking compatibility with CLUs. + +# Virtual CLU + +## Local +> mvn package +> +> java -jar vclu/target/vclu.jar eth0 + +## Docker + +> docker build . --target app-runtime -t vclu:latest +> +> docker run --net host --mount type=bind,source=./runtime,target=/opt/docker/runtime vclu:latest eth0 + +## Quickstart + +* Assuming OM is extracted in $OM_DIR. + +1. Copy [clu_VIRTUAL_ft00000001_fv001_htaa55aa55_hv00000001.xml](runtime%2Fdevice-interfaces%2Fclu_VIRTUAL_ft00000001_fv001_htaa55aa55_hv00000001.xml) to `$OM_DIR/configuration/com.grenton.om/device-interfaces/clu_VIRTUAL_ft00000001_fv001_htaa55aa55_hv00000001.xml` +1. Restart/Launch OM +1. Run Virtual CLU (eg. `docker run --net host --mount type=bind,source=./runtime,target=/opt/docker/runtime ghcr.io/psobiech/opengr8on:latest eth0` - assuming eth0 is your network interface name) +1. Start OM Discovery +1. When prompted for KEY type: `00000000` +1. Virtual CLU should be available like normal CLU: +![vclu.png](docs%2Fimg%2Fvclu.png) + +What works: +- Most of OM integration and LUA scripting (Control, Events, Embedded features, User features, LUA Scripting) +- Communication between CLU and CLU (accessing variables from other CLUs) + +Does not work: +- No virtual objects are implemented yet +- VCLU does not preserve keys on restarts (requires discovery every time, unless you use the hardcoded defaults) +- If discovery is interrupted, VCLU requires restart (some key management issue?) +- Only tested under Linux +- No error handling - LUA errors sometimes are silently dropped + +TODOs: +- most of the code requires refactoring +- support binding via IP instead of network interface name \ No newline at end of file diff --git a/client/pom.xml b/client/pom.xml new file mode 100644 index 0000000..4722884 --- /dev/null +++ b/client/pom.xml @@ -0,0 +1,157 @@ + + + + + 4.0.0 + + + pl.psobiech.opengr8on + parent + 1.0-SNAPSHOT + + + client + + + + + software.amazon.awssdk + bom + ${aws.sdk.version} + pom + import + + + + + + + pl.psobiech.opengr8on + lib + + + pl.psobiech.opengr8on + vclu + test + + + + ch.qos.logback + logback-classic + + + + commons-net + commons-net + + + + commons-cli + commons-cli + + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + com.fasterxml.jackson.module + jackson-module-parameter-names + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + + org.bouncycastle + bcprov-jdk18on + + + + io.jstach + jstachio + + + + software.amazon.awssdk.iotdevicesdk + aws-iot-device-sdk + 1.18.0 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${maven.compiler.source} + ${maven.compiler.target} + ${project.build.sourceEncoding} + + -parameters + + + + + io.jstach + jstachio-apt + ${jstachio.version} + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + + org.apache.maven.plugins + maven-assembly-plugin + + client + false + + jar-with-dependencies + + + + true + pl.psobiech.opengr8on.Main + + + + + + assemble-all + package + + single + + + + + + + diff --git a/client/src/main/java/pl/psobiech/opengr8on/Main.java b/client/src/main/java/pl/psobiech/opengr8on/Main.java new file mode 100644 index 0000000..fdd34a6 --- /dev/null +++ b/client/src/main/java/pl/psobiech/opengr8on/Main.java @@ -0,0 +1,405 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on; + +import java.io.IOException; +import java.net.Inet4Address; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import pl.psobiech.opengr8on.client.CLUClient; +import pl.psobiech.opengr8on.client.CLUFiles; +import pl.psobiech.opengr8on.client.CipherKey; +import pl.psobiech.opengr8on.client.Client; +import pl.psobiech.opengr8on.client.device.CLUDevice; +import pl.psobiech.opengr8on.client.device.CLUDeviceConfig; +import pl.psobiech.opengr8on.client.device.CipherTypeEnum; +import pl.psobiech.opengr8on.exceptions.UnexpectedException; +import pl.psobiech.opengr8on.util.FileUtil; +import pl.psobiech.opengr8on.util.IPv4AddressUtil; +import pl.psobiech.opengr8on.util.IPv4AddressUtil.NetworkInterfaceDto; +import pl.psobiech.opengr8on.util.ObjectMapperFactory; +import pl.psobiech.opengr8on.util.RandomUtil; +import pl.psobiech.opengr8on.util.Util; +import pl.psobiech.opengr8on.xml.interfaces.CLU; +import pl.psobiech.opengr8on.xml.interfaces.InterfaceRegistry; +import pl.psobiech.opengr8on.xml.omp.OmpReader; + +public class Main { + public static final Duration DEFAULT_LONG_TIMEOUT = Duration.ofMillis(30_000); + + private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); + + private static final Map PRIVATE_KEYS = Map.of( + 0x0L, "00000000".getBytes() + ); + + private static final Inet4Address MIN_IP = IPv4AddressUtil.parseIPv4("10.72.144.1"); + + public static void main(String[] args) throws Exception { + final Option helpOption = Option.builder("h").longOpt("help") + .desc("display current help") + .build(); + + final Option localIPAddressPathOption = Option.builder("nip").longOpt("network-address") + .desc("local IPv4 address to use") + .hasArg() + .build(); + + final Option networkInterfaceOption = Option.builder("ni").longOpt("network-interface") + .desc("local network interface name") + .hasArg() + .build(); + + // + + final Option projectPathOption = Option.builder("p").longOpt("project") + .desc("OMP project file path") + .hasArg() + .build(); + + // + + final Option discoverOption = Option.builder("d").longOpt("discover") + .desc("discover clus") + .build(); + + final Option deviceInterfacesPathOption = Option.builder("di").longOpt("device-interfaces") + .desc("device interfaces directory path") + .hasArg() + .build(); + + final Option cluLimitPathOption = Option.builder("cl").longOpt("clu-limit") + .desc("maximum number of clus to discover") + .hasArg() + .build(); + + // + + final Option fetchOption = Option.builder("f").longOpt("fetch") + .desc("fetch device info") + .build(); + + final Option executeOption = Option.builder("e").longOpt("execute") + .desc("execute command") + .hasArg() + .build(); + + final Option ipAddressPathOption = Option.builder("ip").longOpt("address") + .desc("local IPv4 address to use") + .hasArg() + .build(); + + // + + final Options options = new Options() + .addOption(helpOption) + .addOption(localIPAddressPathOption).addOption(networkInterfaceOption).addOption(projectPathOption) + .addOption(discoverOption).addOption(deviceInterfacesPathOption).addOption(cluLimitPathOption) + .addOption(ipAddressPathOption).addOption(fetchOption).addOption(executeOption); + + final CommandLine commandLine = new DefaultParser().parse(options, args); + if (commandLine.hasOption(helpOption)) { + new HelpFormatter() + .printHelp("java -jar opengr8on.jar", options); + + System.exit(0); + } + + // + + final NetworkInterfaceDto networkInterface = getNetworkInterface(commandLine, networkInterfaceOption, localIPAddressPathOption); + LOGGER.debug("Using network interface: {}", networkInterface); + + final InterfaceRegistry interfaceRegistry = Optional.ofNullable(commandLine.getOptionValue(deviceInterfacesPathOption)) + .map(Paths::get) + .map(InterfaceRegistry::new) + .orElseGet(() -> new InterfaceRegistry(Paths.get("./device-interfaces"))); + + if (commandLine.hasOption(discoverOption)) { + final CipherKey projectCipherKey = Optional.ofNullable(commandLine.getOptionValue(projectPathOption)) + .map(Paths::get) + .map(OmpReader::readProjectCipherKey) + .orElseGet(() -> { + final CipherKey cipherKey = new CipherKey(RandomUtil.bytes(16), RandomUtil.bytes(16)); + LOGGER.debug("Generated random project key: {}", cipherKey); + + return cipherKey; + }); + + final Integer cluLimit = Optional.ofNullable(commandLine.getOptionValue(cluLimitPathOption)) + .map(Integer::parseInt) + .orElse(Integer.MAX_VALUE); + + discover(networkInterface, projectCipherKey, cluLimit, interfaceRegistry); + + return; + } + + final Inet4Address ipAddress = Optional.ofNullable(commandLine.getOptionValue(ipAddressPathOption)) + .map(IPv4AddressUtil::parseIPv4) + .orElseThrow(() -> new UnexpectedException("Missing device IP address")); + + if (commandLine.hasOption(fetchOption)) { + final CipherKey projectCipherKey = Optional.ofNullable(commandLine.getOptionValue(projectPathOption)) + .map(Paths::get) + .map(OmpReader::readProjectCipherKey) + .orElseThrow(() -> new UnexpectedException("Provide a project location")); + + final CLUDevice device; + try (CLUClient client = new CLUClient(networkInterface, ipAddress, projectCipherKey)) { + client.startTFTPdServer() + .get(); + + final Path temporaryFile = FileUtil.temporaryFile(); + try { + final Optional path = client.downloadFile(CLUFiles.CONFIG_JSON.getLocation(), temporaryFile); + if (path.isEmpty()) { + throw new UnexpectedException("Unrecognized CLU"); + } + + final Path configJsonFile = path.get(); + final CLUDeviceConfig configJson = ObjectMapperFactory.JSON.readerFor(CLUDeviceConfig.class) + .readValue(configJsonFile.toFile()); + + device = new CLUDevice( + configJson.getSerialNumber(), + configJson.getMacAddress(), + ipAddress, + CipherTypeEnum.PROJECT + ); + + LOGGER.debug(device.toString()); + LOGGER.debug(configJson.toString()); + + final CLU cluDefinition = interfaceRegistry.getCLU( + configJson.getHardwareType(), configJson.getHardwareVersion(), + configJson.getFirmwareType(), configJson.getFirmwareVersion() + ) + .get(); + + LOGGER.debug(cluDefinition.getTypeName()); + } finally { + FileUtil.deleteQuietly(temporaryFile); + } + + client.stopTFTPdServer() + .get(); + } + + try (CLUClient client = new CLUClient(networkInterface, device, projectCipherKey)) { + // NOP + } + } else if (commandLine.hasOption(executeOption)) { + final String command = commandLine.getOptionValue(executeOption); + + final CipherKey projectCipherKey = Optional.ofNullable(commandLine.getOptionValue(projectPathOption)) + .map(Paths::get) + .map(OmpReader::readProjectCipherKey) + .orElseThrow(() -> new UnexpectedException("Provide a project location")); + + try (CLUClient client = new CLUClient(networkInterface, ipAddress, projectCipherKey)) { + LOGGER.info(client.execute(command).get()); + + final Boolean success = client.startTFTPdServer().get(); + if (success) { + final CLUDevice device = client.getCluDevice(); + + final Path rootPath = Paths.get(".").resolve("live").resolve(String.valueOf(device.getSerialNumber())); + Files.createDirectories(rootPath); + + for (CLUFiles cluLikeFile : CLUFiles.values()) { + if (!cluLikeFile.isReadable() || !cluLikeFile.isWritable()) { + continue; + } + + final Path target = rootPath.resolve(cluLikeFile.getDevice() + "_" + StringUtils.lowerCase(cluLikeFile.getFileName())); + + try { + System.out.println(target); + client.downloadFile(cluLikeFile.getLocation(), target); + } catch (Exception e) { + FileUtil.deleteQuietly(target); + } + } + } + } + } + } + + private static NetworkInterfaceDto getNetworkInterface(CommandLine commandLine, Option networkInterfaceOption, Option localIPAddressPathOption) { + final Optional ipAddressOptional = Optional.ofNullable(commandLine.getOptionValue(localIPAddressPathOption)); + if (ipAddressOptional.isPresent()) { + final String ipAddress = ipAddressOptional.get(); + + final Optional networkInterfaceByAddressOptional = IPv4AddressUtil.getLocalIPv4NetworkInterfaceByIpAddress(ipAddress); + if (networkInterfaceByAddressOptional.isEmpty()) { + throw new UnexpectedException("Could not find network interface with address: " + ipAddress); + } + + final Optional networkInterfaceNameOptional = Optional.ofNullable(commandLine.getOptionValue(networkInterfaceOption)); + if (networkInterfaceNameOptional.isPresent()) { + final String networkInterfaceName = networkInterfaceNameOptional.get(); + final String ipAddressNetworkInterfaceName = networkInterfaceByAddressOptional.get().getNetworkInterface().getName(); + if (!networkInterfaceName.equals(ipAddressNetworkInterfaceName)) { + throw new UnexpectedException( + "Network interface %s does not have address %s configured" + .formatted( + networkInterfaceName, + ipAddressNetworkInterfaceName + ) + ); + } + } + + return networkInterfaceByAddressOptional.get(); + } + + final Optional networkInterfaceNameOptional = Optional.ofNullable(commandLine.getOptionValue(networkInterfaceOption)); + if (networkInterfaceNameOptional.isPresent()) { + final String networkInterfaceName = networkInterfaceNameOptional.get(); + + final Optional networkInterfaceByName = IPv4AddressUtil.getLocalIPv4NetworkInterfaceByName(networkInterfaceName); + if (networkInterfaceByName.isEmpty()) { + throw new UnexpectedException("Could not find local network interface with name: " + networkInterfaceName); + } + + return networkInterfaceByName.get(); + } + + throw new UnexpectedException("Provide either address or network interface name"); + } + + private static void discover( + NetworkInterfaceDto networkInterface, + CipherKey projectCipherKey, + Integer cluLimit, + InterfaceRegistry interfaceRegistry + ) { + final List usedAddresses = new ArrayList<>(); + usedAddresses.add(networkInterface.getAddress()); + usedAddresses.add(MIN_IP); + + try (Client broadcastClient = new Client(networkInterface)) { + broadcastClient.discover( + projectCipherKey, PRIVATE_KEYS, + DEFAULT_LONG_TIMEOUT, cluLimit + ) + .map(cluDevice -> { + LOGGER.debug("Discovered device: {}", cluDevice); + + return new CLUClient(networkInterface, cluDevice); + }) + .forEach(client -> { + try (client) { + final CLUDevice device = client.getCluDevice(); + final Inet4Address deviceAddress = device.getAddress(); + + final Inet4Address nextAddress; + synchronized (usedAddresses) { + // temporary hack, we expect the lowest ip to be last + final Inet4Address lastAddress = usedAddresses.getLast(); + + nextAddress = networkInterface.nextAvailable( + lastAddress, Duration.ofMillis(4_000), + deviceAddress, usedAddresses + ) + .get(); + + usedAddresses.add(nextAddress); + } + + client.setCipherKey(projectCipherKey) + .get(); + + if (!deviceAddress.equals(nextAddress)) { + client.setAddress(nextAddress, networkInterface.getAddress()) + .map(address -> { + Util.repeatUntilTrueOrTimeout( + DEFAULT_LONG_TIMEOUT, + duration -> + Optional.of( + IPv4AddressUtil.ping(address) + ) + ); + + return address; + }) + .orElseThrow(() -> new UnexpectedException("CLU did not accept new IP address")); + } + + client.reset(DEFAULT_LONG_TIMEOUT) + .get(); + + Util.repeatUntilTrueOrTimeout( + DEFAULT_LONG_TIMEOUT, + duration -> + client.checkAlive() + ) + .orElseThrow(() -> new UnexpectedException("CLU did not came up alive")); + + client.startTFTPdServer() + .get(); + + final Path temporaryFile = FileUtil.temporaryFile(); + try { + final Optional path = client.downloadFile(CLUFiles.CONFIG_JSON.getLocation(), temporaryFile); + if (path.isPresent()) { + final Path configJsonFile = path.get(); + final CLUDeviceConfig configJson = ObjectMapperFactory.JSON.readerFor(CLUDeviceConfig.class) + .readValue(configJsonFile.toFile()); + + LOGGER.debug(device.toString()); + LOGGER.debug(configJson.toString()); + + final CLU cluDefinition = interfaceRegistry.getCLU( + configJson.getHardwareType(), configJson.getHardwareVersion(), + configJson.getFirmwareType(), configJson.getFirmwareVersion() + ) + .get(); + + LOGGER.debug(cluDefinition.getTypeName()); + } + } catch (IOException e) { + throw new UnexpectedException(e); + } finally { + FileUtil.deleteQuietly(temporaryFile); + } + + client.stopTFTPdServer() + .get(); + } + }); + } + } +} diff --git a/client/src/main/resources/logback.xml b/client/src/main/resources/logback.xml new file mode 100644 index 0000000..ee23a6d --- /dev/null +++ b/client/src/main/resources/logback.xml @@ -0,0 +1,32 @@ + + + + + %date{"yyyy-MM-dd'T'HH:mm:ss,SSSXXX", UTC} [%level] %logger{15} - %message%n%xException{10} + + + + + + + + + + + diff --git a/client/src/test/resources/logback-test.xml b/client/src/test/resources/logback-test.xml new file mode 100644 index 0000000..3af7c46 --- /dev/null +++ b/client/src/test/resources/logback-test.xml @@ -0,0 +1,28 @@ + + + + + %date{"yyyy-MM-dd'T'HH:mm:ss,SSSXXX", UTC} [%level] %logger{15} - %message%n%xException{10} + + + + + + + diff --git a/common/pom.xml b/common/pom.xml new file mode 100644 index 0000000..18dd00c --- /dev/null +++ b/common/pom.xml @@ -0,0 +1,52 @@ + + + + + 4.0.0 + + pl.psobiech.opengr8on + parent + 1.0-SNAPSHOT + + + common + + + + ch.qos.logback + logback-classic + test + + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + com.fasterxml.jackson.module + jackson-module-parameter-names + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + \ No newline at end of file diff --git a/common/src/main/java/pl/psobiech/opengr8on/exceptions/UnexpectedException.java b/common/src/main/java/pl/psobiech/opengr8on/exceptions/UnexpectedException.java new file mode 100644 index 0000000..ed712b6 --- /dev/null +++ b/common/src/main/java/pl/psobiech/opengr8on/exceptions/UnexpectedException.java @@ -0,0 +1,33 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.exceptions; + +public class UnexpectedException extends RuntimeException { + public UnexpectedException(String message) { + super(message); + } + + public UnexpectedException(Throwable cause) { + this(cause.getMessage(), cause); + } + + public UnexpectedException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/common/src/main/java/pl/psobiech/opengr8on/util/FileUtil.java b/common/src/main/java/pl/psobiech/opengr8on/util/FileUtil.java new file mode 100644 index 0000000..0c019c7 --- /dev/null +++ b/common/src/main/java/pl/psobiech/opengr8on/util/FileUtil.java @@ -0,0 +1,307 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.util; + +import java.io.Closeable; +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.WeakHashMap; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.SystemUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import pl.psobiech.opengr8on.exceptions.UnexpectedException; + +public final class FileUtil { + private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class); + + private static final String TMPDIR_PROPERTY = "java.io.tmpdir"; + + private static final String TEMPORARY_FILE_PREFIX = "tmp_"; + + private static final Pattern DISALLOWED_FILENAME_CHARACTERS = Pattern.compile("[/\\\\:*?\"<>|\0]+"); + + private static final Pattern WHITESPACE_CHARACTERS = Pattern.compile("\\s+"); + + private static final Path TEMPORARY_DIRECTORY; + + private static final TemporaryFileTracker FILE_TRACKER = new TemporaryFileTracker(); + + static { + try { + TEMPORARY_DIRECTORY = Files.createTempDirectory( + Paths.get(System.getProperty(TMPDIR_PROPERTY)) + .toAbsolutePath(), + TEMPORARY_FILE_PREFIX + ); + } catch (IOException e) { + throw new UnexpectedException(e); + } + + ThreadUtil.shutdownHook(() -> { + try { + Files.walkFileTree(TEMPORARY_DIRECTORY, new SimpleFileVisitor<>() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { + deleteQuietly(file); + + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) { + deleteQuietly(dir); + + return FileVisitResult.CONTINUE; + } + }); + } catch (IOException e) { + LOGGER.warn(e.getMessage(), e); + } + + deleteQuietly(TEMPORARY_DIRECTORY); + }); + + ThreadUtil.shutdownHook(FILE_TRACKER::cleanUp); + + mkdir(TEMPORARY_DIRECTORY); + } + + private FileUtil() { + // NOP + } + + public static Path temporaryDirectory() { + return temporaryDirectory(null); + } + + public static Path temporaryDirectory(Path parentPath) { + try { + return Files.createTempDirectory( + parentPath == null ? TEMPORARY_DIRECTORY : parentPath, + TEMPORARY_FILE_PREFIX + ) + .toAbsolutePath(); + } catch (IOException e) { + throw new UnexpectedException(e); + } + } + + public static Path temporaryFile() { + return temporaryFile(null, null); + } + + public static Path temporaryFile(String fileName) { + return temporaryFile(null, fileName); + } + + public static Path temporaryFile(Path parentPath) { + return temporaryFile(parentPath, null); + } + + public static Path temporaryFile(Path parentPath, String fileName) { + try { + return FILE_TRACKER.tracked( + Files.createTempFile( + parentPath == null ? TEMPORARY_DIRECTORY : parentPath, + TEMPORARY_FILE_PREFIX, sanitize(fileName) + ) + .toAbsolutePath() + ); + } catch (IOException e) { + throw new UnexpectedException(e); + } + } + + public static void mkdir(Path path) { + try { + Files.createDirectories(path); + } catch (IOException e) { + throw new UnexpectedException(e); + } + } + + public static void touch(Path path) { + try { + Files.newOutputStream(path, StandardOpenOption.CREATE).close(); + } catch (IOException e) { + throw new UnexpectedException(e); + } + } + + public static void linkOrCopy(Path from, Path to) { + deleteQuietly(to); + + if (!SystemUtils.IS_OS_WINDOWS) { + try { + Files.createLink(to, from); + + return; + } catch (Exception e) { + // log exception and revert to copy + + LOGGER.warn(e.getMessage(), e); + } + } + + try { + Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + throw new UnexpectedException(e); + } + } + + public static void deleteQuietly(Path... paths) { + for (Path path : paths) { + deleteQuietly(path); + } + } + + public static void deleteQuietly(Path path) { + if (path == null) { + return; + } + + try { + Files.deleteIfExists(path); + } catch (IOException e) { + final boolean isFileOrLinkOrDoesNotExist = !Files.isDirectory(path); + if (isFileOrLinkOrDoesNotExist) { + LOGGER.warn(e.getMessage(), e); + } else if (LOGGER.isTraceEnabled()) { + // directories might be not-empty, hence not removable + LOGGER.trace(e.getMessage(), e); + } + } + } + + public static void closeQuietly(Closeable... closeables) { + for (Closeable closeable : closeables) { + closeQuietly(closeable); + } + } + + public static void closeQuietly(Closeable closeable) { + if (closeable == null) { + return; + } + + try { + closeable.close(); + } catch (IOException e) { + LOGGER.warn(e.getMessage(), e); + } + } + + public static String sanitize(String fileName) { + fileName = StringUtils.stripToNull(fileName); + if (fileName == null) { + return null; + } + + final String fileNameNoDisallowedCharacters = DISALLOWED_FILENAME_CHARACTERS.matcher(fileName) + .replaceAll("_"); + + return WHITESPACE_CHARACTERS.matcher(fileNameNoDisallowedCharacters) + .replaceAll("_"); + } + + public static long size(Path path) { + try { + return Files.size(path); + } catch (IOException e) { + throw new UnexpectedException(e); + } + } + + public static class TemporaryFileTracker { + private final Map stacktraces = new HashMap<>(); + + private final Map reachablePaths = new WeakHashMap<>(); + + private TemporaryFileTracker() { + // NOP + } + + public void cleanUp() { + final Map unreachablePaths = new HashMap<>(); + + synchronized (stacktraces) { + final Iterator> iterator = stacktraces.entrySet().iterator(); + while (iterator.hasNext()) { + final Entry entry = iterator.next(); + + final Path path = Paths.get(entry.getKey()); + synchronized (reachablePaths) { + if (reachablePaths.containsKey(path)) { + continue; + } + } + + iterator.remove(); + + if (Files.exists(path)) { + unreachablePaths.put(path, entry.getValue()); + } + } + } + + for (Entry entry : unreachablePaths.entrySet()) { + final Path path = entry.getKey(); + + if (Files.exists(path)) { + final UnexpectedException e = entry.getValue(); + + LOGGER.warn(e.getMessage(), e); + } + } + } + + public Path tracked(Path path) { + final Path absolutePath = path.toAbsolutePath(); + final String absolutePathAsString = absolutePath.toString(); + + final UnexpectedException + stacktrace = + new UnexpectedException("Temporary Path went out of scope, and the file was not removed: " + absolutePathAsString); + synchronized (stacktraces) { + stacktraces.put(absolutePathAsString, stacktrace); + } + + synchronized (reachablePaths) { + reachablePaths.put(absolutePath, Boolean.TRUE); + } + + return absolutePath; + } + } +} diff --git a/common/src/main/java/pl/psobiech/opengr8on/util/HexUtil.java b/common/src/main/java/pl/psobiech/opengr8on/util/HexUtil.java new file mode 100644 index 0000000..cfe076b --- /dev/null +++ b/common/src/main/java/pl/psobiech/opengr8on/util/HexUtil.java @@ -0,0 +1,123 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.util; + +import java.math.BigInteger; + +import org.apache.commons.codec.DecoderException; +import org.apache.commons.codec.binary.Hex; +import pl.psobiech.opengr8on.exceptions.UnexpectedException; + +import static org.apache.commons.lang3.StringUtils.upperCase; + +public final class HexUtil { + static final int HEX_BASE = 16; + + static final String HEX_PREFIX = "0x"; + + private HexUtil() { + // NOP + } + + public static long asLong(String hexAsString) { + try { + return Long.parseUnsignedLong( + stripPrefix(hexAsString), + HEX_BASE + ); + } catch (NumberFormatException e) { + throw new UnexpectedException(String.format("Value %s is not in the correct HEX format", hexAsString), e); + } + } + + public static int asInt(String hexAsString) { + try { + return Integer.parseUnsignedInt( + stripPrefix(hexAsString), + HEX_BASE + ); + } catch (NumberFormatException e) { + throw new UnexpectedException(String.format("Value %s is not in the correct HEX format", hexAsString), e); + } + } + + public static byte[] asBytes(String hexAsString) { + try { + return Hex.decodeHex( + stripPrefix(hexAsString) + ); + } catch (DecoderException e) { + throw new UnexpectedException(String.format("Value %s is not in the correct HEX format", hexAsString), e); + } + } + + private static String stripPrefix(String hexAsString) { + if (hexAsString.startsWith(HEX_PREFIX)) { + return hexAsString.substring(HEX_PREFIX.length()); + } + + return hexAsString; + } + + public static String asString(BigInteger value) { + if (value == null) { + return null; + } + + return format(value.toString(HEX_BASE)); + } + + public static String asString(byte value) { + return asString(value & 0xFF); + } + + public static String asString(byte[] array) { + return format(Hex.encodeHexString(array)); + } + + public static String asString(Integer value) { + if (value == null) { + return null; + } + + return format(Integer.toHexString(value)); + } + + public static String asString(Long value) { + if (value == null) { + return null; + } + + return format(Long.toHexString(value)); + } + + private static String format(String valueAsString) { + return evenZeroLeftPad( + upperCase(valueAsString) + ); + } + + private static String evenZeroLeftPad(String valueAsString) { + if (valueAsString.length() % 2 == 0) { + return valueAsString; + } + + return '0' + valueAsString; + } +} diff --git a/common/src/main/java/pl/psobiech/opengr8on/util/IPv4AddressUtil.java b/common/src/main/java/pl/psobiech/opengr8on/util/IPv4AddressUtil.java new file mode 100644 index 0000000..bf02f05 --- /dev/null +++ b/common/src/main/java/pl/psobiech/opengr8on/util/IPv4AddressUtil.java @@ -0,0 +1,386 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.util; + +import java.io.IOException; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.InterfaceAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.nio.ByteBuffer; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import pl.psobiech.opengr8on.exceptions.UnexpectedException; + +public final class IPv4AddressUtil { + private static final Logger LOGGER = LoggerFactory.getLogger(IPv4AddressUtil.class); + + private static final int PING_TIMEOUT = 2000; + + public static final Set DEFAULT_BROADCAST_ADDRESSES = Set.of( + parseIPv4("255.255.255.255"), + parseIPv4("255.255.0.0"), + parseIPv4("255.0.0.0") + ); + + public static final Set HARDWARE_ADDRESS_PREFIX_BLACKLIST = Set.of( + HexUtil.asString(0x000569), // VMware, Inc. + HexUtil.asString(0x001c14), // VMware, Inc. + HexUtil.asString(0x000c29), // VMware, Inc. + HexUtil.asString(0x005056) // VMware, Inc. + ); + + public static final Set NETWORK_INTERFACE_NAME_PREFIX_BLACKLIST = Set.of( + "vmnet", "vboxnet", "docker" + ); + + private IPv4AddressUtil() { + // NOP + } + + public static Optional getLocalIPv4NetworkInterfaceByName(String name) { + final List networkInterfaces = getLocalIPv4NetworkInterfaces(); + for (NetworkInterfaceDto networkInterface : networkInterfaces) { + if (Objects.equals(networkInterface.getNetworkInterface().getName(), name)) { + return Optional.of(networkInterface); + } + } + + return Optional.empty(); + } + + public static Optional getLocalIPv4NetworkInterfaceByIpAddress(String ipAddress) { + final List networkInterfaces = getLocalIPv4NetworkInterfaces(); + for (NetworkInterfaceDto networkInterface : networkInterfaces) { + if (Objects.equals(networkInterface.getAddress().getHostAddress(), ipAddress)) { + return Optional.of(networkInterface); + } + } + + return Optional.empty(); + } + + public static List getLocalIPv4NetworkInterfaces() { + final List validNetworkInterfaces = allValidNetworkInterfaces(); + final List networkInterfaces = new ArrayList<>(validNetworkInterfaces.size()); + for (NetworkInterface networkInterface : validNetworkInterfaces) { + for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { + final InetAddress address = interfaceAddress.getAddress(); + if (!(address instanceof Inet4Address)) { + continue; + } + + final InetAddress broadcastAddress = interfaceAddress.getBroadcast(); + if (!(broadcastAddress instanceof Inet4Address)) { + continue; + } + + if (!address.isSiteLocalAddress()) { + continue; + } + + final int networkMask = getNetworkMaskFromPrefix(interfaceAddress.getNetworkPrefixLength()); + + networkInterfaces.add(new NetworkInterfaceDto( + (Inet4Address) address, (Inet4Address) broadcastAddress, + networkMask, + networkInterface + )); + } + } + + return networkInterfaces; + } + + private static int getNetworkMaskFromPrefix(short networkPrefixLength) { + int networkMask = 0x00; + for (int i = 0; i < 32 - networkPrefixLength; i++) { + networkMask += (1 << i); + } + + networkMask ^= 0xFFFFFFFF; + + return networkMask; + } + + private static List allValidNetworkInterfaces() { + final List networkInterfaces; + try { + networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); + } catch (SocketException e) { + throw new UnexpectedException(e); + } + + final List validNetworkInterfaces = new ArrayList<>(networkInterfaces.size()); + for (NetworkInterface networkInterface : networkInterfaces) { + try { + if (!networkInterface.isUp() + || networkInterface.isLoopback() + || networkInterface.isPointToPoint() + || isBlacklisted(networkInterface) + ) { + continue; + } + } catch (SocketException e) { + LOGGER.warn(e.getMessage(), e); + + continue; + } + + validNetworkInterfaces.add(networkInterface); + } + + return validNetworkInterfaces; + } + + private static boolean isBlacklisted(NetworkInterface networkInterface) throws SocketException { + final String networkInterfaceName = networkInterface.getName(); + for (String blacklistedNetworkInterfaceNamePrefix : NETWORK_INTERFACE_NAME_PREFIX_BLACKLIST) { + if (networkInterfaceName.startsWith(blacklistedNetworkInterfaceNamePrefix)) { + return true; + } + } + + final byte[] hardwareAddress = networkInterface.getHardwareAddress(); + if (hardwareAddress == null) { + return true; + } + + return isHardwareAddressBlacklisted(hardwareAddress); + } + + private static boolean isHardwareAddressBlacklisted(byte[] macAddress) { + if (macAddress == null) { + return true; + } + + final String hardwareAddressPrefix = HexUtil.asString(Arrays.copyOf(macAddress, 3)); + + return HARDWARE_ADDRESS_PREFIX_BLACKLIST.contains(hardwareAddressPrefix); + } + + public static Inet4Address parseIPv4(String ipv4AddressAsString) { + try { + return (Inet4Address) InetAddress.getByAddress( + getIPv4AsBytes(ipv4AddressAsString) + ); + } catch (UnknownHostException e) { + throw new UnexpectedException(e); + } + } + + public static Inet4Address parseIPv4(int ipv4AddressAsNumber) { + try { + final byte[] buffer = asBytes(ipv4AddressAsNumber); + + return (Inet4Address) InetAddress.getByAddress(buffer); + } catch (UnknownHostException e) { + throw new UnexpectedException(e); + } + } + + public static String getIPv4FromNumber(int ipv4AsNumber) { + final byte[] buffer = asBytes(ipv4AsNumber); + + return IntStream.range(0, Integer.BYTES) + .mapToObj(i -> String.valueOf(buffer[i] & 0xFF)) + .collect(Collectors.joining(".")); + } + + private static byte[] asBytes(int ipv4AsNumber) { + final ByteBuffer byteBuffer = ByteBuffer.allocate(Integer.BYTES); + + byteBuffer.putInt(ipv4AsNumber); + byteBuffer.flip(); + + return byteBuffer.array(); + } + + public static int getIPv4AsNumber(Inet4Address inetAddress) { + return getIPv4AsNumber(inetAddress.getAddress()); + } + + public static int getIPv4AsNumber(String ipv4AddressAsString) { + return getIPv4AsNumber(getIPv4AsBytes(ipv4AddressAsString)); + } + + public static int getIPv4AsNumber(byte[] ipv4AddressAsBytes) { + if (ipv4AddressAsBytes.length != Integer.BYTES) { + throw new UnexpectedException("Invalid IPv4 address: " + Arrays.toString(ipv4AddressAsBytes)); + } + + return ByteBuffer.wrap(ipv4AddressAsBytes) + .getInt(); + } + + private static byte[] getIPv4AsBytes(String ipv4AddressAsString) { + final String[] ipAddressParts = Util.splitAtLeast(ipv4AddressAsString, "\\.", Integer.BYTES) + .orElseThrow(() -> new UnexpectedException("Invalid IPv4 address: " + ipv4AddressAsString)); + + final byte[] addressAsBytes = new byte[Integer.BYTES]; + for (int i = 0; i < 4; i++) { + addressAsBytes[i] = (byte) Integer.parseInt(ipAddressParts[i]); + } + + return addressAsBytes; + } + + public static boolean ping(InetAddress inetAddress) { + try { + return inetAddress.isReachable(PING_TIMEOUT); + } catch (IOException e) { + LOGGER.warn(e.getMessage(), e); + + return false; + } + } + + public static final class NetworkInterfaceDto { + private final Inet4Address address; + + private final Inet4Address broadcastAddress; + + private final int networkAddress; + + private final int networkMask; + + private final NetworkInterface networkInterface; + + public NetworkInterfaceDto( + Inet4Address address, Inet4Address broadcastAddress, + int networkMask, + NetworkInterface networkInterface + ) { + this.address = address; + + final int addressAsNumber = IPv4AddressUtil.getIPv4AsNumber(address.getAddress()); + this.networkAddress = addressAsNumber & networkMask; + + assert IPv4AddressUtil.getIPv4AsNumber(broadcastAddress) == (networkAddress | (~networkMask)); + this.broadcastAddress = broadcastAddress; + this.networkMask = networkMask; + + this.networkInterface = networkInterface; + } + + public Inet4Address getAddress() { + return address; + } + + public Inet4Address getNetworkAddress() { + return parseIPv4(networkAddress); + } + + public Inet4Address getBroadcastAddress() { + return broadcastAddress; + } + + public int getNetworkMask() { + return networkMask; + } + + public NetworkInterface getNetworkInterface() { + return networkInterface; + } + + public boolean valid(Inet4Address address) { + final int ipAsNumber = getIPv4AsNumber(address); + + return ipAsNumber > networkAddress && ipAsNumber < IPv4AddressUtil.getIPv4AsNumber(broadcastAddress); + } + + public Optional nextAvailable( + Inet4Address startingAddress, + Duration timeout, + Inet4Address currentAddress, + Collection exclusionList + ) { + final List addresses = nextAvailableExcluding(startingAddress, timeout, 1, currentAddress, exclusionList); + if (addresses.isEmpty()) { + return Optional.empty(); + } + + return Optional.of(addresses.getFirst()); + } + + public List nextAvailableExcluding( + Inet4Address startingAddress, + Duration timeout, + int limit, + Inet4Address currentAddress, + Collection exclusionList + ) { + final Set excludedIpAddressNumbers = exclusionList.stream() + .map(IPv4AddressUtil::getIPv4AsNumber) + .collect(Collectors.toSet()); + + int currentIpAsNumber = getIPv4AsNumber(currentAddress); + int ipAsNumber = getIPv4AsNumber(startingAddress); + + final List addresses = new ArrayList<>(limit); + do { + final long startedAt = System.nanoTime(); + + final int addressAsNumber = ipAsNumber++; + if (currentIpAsNumber == addressAsNumber) { + addresses.add(currentAddress); + continue; + } + + if (excludedIpAddressNumbers.contains(addressAsNumber)) { + continue; + } + + final Inet4Address address = parseIPv4(addressAsNumber); + if (!ping(address)) { + addresses.add(address); + } + + timeout = timeout.minusNanos(System.nanoTime() - startedAt); + } while (timeout.isPositive() && addresses.size() < limit && !Thread.interrupted()); + + return addresses; + } + + @Override + public String toString() { + return "NetworkInterfaceDto{" + + "networkInterface=" + ToStringUtil.toString(networkInterface) + + ", address=" + ToStringUtil.toString(address) + + ", broadcastAddress=" + ToStringUtil.toString(broadcastAddress) + + ", networkAddress=" + ToStringUtil.toString(parseIPv4(networkAddress)) + + ", networkMask=" + ToStringUtil.toString(parseIPv4(networkMask)) + + '}'; + } + } +} diff --git a/common/src/main/java/pl/psobiech/opengr8on/util/ObjectMapperFactory.java b/common/src/main/java/pl/psobiech/opengr8on/util/ObjectMapperFactory.java new file mode 100644 index 0000000..e158e5e --- /dev/null +++ b/common/src/main/java/pl/psobiech/opengr8on/util/ObjectMapperFactory.java @@ -0,0 +1,74 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.util; + +import java.lang.reflect.InvocationTargetException; + +import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.json.JsonMapper; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; +import pl.psobiech.opengr8on.exceptions.UnexpectedException; + +public final class ObjectMapperFactory { + public static final XmlMapper XML = ObjectMapperFactory.create(XmlMapper.class); + + public static final JsonMapper JSON = ObjectMapperFactory.create(JsonMapper.class); + + private ObjectMapperFactory() { + // NOP + } + + public static M create(Class clazz) { + try { + final M objectMapperInstance = clazz.getConstructor().newInstance(); + + return configureJacksonObjectMapper(objectMapperInstance); + } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { + throw new UnexpectedException(e); + } + } + + private static M configureJacksonObjectMapper(M mapper) { + mapper.registerModule(new JavaTimeModule()) + .registerModule(new ParameterNamesModule()) + .registerModule(new JacksonXmlModule()); + + mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + + mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(false)); + + mapper.setVisibility( + mapper.getSerializationConfig() + .getDefaultVisibilityChecker() + .withVisibility(PropertyAccessor.FIELD, Visibility.ANY) + ); + + return mapper; + } +} diff --git a/common/src/main/java/pl/psobiech/opengr8on/util/RandomUtil.java b/common/src/main/java/pl/psobiech/opengr8on/util/RandomUtil.java new file mode 100644 index 0000000..d23722f --- /dev/null +++ b/common/src/main/java/pl/psobiech/opengr8on/util/RandomUtil.java @@ -0,0 +1,142 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.util; + +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Random; +import java.util.function.Function; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import pl.psobiech.opengr8on.exceptions.UnexpectedException; + +public final class RandomUtil { + private static final Logger LOGGER = LoggerFactory.getLogger(RandomUtil.class); + + private static final ThreadLocal WEAK_RANDOM_THREAD_LOCAL = ThreadLocal.withInitial(RandomUtil::createWeakRandom); + + private static final SecureRandom STRONG_RANDOM; + + private static final int UNIQUE_MAX_RETRIES = 32; + + private static final int BYTE_MASK = 0xFF; + + private static final int NIBBLE_MASK = 0x0F; + + private static final char[] HEX_DICTIONARY; + + static { + try { + STRONG_RANDOM = SecureRandom.getInstanceStrong(); + } catch (NoSuchAlgorithmException e) { + throw new UnexpectedException("No strong random PRNG available", e); + } + + final char[] chars = new char[HexUtil.HEX_BASE]; + for (int i = 0; i < chars.length; i++) { + chars[i] = Integer.toHexString(i).charAt(0); + } + + HEX_DICTIONARY = chars; + } + + private static SecureRandom createWeakRandom() { + return new SecureRandom(); + } + + private RandomUtil() { + // NOP + } + + public static String unique(int length, Function generatorFunction, Function existsFunction) { + int retries = UNIQUE_MAX_RETRIES; + + String candidate; + do { + if (--retries < 0) { + throw new UnexpectedException("Cannot generate unique value"); + } + + candidate = generatorFunction.apply(length); + } while (existsFunction.apply(candidate) && !Thread.interrupted()); + + return candidate; + } + + /** + * @return random hex string (weak rng) + */ + public static String hexString(int length) { + return dictionaryString(random(false), length, HEX_DICTIONARY); + } + + /** + * @return random hex string + */ + public static String hexString(Random random, int length) { + return dictionaryString(random, length, HEX_DICTIONARY); + } + + /** + * @return random dictionary string + */ + private static String dictionaryString(Random random, int length, char[] dictionary) { + final StringBuilder sb = new StringBuilder(); + + final byte[] randomBytes = bytes(random, Math.floorDiv(length + 1, 2)); + for (byte randomByte : randomBytes) { + final int unsignedByte = randomByte & BYTE_MASK; + + sb.append(dictionary[unsignedByte & NIBBLE_MASK]); + sb.append(dictionary[unsignedByte >> (Byte.SIZE / 2)]); + } + + if (sb.length() > length) { + sb.setLength(length); + } + + return sb.toString(); + } + + /** + * @return random array of bytes (weak rng) + */ + public static byte[] bytes(int size) { + return bytes(random(false), size); + } + + /** + * @return random array of bytes + */ + public static byte[] bytes(Random random, int size) { + final byte[] salt = new byte[size]; + random.nextBytes(salt); + + return salt; + } + + public static SecureRandom random(boolean strong) { + if (strong) { + return RandomUtil.STRONG_RANDOM; + } + + return RandomUtil.WEAK_RANDOM_THREAD_LOCAL.get(); + } +} diff --git a/common/src/main/java/pl/psobiech/opengr8on/util/SocketUtil.java b/common/src/main/java/pl/psobiech/opengr8on/util/SocketUtil.java new file mode 100644 index 0000000..648cf0b --- /dev/null +++ b/common/src/main/java/pl/psobiech/opengr8on/util/SocketUtil.java @@ -0,0 +1,167 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.util; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.Inet4Address; +import java.net.InetSocketAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.net.StandardSocketOptions; +import java.time.Duration; +import java.util.Arrays; +import java.util.Optional; + +import pl.psobiech.opengr8on.exceptions.UnexpectedException; + +public class SocketUtil { + public static final int DEFAULT_TIMEOUT = 9_000; + + private static final int IPTOS_RELIABILITY = 0x04; + + private SocketUtil() { + // NOP + } + + public static UDPSocket udp(Inet4Address address, int port) { + return new UDPSocket( + address, port, false, null + ); + } + + public static UDPSocket udp(NetworkInterface networkInterface, Inet4Address address) { + return new UDPSocket( + address, 0, true, networkInterface + ); + } + + public static class UDPSocket { + private final Inet4Address address; + + private final int port; + + private final boolean broadcast; + + private final NetworkInterface networkInterface; + + private DatagramSocket socket; + + public UDPSocket(Inet4Address address, int port, boolean broadcast, NetworkInterface networkInterface) { + this.address = address; + this.port = port; + this.broadcast = broadcast; + this.networkInterface = networkInterface; + } + + public void open() { + synchronized (this) { + try { + this.socket = new DatagramSocket(new InetSocketAddress(address, port)); + this.socket.setSoTimeout(DEFAULT_TIMEOUT); + this.socket.setTrafficClass(IPTOS_RELIABILITY); + + this.socket.setBroadcast(broadcast); + if (broadcast) { + this.socket.setOption(StandardSocketOptions.IP_MULTICAST_IF, networkInterface); + } + } catch (IOException e) { + throw new UnexpectedException(e); + } + } + } + + public void send(DatagramPacket packet) { + synchronized (this) { + try { + socket.send(packet); + } catch (IOException e) { + throw new UnexpectedException(e); + } + } + } + + public void discard(DatagramPacket packet) { + synchronized (this) { + try { + socket.setSoTimeout(1); + do { + socket.receive(packet); + } while (packet.getLength() > 0 && !Thread.interrupted()); + } catch (IOException e) { + // NOP + } finally { + try { + socket.setSoTimeout(DEFAULT_TIMEOUT); + } catch (SocketException e) { + // NOP + } + } + } + } + + public Optional tryReceive(DatagramPacket packet, Duration timeout) { + synchronized (this) { + try { + socket.setSoTimeout(Math.toIntExact(timeout.toMillis())); + socket.receive(packet); + socket.setSoTimeout(DEFAULT_TIMEOUT); + } catch (SocketTimeoutException e) { + return Optional.empty(); + } catch (IOException e) { + throw new UnexpectedException(e); + } + + return Optional.of( + Payload.of( + (Inet4Address) packet.getAddress(), packet.getPort(), + Arrays.copyOfRange( + packet.getData(), + packet.getOffset(), packet.getOffset() + packet.getLength() + ) + ) + ); + } + } + + public void close() { + synchronized (this) { + FileUtil.closeQuietly(this.socket); + + this.socket = null; + } + } + } + + public record Payload(Inet4Address address, int port, byte[] buffer) { + public static Payload of(Inet4Address ipAddress, int port, byte[] buffer) { + return new Payload(ipAddress, port, buffer); + } + + @Override + public String toString() { + return "Payload{" + + "address=" + ToStringUtil.toString(address, port) + + ", buffer=" + ToStringUtil.toString(buffer) + + '}'; + } + } +} diff --git a/common/src/main/java/pl/psobiech/opengr8on/util/ThreadUtil.java b/common/src/main/java/pl/psobiech/opengr8on/util/ThreadUtil.java new file mode 100644 index 0000000..e209a7b --- /dev/null +++ b/common/src/main/java/pl/psobiech/opengr8on/util/ThreadUtil.java @@ -0,0 +1,61 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.util; + +import java.util.concurrent.ThreadFactory; +import java.util.function.BiFunction; + +public class ThreadUtil { + private static final ThreadFactory DEFAULT_DAEMON_FACTORY = daemonThreadFactory("default"); + + private static final ThreadFactory SHUTDOWN_HOOK_FACTORY = threadFactory(false, "shutdownHooks", Thread::new); + + private ThreadUtil() { + // NOP + } + + public static void shutdownHook(Runnable runnable) { + Runtime.getRuntime().addShutdownHook( + SHUTDOWN_HOOK_FACTORY.newThread(runnable) + ); + } + + public static Thread newDaemonThread(Runnable runnable) { + return DEFAULT_DAEMON_FACTORY.newThread(runnable); + } + + public static ThreadFactory daemonThreadFactory(String groupName) { + return daemonThreadFactory(groupName, Thread::new); + } + + public static ThreadFactory daemonThreadFactory(String groupName, BiFunction supplier) { + return threadFactory(true, groupName, supplier); + } + + public static ThreadFactory threadFactory(boolean daemon, String groupName, BiFunction supplier) { + final ThreadGroup threadGroup = new ThreadGroup(groupName); + + return runnable -> { + final Thread thread = supplier.apply(threadGroup, runnable); + thread.setDaemon(daemon); + + return thread; + }; + } +} diff --git a/common/src/main/java/pl/psobiech/opengr8on/util/ToStringUtil.java b/common/src/main/java/pl/psobiech/opengr8on/util/ToStringUtil.java new file mode 100644 index 0000000..cf5101b --- /dev/null +++ b/common/src/main/java/pl/psobiech/opengr8on/util/ToStringUtil.java @@ -0,0 +1,112 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.util; + +import java.net.Inet4Address; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.lang3.StringUtils; + +public final class ToStringUtil { + private ToStringUtil() { + // NOP + } + + public static String toString(Inet4Address address, Integer port) { + final String addressAsString = toString(address); + if (port == null) { + return addressAsString; + } + + return "%s:%d".formatted(addressAsString, port); + } + + public static String toString(Inet4Address address) { + if (address == null) { + return null; + } + + return "%s::%s%s".formatted( + address.getHostAddress(), + HexUtil.HEX_PREFIX, HexUtil.asString(IPv4AddressUtil.getIPv4AsNumber(address)) + ); + } + + public static String toString(Long value) { + if (value == null) { + return null; + } + + return "%d::%s%s".formatted( + value, + HexUtil.HEX_PREFIX, HexUtil.asString(value) + ); + } + + public static String toString(Integer value) { + if (value == null) { + return null; + } + + return "%d::%s%s".formatted( + value, + HexUtil.HEX_PREFIX, HexUtil.asString(value) + ); + } + + public static String toString(NetworkInterface networkInterface) { + if (networkInterface == null) { + return null; + } + + byte[] hardwareAddress = null; + try { + hardwareAddress = networkInterface.getHardwareAddress(); + } catch (SocketException e) { + // NOP + } + + return networkInterface.getName() + " (" + networkInterface.getDisplayName() + ") [" + toString(hardwareAddress) + "]"; + } + + public static String toString(byte[] buffer) { + if (buffer == null) { + return null; + } + + final String asciiValues = new String(buffer) + .replaceAll("[^\\p{Graph}]", "."); + + final String hexString = StringUtils.stripToEmpty( + IntStream.range(0, buffer.length) + .mapToObj(i -> (i % 2 == 0 ? " " : "") + HexUtil.asString(buffer[i])) + .collect(Collectors.joining()) + ); + + return "'%s # %s # %s'".formatted( + asciiValues, + hexString, + Base64.encodeBase64String(buffer) + ); + } +} diff --git a/common/src/main/java/pl/psobiech/opengr8on/util/Util.java b/common/src/main/java/pl/psobiech/opengr8on/util/Util.java new file mode 100644 index 0000000..192ccbb --- /dev/null +++ b/common/src/main/java/pl/psobiech/opengr8on/util/Util.java @@ -0,0 +1,227 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.util; + +import java.text.DecimalFormat; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +import static java.lang.Math.max; +import static java.lang.Math.min; +import static java.lang.Math.round; + +public final class Util { + public static final int ONE_HUNDRED_PERCENT = 100; + + private static final double ONE_HUNDRED_PERCENT_DOUBLE = ONE_HUNDRED_PERCENT; + + private Util() { + // NOP + } + + public static Optional repeatUntilTrueOrTimeout(Duration timeout, Function> fn) { + Optional optionalBoolean; + do { + final long startedAt = System.nanoTime(); + + optionalBoolean = fn.apply(timeout); + if (optionalBoolean.isPresent() && optionalBoolean.get()) { + return optionalBoolean; + } + + timeout = timeout.minusNanos(System.nanoTime() - startedAt); + } while (timeout.isPositive() && !Thread.interrupted()); + + return optionalBoolean; + } + + public static Optional repeatUntilTimeout(Duration timeout, Function> fn) { + return repeatUntilTimeoutOrLimit(timeout, 1, fn).stream().findAny(); + } + + public static List repeatUntilTimeoutOrLimit(Duration timeout, int limit, Function> fn) { + final ArrayList results = new ArrayList<>(Math.max(limit == Integer.MAX_VALUE ? -1 : limit, 0)); + do { + final long startedAt = System.nanoTime(); + + fn.apply(timeout) + .ifPresent(results::add); + + timeout = timeout.minusNanos(System.nanoTime() - startedAt); + } while (timeout.isPositive() && results.size() < limit && !Thread.interrupted()); + + return results; + } + + public static Optional splitExact(String value, String pattern, int exactlyParts) { + final String[] split = value.split(pattern, exactlyParts + 1); + if (split.length != exactlyParts) { + return Optional.empty(); + } + + return Optional.of(split); + } + + public static Optional splitAtLeast(String value, String pattern, int atLeastParts) { + final String[] split = value.split(pattern, atLeastParts + 1); + if (split.length < atLeastParts) { + return Optional.empty(); + } + + return Optional.of(split); + } + + public static int percentage(long elementCount, long totalElementCount) { + return (int) max(0, min(ONE_HUNDRED_PERCENT_DOUBLE, round((elementCount * ONE_HUNDRED_PERCENT_DOUBLE) / (double) totalElementCount))); + } + + /** + * @return tries to convert a Serializable to Number formatted as string (with 2 decimal places), defaults to {@link String#valueOf(Object)} + */ + public static String formatNumber(Number value) { + if (value == null) { + return null; + } + + final DecimalFormat scoreDecimalFormat = new DecimalFormat("0.##"); + + return scoreDecimalFormat.format(((Number) value).doubleValue()); + } + + public static List nullAsEmpty(List list) { + if (list == null) { + return Collections.emptyList(); + } + + return list; + } + + public static Map nullAsEmpty(Map map) { + if (map == null) { + return Collections.emptyMap(); + } + + return map; + } + + public static Set nullAsEmpty(Set list) { + if (list == null) { + return Collections.emptySet(); + } + + return list; + } + + public static Collection nullAsEmpty(Collection list) { + if (list == null) { + return Collections.emptyList(); + } + + return list; + } + + public static T mapNullSafe(F from, Function mapper) { + return mapNullSafeWithDefault(from, mapper, null); + } + + public static T mapNullSafeWithDefault(F from, Function mapper, T nullValue) { + if (from != null) { + final T value = mapper.apply(from); + if (value != null) { + return value; + } + } + + return nullValue; + } + + public static List mapNullSafe(List from, Function mapper) { + return mapNullSafeListWithDefault(from, mapper, Collections.emptyList()); + } + + public static List mapNullSafeListWithDefault(List from, Function mapper, List nullValue) { + return Optional.ofNullable(from) + .map(f -> + f.stream() + .map(mapper) + .collect(Collectors.toList()) + ) + .orElse(nullValue); + } + + public static T nullAsDefault(T value, T defaultValue) { + return Objects.requireNonNullElse(value, defaultValue); + } + + public static T nullAsDefaultGet(T value, Supplier defaultValueSupplier) { + return Objects.requireNonNullElseGet(value, defaultValueSupplier); + } + + public static > EnumSet asEnum(List valueList, Class enumClass) { + if (valueList == null) { + return null; + } + + return valueList.stream() + .map(valueAsString -> Enum.valueOf(enumClass, valueAsString)) + .collect(Collectors.toCollection(() -> EnumSet.noneOf(enumClass))); + } + + /** + * @return lazy initiated singleton (thread safe) + */ + public static Supplier lazy(Supplier supplier) { + return cache(supplier); + } + + /** + * @return lazy initiated singleton (thread safe) + */ + public static Supplier cache(Supplier constructor) { + final AtomicReference reference = new AtomicReference<>(); + + return () -> { + final T currentValue = reference.get(); + if (currentValue != null) { + return currentValue; + } + + return reference.updateAndGet(value -> { + if (value != null) { + // new value was already allocated by some other thread between notnull check and here, we preserve the other thread value + return value; + } + + return constructor.get(); + }); + }; + } +} diff --git a/common/src/test/java/pl/psobiech/opengr8on/client/util/IPv4AddressUtilTest.java b/common/src/test/java/pl/psobiech/opengr8on/client/util/IPv4AddressUtilTest.java new file mode 100644 index 0000000..41e1280 --- /dev/null +++ b/common/src/test/java/pl/psobiech/opengr8on/client/util/IPv4AddressUtilTest.java @@ -0,0 +1,66 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.util; + +import java.net.Inet4Address; +import java.net.InetAddress; +import java.util.Collection; + +import org.junit.jupiter.api.Test; +import pl.psobiech.opengr8on.util.IPv4AddressUtil; +import pl.psobiech.opengr8on.util.IPv4AddressUtil.NetworkInterfaceDto; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +class IPv4AddressUtilTest { + @Test + void testParseIPv4() throws Exception { + final InetAddress expected = InetAddress.getByName("192.168.31.31"); + + final Inet4Address actual = IPv4AddressUtil.parseIPv4("192.168.31.31"); + + assertEquals(expected, actual); + } + + @Test + void testParseIPv4AsNumber() throws Exception { + final int expected = 0xA489001; + + final int actual = IPv4AddressUtil.getIPv4AsNumber("10.72.144.1"); + + assertEquals(expected, actual); + } + + @Test + void testGetIPv4FromNumber() throws Exception { + final String expected = "10.72.144.1"; + + final String actual = IPv4AddressUtil.getIPv4FromNumber(0xA489001); + + assertEquals(expected, actual); + } + + @Test + void testGetNetworkInterfaces() throws Exception { + final Collection networkInterfaces = IPv4AddressUtil.getLocalIPv4NetworkInterfaces(); + + assertFalse(networkInterfaces.isEmpty()); + } +} \ No newline at end of file diff --git a/common/src/test/resources/logback-test.xml b/common/src/test/resources/logback-test.xml new file mode 100644 index 0000000..3af7c46 --- /dev/null +++ b/common/src/test/resources/logback-test.xml @@ -0,0 +1,28 @@ + + + + + %date{"yyyy-MM-dd'T'HH:mm:ss,SSSXXX", UTC} [%level] %logger{15} - %message%n%xException{10} + + + + + + + diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..63729e2 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,19 @@ +version: "2.3" + +services: + opengr8on: + image: ghcr.io/psobiech/opengr8on:latest + command: wlp7s0 + restart: unless-stopped + read_only: false + security_opt: + - no-new-privileges:true + build: + target: app-runtime + network_mode: "host" + ports: + - "1234:1234" + volumes: + - type: bind + source: ./runtime + target: /opt/docker/runtime diff --git a/docs/COMMUNICATION.md b/docs/COMMUNICATION.md new file mode 100644 index 0000000..92f6208 --- /dev/null +++ b/docs/COMMUNICATION.md @@ -0,0 +1,130 @@ +# Discover CLU(s) / CLU Initialization + +All commands below are using port `1234/udp`. + +Local machine IP is 10.72.144.72/16. + +1. Use previously saved AES key and IV or generate new random AES Key and IV (both 16 bytes long) - we will call them OWN_KEY and OWN_IV +1. Broadcast the `req_discovery_clu` port using broadcast addresses in the network (eg. 255.255.255.255). + (The request itself is encrypted using Grenton special KEY/IV.) + ``` + REQUEST: + ::req_discovery_clu: + eg. ::req_discovery_clu:10.72.144.72 + ``` +1. Listen for responses from CLUs (`resp_discovery_clu`) + (The response itself is encrypted using Grenton special KEY, but with IV provided in the discovery request - OWN_IV) + ``` + RESPONSE: + randomBytes))>::resp_discovery_clu:: + eg. ::resp_discovery_clu:0dxxxxxx:80XXXXXXXXXX + ``` + * Detect if CLU has proper AES/IV key already configured if not then calculate default AES key using private key (using KEY from the sticker on the CLU), IV is randomized by CLU on reset +1. Broadcast the command `req_set_clu_ip` to set the IP address of the device + (The response itself is encrypted using Grenton special KEY, but with IV provided in the discovery request - OWN_IV) + ``` + REQUEST: + req_set_clu_ip::: + eg. req_set_clu_ip:0dxxxxxx:10.72.144.1:10.72.72.1 + + RESPONSE: + resp_set_clu_ip:: + eg. resp_set_clu_ip:0dxxxxxx:10.72.144.1 + ``` +1. Send command `req_set_key` to overwrite the key + (The request and response are encrypted using CLU KEY / IV from now on all messages will be encrypted using this key) + ``` + REQUEST: + ::req_set_key: + eg. ::req_set_key: + + RESPONSE: + resp:OK + ``` +1. Send the command `req_start_ftp` to enable TFTP server on the CLU (if necessary this command is repeated before _every_ file transfer) + ``` + REQUEST: + req_start_ftp + + RESPONSE: + resp:OK + ``` +1. TFTP Download a:\config.txt and a:\CONFIG.JSON files that contains versions of hardware and firmware, plus some other information +1. Load device interfaces for the CLU (using the hardware and software versions from config.txt and/or CONFIG.JSON) +1. Download a:\OM.LUA, a:\MAIN.LUA, a:\USER.LUA +1. Parse contents of the LUA files and check for errors / outdated features / etc or clean them. +1. Generate new contents of LUA files +1. Upload a:\MAIN.LUA, a:\OM.LUA, a:\USER.LUA +1. Send the command `req_reset` to reset the CLU and use the new scripts + ``` + REQUEST: + req_reset: + eg. req_reset:10.72.144.72 + + RESPONSE: + resp_reset: + eg. resp_reset:10.72.144.8 + ``` + +# Check Alive + ``` + REQUEST: + req:::checkAlive() + eg. req:10.72.144.72:003649:checkAlive() + + RESPONSE CLU: + resp::randomCharacters>: + eg. resp:10.72.144.1:00003649: + + RESPONSE GATE: + resp::randomCharacters>:true + eg. resp:10.72.144.1:000082b2:true + + RESPONSE CLU/GATE in Emergency mode: + resp::randomCharacters>:emergency + eg. resp:10.72.144.1:00004b35:emergency + ``` + +OM us using only 6 random characters, but CLU always responds using 8 characters (left padding with zero) - the communication seems to work correctly if using 8 characters for both request and response. + +In fact this command can be used to execute any LUA function declared in the script (including communication between multiple CLUs). + +## Fetch Data (Bulk) + +This command effectively executes the following LUA functions: +* SYSTEM:clientRegister() +* SYSTEM:clientDestroy() + +It seems to subscribe for some specific feature value changes, that are then pushed by the CLU into the specified IP/PORT every client report interval. +The default port is 4344. + +req:10.72.144.72:000616:SYSTEM:clientRegister("10.72.144.72",4344,49064,{{CLU22XXXXXXX,0},{CLU22XXXXXXX,1},{CLU22XXXXXXX,2},{CLU22XXXXXXX,3},{CLU22XXXXXXX,5},{CLU22XXXXXXX,6},{CLU22XXXXXXX,7},{CLU22XXXXXXX,8},{CLU22XXXXXXX,9},{CLU22XXXXXXX,10},{CLU22XXXXXXX,11},{CLU22XXXXXXX,12},{CLU22XXXXXXX,13},{CLU22XXXXXXX,17},{CLU22XXXXXXX,18},{CLU22XXXXXXX,19},{CLU22XXXXXXX,20},{CLU22XXXXXXX,21},{CLU22XXXXXXX,22},{CLU22XXXXXXX,23},{CLU22XXXXXXX,24},{CLU22XXXXXXX,25},{CLU22XXXXXXX,26},{CLU22XXXXXXX,27},{CLU22XXXXXXX,28},{CLU22XXXXXXX,29},{CLU22XXXXXXX,30},{CLU22XXXXXXX,31}}) +resp:10.72.144.1:00000616:clientReport:49064:{27,nil,1,true,"2023-12-05","00:20:47",5,12,2023,2,0,20,1701735647,"05.12.01-2330",false,false,50,230,"tempus1.gum.gov.pl",0,0,"8.8.8.8","8.8.4.4",24.09,0.50,25,23,0} +resp:10.72.144.1:00000000:clientReport:49064:{31,nil,1,true,"2023-12-05","00:20:52",5,12,2023,2,0,20,1701735652,"05.12.01-2330",false,false,50,230,"tempus1.gum.gov.pl",0,0,"8.8.8.8","8.8.4.4",24.14,0.50,25,23,0} +req:10.72.144.72:004716:SYSTEM:clientDestroy("10.72.144.72",4344,49064) +resp:10.72.144.1:00004716:49064 + +req:10.72.144.72:00f0d4:SYSTEM:clientRegister("10.72.144.72",4344,3903,{{PAN9821,1},{PAN9821,2},{PAN9821,3},{PAN9821,4},{PAN9821,0}}) +resp:10.72.144.1:0000f0d4:clientReport:3903:{0.50,500,0,100,0.50} +resp:10.72.144.1:00000000:clientReport:3903:{0.50,500,0,100,1.90} +resp:10.72.144.1:00000000:clientReport:3903:{0.50,500,0,100,0.70} +req:10.72.144.72:00b9fa:SYSTEM:clientDestroy("10.72.144.72",4344,3903) +resp:10.72.144.1:0000b9fa:3903 + +# Notes +1. It does seem like CLU supports all netmasks, but it's impossible to set a netmask during the initialization - it always defaults to 255.255.255.0, one can only override the netmask when setting the ip address using telnet command line. + +# Other possible commands to be investigated (some might not work or be false positives) +req_stop_ftp -- does not work? +req_tftp_stop -- does not work? +req_refresh_modules / resp_refresh_modules +req_gen_measurements +req_diagnostic_refresh +req_cert_gen +monitor_req_control / monitor_resp_state +monitor_resp_values / monitor_resp_packages +req_start_fw_upgrade / resp_fw_upgrade_status +req_fw_upgrade +req_refresh_config / resp_refresh_config +req_reload_scripts +req_check_alive / resp_check_alive diff --git a/docs/FIRMWARE.md b/docs/FIRMWARE.md new file mode 100644 index 0000000..b604597 --- /dev/null +++ b/docs/FIRMWARE.md @@ -0,0 +1,132 @@ +# Firmware locations + +> http://om.grenton.com/firmware/v5/firmware.list +> +> eg. +> http://om.grenton.com/firmware/v5/CLU_GATE_HTTP-18-2-3-1.1.0-2034C.fw + +# Hashes +6c4b8365dce7ed583fa8bbb515e87b4f37d72cda970598f06e4161415ee7344a ANALOG_IN_DIN-25-1-2-1.2.13-2125.fw +e13b231b5cc9b79fae56decf1136584c4b1779697bbcd8b9a6023903192273cb ANALOG_IN_DIN-25-1-2-1.2.5-1927A.fw +a22767b05e28a9a0865d09710fc369b6d023c0096ed5d99bb7113a73f1ed22bf ANALOG_IN_DIN-25-1-2-1.2.8-1949A.fw +4bd695d641b34ff8c10ab57d344ef1821745c9e1b5a790bc5fa7a891a81b935d ANALOG_IN_DIN-25-2-2-1.2.12-2010A.fw +7bfa3e85d324fc9a1d49452f9ef7040754f5bc12feb3d13a84915e1c7819cca7 ANALOG_IN_DIN-25-2-2-1.2.13-2125.fw + +153f6dcf89b8caa47c556577d089dc8cf9eb5dc74153f97674d55f6daed933f4 CLU_GATE_ALARM-18-2-2-1.1.0-2034C.fw +834eb9e88ad4e2ffb5bbd93fe4fa66e5858d082b35eaa9c83bbe8dd2b2c4b751834eb9e88ad4e2ffb5bbd93fe4fa66e5858d082b35eaa9c83bbe8dd2b2c4b751 CLU_GATE_ALARM-18-2-2-1.1.10-2140.fw +ebddabadeae03d1992e49c8c3a6c5845960fc7cda5555bd431321b2d70c71803 CLU_GATE_ALARM-18-2-2-1.1.11-2218B.fw +bb67c6229b315091f9a0b2a5d8801a73f2d52e4c4860d3502f10b7bf9ef629ec CLU_GATE_ALARM-18-2-2-1.1.20-2219.fw +183fc1354d2d292a3b519dddb4b72a7b2533d870f6ef3e52a79b95785bfd3dc5 CLU_GATE_ALARM-4294967295-4294967295-2-1.1.0-2012.fw + +a0e76ae29b112db808f5cee778e8d62636fbd578e9926a4f10cd7df50815d2f6 CLU_GATE_HTTP-18-1-3-1.0.1-1932.fw +153f6dcf89b8caa47c556577d089dc8cf9eb5dc74153f97674d55f6daed933f4 CLU_GATE_HTTP-18-2-3-1.1.0-2034C.fw +834eb9e88ad4e2ffb5bbd93fe4fa66e5858d082b35eaa9c83bbe8dd2b2c4b751 CLU_GATE_HTTP-18-2-3-1.1.10-2140.fw +ebddabadeae03d1992e49c8c3a6c5845960fc7cda5555bd431321b2d70c71803 CLU_GATE_HTTP-18-2-3-1.1.11-2218B.fw +d8df8eafc812c84bc74724ac6b2cf2876b6ad15a732311046d2b47ec71d23e21 CLU_GATE_HTTP-18-2-3-1.3.1-2243.fw +09ba7ae2b109c27f8ba6daa39336cabd102301874f407face64956f161a22fff CLU_GATE_HTTP-18-2-3-1.4.2-2346.fw +a0e76ae29b112db808f5cee778e8d62636fbd578e9926a4f10cd7df50815d2f6 CLU_GATE_HTTP-4294967295-4294967295-5-1.0.1-1932.fw + +153f6dcf89b8caa47c556577d089dc8cf9eb5dc74153f97674d55f6daed933f4 CLU_GATE_MODBUS-18-2-1-1.1.0-2034C.fw +834eb9e88ad4e2ffb5bbd93fe4fa66e5858d082b35eaa9c83bbe8dd2b2c4b751 CLU_GATE_MODBUS-18-2-1-1.1.10-2140.fw +317ad3883689ab37825660ca3f980a67e5c4fbd5f1fa7fa73bfc4f0510fd2412 CLU_GATE_MODBUS-18-2-1-1.4.1-2334.fw + +3575aa568af45d882e86777de2e7a26b5daee73ee63309ae213e2f94a03dfac5 CLU_WIFI_RL-35-1-1-1.1.4-2031.fw +d4f94a52edf3c805db6f19c907d57a2915496a1894b836be94cf971a2e6136d1 CLU_WIFI_RL-35-1-1-1.1.5-2137D.fw + +3575aa568af45d882e86777de2e7a26b5daee73ee63309ae213e2f94a03dfac5 CLU_WIFI_RL_PLUS-34-1-1-1.1.4-2031.fw +d4f94a52edf3c805db6f19c907d57a2915496a1894b836be94cf971a2e6136d1 CLU_WIFI_RL_PLUS-34-1-1-1.1.5-2137D.fw + +3575aa568af45d882e86777de2e7a26b5daee73ee63309ae213e2f94a03dfac5 CLU_WIFI_RS-41-1-1-1.1.4-2031.fw +d4f94a52edf3c805db6f19c907d57a2915496a1894b836be94cf971a2e6136d1 CLU_WIFI_RS-41-1-1-1.1.5-2137D.fw +21524078c5807b4b919df0643691efddf5f7856e72a528b14ff8e4f9c3986047 CLU_WIFI_RS-41-1-1-1.2.3-2310.fw + +f18db948d3eacfb75fe35003faebf5879083cfb7e6292bea83c18093adf8cbb5 CLU_WIFI_SP-33-1-1-1.1.5-2033.fw + +2ef3511cbfe53b1baee55d77e6181e29d2378b0a5a82da553846450ee46630f2 CLU_ZWAVE-0-0-3-4.7.49-1912.fw +68b24a2f53c8e13438484eb3cf69b1205d3cec802c9a4dbc7ed98fc34a2bf593 CLU_ZWAVE_2-19-1-3-5.04.09-1944B.fw +35f8bd120259c8a00bd058d70dabd073c33960e82223d3ca8b853fd5dc774809 CLU_ZWAVE_2-19-1-3-5.04.11-1949A.fw +78c3efbba7dff121f05ecf22050c5571be146426827f6807817a8ec2310e2c33 CLU_ZWAVE_2-19-1-3-5.04.14-2009.fw +93eeb3f762df745aa33e80212f7e7c83c0e05e60166fd99668540df7ec83ac34 CLU_ZWAVE_2-19-1-3-5.05.05-2014.fw +91efe62a1e35bbeb15a9e15df3b7581474f39150c161df2407cd111d6a0852d6 CLU_ZWAVE_2-19-1-3-5.06.03-2043.fw +632e45e099212a5c081746036494f91011e31b7994d5fd31966c3c93758d1a40 CLU_ZWAVE_2-19-1-3-5.06.04-2050.fw +639012aeae942194a3cec564ab5530262ec1f1c7a5a39555dbde6d3b5b5d7553 CLU_ZWAVE_2-19-1-3-5.07.02-2120C.fw +e64748dfb76dc0ab31cc4dd4ad94d9954f6380e4a08c489290c47fdf8cba2a7d CLU_ZWAVE_2-19-1-3-5.08.01-2128B.fw +d204e898bdb182be746bed0cfe7eb6da3ab5d27ef3c055d1338bab650ac0a070 CLU_ZWAVE_2-19-1-3-5.09.02-2208.fw +4d3cfff7e25037470d3cac8517fa14f3c14ef4c966089425cad93f2ab062e498 CLU_ZWAVE_2-19-1-3-5.10.03-2248.fw +888830e3da22c600362314c8aa2145841deb876345d1a3abd576456e21ed7e06 CLU_ZWAVE_2-19-1-3-5.12.01-2330.fw +bd8e7f3da1c591b999913105313a95ff8df2af2ecfc178323ed0d302bb77d54f CLU_ZWAVE_2-19-1-3-5.3.1-1924.fw +86ba732b01e8d3aa8be3b34658fdd6e321afa8ad48d98fc0127159ddff4edbfd CLU_ZWAVE_2-19-1-3-5.3.6-1927A.fw + +55fff6cad49745be6c52fca2b62f2a5a9fb77a8831a372bcbdb2eeeb8e04c48c DALI_MASTER_DIN-39-1-2-1.1.11-2048.fw +4a6c391e64bc4bc0a522262e7e45249dbc6685d961c5c83b90ff832e4ac3b587 DALI_MASTER_DIN-39-1-2-1.1.12-2321.fw + +aa084d980f59ce2e36ad4cfbb6870912a6ccbdd8fbd1c9e3881d5c117d32e681 DIGITAL_IN_DIN-20-1-2-1.2.12-2006.fw +cc2fa97c99a829fae3ffc416a65a18836447322e0a81abfc027536d1694ed044 DIGITAL_IN_DIN-20-1-2-1.2.14-2125.fw +74eb0366ba430eed767ab4589a291f3122ded248cc628e482b597e1843dea905 DIGITAL_IN_DIN-20-1-2-1.2.9-1920.fw +d1ab9085cee57c22b13d0a90a0e13ace50ff6fb9746ae29022acd50ab11347a4 DIGITAL_IN_FM-51-1-2-1.1.4-2334.fw + +226a117e2338e253106df87c04ee732cf25e611fb5b5b85587623137b43675bc DIMMER_MOSFET_DIN-26-1-2-1.1.11-2114.fw +17e0ae25973647853a0cbc8b0284086d4ae59c3dc936d1c1c25a305c6bbf9760 DIMMER_MOSFET_DIN-26-1-2-1.1.4-1927.fw +79c9358cdea20058600de19f44d6fb446f18b97ef5b0877b9520cac72ab0916f DIMMER_MOSFET_DIN-26-1-2-1.1.8-2008.fw +6d96f5d9fecbdd429e97f9fdf18ea80a9d016fa550f7f966d4259a7eb7bf8215 DIMMER_MOSFET_DIN-26-1-2-1.1.9-2020.fw +4abf8a87b145702c10dd826a3d1aea148d20ef52d58e7048b4c5c30983da0ee9 DIMMER_MOSFET_FM-44-1-2-1.2.2-2222H.fw + +78a4de7abb4939bc1884ccb809e2e480f0cb4672b2f89c34f6447920d25de181 IO_MODULE_DIN_8-30-1-2-1.4.11-2125.fw +4fa02d0dd30cb6dcc6b6195256a69d2a8d67ee1df378c6fd240bf0b0aa7f0cfb IO_MODULE_DIN_8-30-1-2-1.4.6-1921.fw +19cab49290922867a6c65e5d13509d2c86f27ce1166e6321917cec288b726fde IO_MODULE_DIN_8-30-1-2-1.4.9-2007.fw +111b25d6371e36d7dba7665e254fe8a3afee8733469ee430134a27effc32bb43 IO_MODULE_DIN_8-30-1-2-2.0.0-2325.fw + +f42371618980b0258167db36261a652b825c1c6bd0e98aef3ad3d2b4fee4e9ac IO_MODULE_FM-31-1-2-1.1.5-1922.fw +93d4314a371a61731fa91e9c762a4cd7f94e0fc78973c852d2f69652258f3b2a IO_MODULE_FM-31-1-2-1.1.8-2006.fw +c0ff359b43a09dbf621bba411cc2fd003dde16ef0baf6793c27900d69309e5b3 IO_MODULE_FM-31-1-2-1.1.9-2125.fw +585b9e4f065d182755c4582fd84d41c9d22b28fccf28a19f12be76d4fb0b6c52 IO_MODULE_FM-31-1-2-2.0.0-2325.fw + +08c8d241e0be800fd5f5af497461ad1adfc1ddea864c7b5fabcfa54647a0a769 LED_RGBW_DIN-24-1-2-1.4.4-1920.fw +fdc3fdf3c48945c7c8f73ce23a8708d4355374e8da988aa7600a5060122e62e0 LED_RGBW_DIN-24-1-2-1.4.6-1949A.fw +7e00f31be102848fb627eea3a3a1ac4669966e3d369ab5503fc7ab66453c03c8 LED_RGBW_DIN-24-1-2-1.4.7-2125.fw +e97668700e59e38dd6ca83b0662d5111c1ca459a3156da4d43dc7cfcf08465fb LED_RGBW_DIN-24-1-2-1.4.8-2316.fw +b257671bef69850d4ea7f2278d9de2be2c8463502455b85862ee9cff8a5780b1 LED_RGBW_FM-29-1-2-1.1.6-2040.fw + +7dc2178b115255e6be0f0cfffb8e0c692f23e67cecd24f66dde8ad12b95ce4ed MSENSOR_IR-45-2-2-1.2.6-2148.fw + +0dbf4c44327373170e471f848ad9be0129c501d4ac2cd6737c96063c746e9c99 RELAY_DIN_2-22-1-2-1.3.12-2006.fw +f78b6d92cbaafc3ea0421b81b25e5ef7fef7cbadfa876699da530d8a72260e67 RELAY_DIN_2-22-1-2-1.3.13-2125.fw +d7211b4bfae3085806c94a90a8b87e239bbf06c031ffc273a1f67b7eb32a5bff RELAY_DIN_2-22-1-2-1.3.7-1924.fw +7a4961d5efb4a620e290afdb9114c393f09bacac92bfddd8117be523c1cd888c RELAY_DIN_2-22-1-2-2.0.0-2325.fw +490267603dd4489b10f00503584a9f97c4fc8e68b218ddf61ebaf54f5045f9fc RELAY_DIN_4-21-1-2-1.3.12-2006.fw +1f2569ce0da0be7575b21884ae1197bea2ba366251017c2b74066b35e473bf03 RELAY_DIN_4-21-1-2-1.3.13-2125.fw +eaf8b7c390ec6a171019671c0824d1e2043d8600df554842dc076a9b443ab71e RELAY_DIN_4-21-1-2-1.3.7-1924.fw +4f0dc17ce1d91708cc59b6e8d98f79c0218e74a0145d8005a8f221011c29396d RELAY_DIN_4-21-1-2-2.0.0-2325.fw + +a8a88b8f0f53440fd641af62513cb0d19d30f93e7284c092b0756ad189e8c891 ROLLER_SH_DIN-23-1-2-1.1.11-2006.fw +e2c59c020cc86b8a98a1f498592edd6a0075315ea5bbcce32cd14c12a8089e84 ROLLER_SH_DIN-23-1-2-1.1.6-1922.fw +c7c436b67c54bf6a325345c52f097595d1fdd804841456dc37f39d86d0c9272a ROLLER_SH_DIN-23-1-2-2.1.2-2114.fw +7f6f4164ece295b86f8971cf92e6c52336fbc44efbd356b23fe83e9f34c9649d ROLLER_SH_DIN-23-1-2-2.1.3-2125.fw +00992ca99e97dd930e69fb3facfc56045c14e8db312dc82c2d3f0c33840573c7 ROLLER_SH_DIN-23-1-2-3.1.2-2151.fw +d57244ebdfecf33d7d0d5caed3d9339f025ef895083c17d5c50d290d387ea174 ROLLER_SH_DIN-23-1-2-3.1.3-2225A.fw +895c32273bf8f73d620ef4f40061470ae81d85f98cca3aab1ee1091d7e3bbcb4 ROLLER_SH_DIN-23-1-2-3.2.1-2228.fw + +4e057f91370a5ad1715d7b6081d652e91df3bf93769f57e4a154737b4e57126a ROLLER_SH_DIN_1-23-1-2-3.2.4-2337.fw + +529fcbea9c370e5cb68f69f83ac2c41b34c629db03bfc6676d093daa1858d850 ROLLER_SH_DIN_3-42-1-2-1.1.13-2026.fw +4c789bc43e34159c44ea19a41e4b571ca0751320688a420cd03656cc9b0fa6d5 ROLLER_SH_DIN_3-42-1-2-2.1.3-2127A.fw +17614d28a1e600096b5c18fad6bdf16c4a1262c87f40f3d3282b2e40325b0410 ROLLER_SH_DIN_3-42-1-2-3.2.1-2228.fw +77181c76e5d1ae713f20eba91fe40d964b64537c1489267b9ff62bda50c07a07 ROLLER_SH_DIN_3-42-1-2-3.2.2-2333.fw +c06b8ba93221095ed35d61fd3e7345a00bd4882daf70ae5174dda871f8ffef1a ROLLER_SH_DIN_3-42-1-2-3.2.4-2337.fw + +cc9cadd0b99e5716a2b2a9a181712fda8335a7926eaf67c11f6731fec1f32efe ROLLER_SH_FM-32-1-2-1.0.7-2008.fw +d7748df4337aa7ad9cbbfbb65ab0be69239d38ebe7a6b580e19bf9ca383760ee ROLLER_SH_FM-32-1-2-2.1.2-2114.fw +09ac67629829283943b382848c51b07e21364df2bbcec8d8ac8a690d3e641870 ROLLER_SH_FM-32-1-2-2.1.3-2125.fw +52911b9de7de9d7a3acccbe53e23c6209dc4f2e91afb70488dc6e7f7f05ca91e ROLLER_SH_FM-32-1-2-3.2.1-2228.fw +13b6cca191038dbe485f4ab1ce71a34cd99e08a625ea99b328257e77a4adcbad ROLLER_SH_FM-32-1-2-3.2.4-2341.fw + +288e64a41037d5e646cf2fc9246afc4eee6cf710bdcf8b31b1f7584932832217 TOUCH_PANEL_FM_4-28-1-2-1.1.5-2006.fw +a4d9a458cd9e98ed93c5a7240489ad46546aa7c7cee94871e9f51f6721f75f7a TOUCH_PANEL_FM_4-28-1-2-1.1.6-2103.fw +7dc269ef8d7924fa1149370967ae6896e145c0f9633571c66494da58e2fd05a5 TOUCH_PANEL_FM_4-28-2-2-1.2.7-2228.fw +7875c7218f6b3e344e4b94c6a48e8b2100703893811271e65e9914fe88ea3f1f TOUCH_PANEL_FM_4-28-3-2-1.3.5-2244.fw + +c277f81e5d08ea73d7fd65822140e1602bab42950a7eb133a680cacb939acb37 TOUCH_PANEL_FM_8-27-1-2-1.1.3-2006.fw +3a089ef16aa1890d59d5cc5f40c37ad48c91d8c74b5c9581dbed095661372064 TOUCH_PANEL_FM_8-27-1-2-1.1.4-2102.fw +c519d552f6c37bf644e953a02fec32161c24001f86b9a7db11ff49623f71ad2a TOUCH_PANEL_FM_8-27-2-2-1.2.4-2217.fw +f1dfee76fee4c5956aa9362803b2661aacc8ef9199c7be3357d9c5bddcb7cf93 TOUCH_PANEL_FM_8-27-2-2-1.2.7-2228.fw +2700869ed6eea04d090bbc24140fe183a30b9c80f78668c88e26a846438c7d9c TOUCH_PANEL_FM_8-27-3-2-1.3.6-2245.fw diff --git a/docs/LICENSE.md b/docs/LICENSE.md new file mode 100644 index 0000000..81a8199 --- /dev/null +++ b/docs/LICENSE.md @@ -0,0 +1,430 @@ +This work is licensed under CC BY-SA 4.0. +To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/4.0/ + +Attribution-ShareAlike 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-ShareAlike 4.0 International Public +License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-ShareAlike 4.0 International Public License ("Public +License"). To the extent this Public License may be interpreted as a +contract, You are granted the Licensed Rights in consideration of Your +acceptance of these terms and conditions, and the Licensor grants You +such rights in consideration of benefits the Licensor receives from +making the Licensed Material available under these terms and +conditions. + + +Section 1 -- Definitions. + +a. Adapted Material means material subject to Copyright and Similar +Rights that is derived from or based upon the Licensed Material +and in which the Licensed Material is translated, altered, +arranged, transformed, or otherwise modified in a manner requiring +permission under the Copyright and Similar Rights held by the +Licensor. For purposes of this Public License, where the Licensed +Material is a musical work, performance, or sound recording, +Adapted Material is always produced where the Licensed Material is +synched in timed relation with a moving image. + +b. Adapter's License means the license You apply to Your Copyright +and Similar Rights in Your contributions to Adapted Material in +accordance with the terms and conditions of this Public License. + +c. BY-SA Compatible License means a license listed at +creativecommons.org/compatiblelicenses, approved by Creative +Commons as essentially the equivalent of this Public License. + +d. Copyright and Similar Rights means copyright and/or similar rights +closely related to copyright including, without limitation, +performance, broadcast, sound recording, and Sui Generis Database +Rights, without regard to how the rights are labeled or +categorized. For purposes of this Public License, the rights +specified in Section 2(b)(1)-(2) are not Copyright and Similar +Rights. + +e. Effective Technological Measures means those measures that, in the +absence of proper authority, may not be circumvented under laws +fulfilling obligations under Article 11 of the WIPO Copyright +Treaty adopted on December 20, 1996, and/or similar international +agreements. + +f. Exceptions and Limitations means fair use, fair dealing, and/or +any other exception or limitation to Copyright and Similar Rights +that applies to Your use of the Licensed Material. + +g. License Elements means the license attributes listed in the name +of a Creative Commons Public License. The License Elements of this +Public License are Attribution and ShareAlike. + +h. Licensed Material means the artistic or literary work, database, +or other material to which the Licensor applied this Public +License. + +i. Licensed Rights means the rights granted to You subject to the +terms and conditions of this Public License, which are limited to +all Copyright and Similar Rights that apply to Your use of the +Licensed Material and that the Licensor has authority to license. + +j. Licensor means the individual(s) or entity(ies) granting rights +under this Public License. + +k. Share means to provide material to the public by any means or +process that requires permission under the Licensed Rights, such +as reproduction, public display, public performance, distribution, +dissemination, communication, or importation, and to make material +available to the public including in ways that members of the +public may access the material from a place and at a time +individually chosen by them. + +l. Sui Generis Database Rights means rights other than copyright +resulting from Directive 96/9/EC of the European Parliament and of +the Council of 11 March 1996 on the legal protection of databases, +as amended and/or succeeded, as well as other essentially +equivalent rights anywhere in the world. + +m. You means the individual or entity exercising the Licensed Rights +under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + +a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. Additional offer from the Licensor -- Adapted Material. + Every recipient of Adapted Material from You + automatically receives an offer from the Licensor to + exercise the Licensed Rights in the Adapted Material + under the conditions of the Adapter's License You apply. + + c. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + +b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + +a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + +b. ShareAlike. + + In addition to the conditions in Section 3(a), if You Share + Adapted Material You produce, the following conditions also apply. + + 1. The Adapter's License You apply must be a Creative Commons + license with the same License Elements, this version or + later, or a BY-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the + Adapter's License You apply. You may satisfy this condition + in any reasonable manner based on the medium, means, and + context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms + or conditions on, or apply any Effective Technological + Measures to, Adapted Material that restrict exercise of the + rights granted under the Adapter's License You apply. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + +a. for the avoidance of doubt, Section 2(a)(1) grants You the right +to extract, reuse, reproduce, and Share all or a substantial +portion of the contents of the database; + +b. if You include all or a substantial portion of the database +contents in a database in which You have Sui Generis Database +Rights, then the database in which You have Sui Generis Database +Rights (but not its individual contents) is Adapted Material, +including for purposes of Section 3(b); and + +c. You must comply with the conditions in Section 3(a) if You Share +all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + +a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE +EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS +AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF +ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, +IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, +WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, +ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT +KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT +ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + +b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE +TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, +NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, +INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, +COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR +USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN +ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR +DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR +IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + +c. The disclaimer of warranties and limitation of liability provided +above shall be interpreted in a manner that, to the extent +possible, most closely approximates an absolute disclaimer and +waiver of all liability. + + +Section 6 -- Term and Termination. + +a. This Public License applies for the term of the Copyright and +Similar Rights licensed here. However, if You fail to comply with +this Public License, then Your rights under this Public License +terminate automatically. + +b. Where Your right to use the Licensed Material has terminated under +Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + +c. For the avoidance of doubt, the Licensor may also offer the +Licensed Material under separate terms or conditions or stop +distributing the Licensed Material at any time; however, doing so +will not terminate this Public License. + +d. Sections 1, 5, 6, 7, and 8 survive termination of this Public +License. + + +Section 7 -- Other Terms and Conditions. + +a. The Licensor shall not be bound by any additional or different +terms or conditions communicated by You unless expressly agreed. + +b. Any arrangements, understandings, or agreements regarding the +Licensed Material not stated herein are separate from and +independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + +a. For the avoidance of doubt, this Public License does not, and +shall not be interpreted to, reduce, limit, restrict, or impose +conditions on any use of the Licensed Material that could lawfully +be made without permission under this Public License. + +b. To the extent possible, if any provision of this Public License is +deemed unenforceable, it shall be automatically reformed to the +minimum extent necessary to make it enforceable. If the provision +cannot be reformed, it shall be severed from this Public License +without affecting the enforceability of the remaining terms and +conditions. + +c. No term or condition of this Public License will be waived and no +failure to comply consented to unless expressly agreed to by the +Licensor. + +d. Nothing in this Public License constitutes or may be interpreted +as a limitation upon, or waiver of, any privileges and immunities +that apply to the Licensor or You, including from the legal +processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/docs/PORTS.md b/docs/PORTS.md new file mode 100644 index 0000000..3a4e54e --- /dev/null +++ b/docs/PORTS.md @@ -0,0 +1,26 @@ +# 1234/udp +Main command port used for communication of Object Manager with the Devices and between the devices + +# 2001/tcp +TBD + +# 4343/tcp +TBD + +# 4344/udp +Port used for clientRegister subscription function responses + +# 2345 +Maybe used for communication with Mobile devices (listening) + +# 5678 +Maybe used for communication with Mobile devices + +# 69/udp +Used for file transfer between the Object Manager and the Devices. TFTP. + +# 23/tcp +Telnet for CLU diagnostic log preview + +# 24/tcp +Telnet shell, password protected \ No newline at end of file diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..0b7a8a6 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,12 @@ +An effort to analyze and validate modules made by Grenton, before installing them into my own house. + +My main objective is to understand how the whole system works and to be able to extend and service it even without commercial support. + +# Current Objectives +1. Check Hardware +1. Understand Communication Protocols + 1. Ethernet + 1. OM <-> CLU + 1. CLU <-> CLU + 1. TF-Bus +1. Understand LUA API diff --git a/docs/img/vclu.png b/docs/img/vclu.png new file mode 100644 index 0000000..3a64cc2 Binary files /dev/null and b/docs/img/vclu.png differ diff --git a/docs/modules/bus/README.md b/docs/modules/bus/README.md new file mode 100644 index 0000000..d5b5291 --- /dev/null +++ b/docs/modules/bus/README.md @@ -0,0 +1,9 @@ +# Bus Module Hardware + +The module actually consists only of a protection diode, capacitor and connectors... + +# Datasheets +[0923150432.pdf](datasheets%2F0923150432.pdf) +[0923151006.pdf](datasheets%2F0923151006.pdf) +[mx90325.pdf](datasheets%2Fmx90325.pdf) +[smcj26a.pdf](datasheets%2Fsmcj26a.pdf) \ No newline at end of file diff --git a/docs/modules/bus/datasheets/0923150432.pdf b/docs/modules/bus/datasheets/0923150432.pdf new file mode 100644 index 0000000..facd709 Binary files /dev/null and b/docs/modules/bus/datasheets/0923150432.pdf differ diff --git a/docs/modules/bus/datasheets/0923151006.pdf b/docs/modules/bus/datasheets/0923151006.pdf new file mode 100644 index 0000000..51829f2 Binary files /dev/null and b/docs/modules/bus/datasheets/0923151006.pdf differ diff --git a/docs/modules/bus/datasheets/mx90325.pdf b/docs/modules/bus/datasheets/mx90325.pdf new file mode 100644 index 0000000..b71d924 Binary files /dev/null and b/docs/modules/bus/datasheets/mx90325.pdf differ diff --git a/docs/modules/bus/datasheets/smcj26a.pdf b/docs/modules/bus/datasheets/smcj26a.pdf new file mode 100644 index 0000000..98a59ff Binary files /dev/null and b/docs/modules/bus/datasheets/smcj26a.pdf differ diff --git a/docs/modules/gates/README.md b/docs/modules/gates/README.md new file mode 100644 index 0000000..0e18e83 --- /dev/null +++ b/docs/modules/gates/README.md @@ -0,0 +1,39 @@ +# Gate Hardware + +I currently only own MODBUS and HTTP gates, but I assume all should be true for the ALARM gate as well. + +The module is divided into two PCB's, the bottom ones are marked: `CLU_Gate_Bottom_v15` and contains connectors, voltage regulator and protection circuits. + +The top PCB is marked as `CLU_GATE_Main_v14` and it contains an ESP32-WROVER-B module, modbus transceiver, ethernet transceiver, ethernet connector and a green LED. +In both cases MODBUS and HTTP gates are completely identical hardware wise. +To the point that even the HTTP gate also has ST3485EB RS-485 MODBUS transceiver. So technically each of them could work as any gate type (even at the same time) with only software change (maybe even at the same time!). + +Even software updates are identical for each of the gates. Capabilities are limited somehow using eFuses or using memory that is not updated during normal firmware update (it might be write protected). +I tried using HTTP features on the MODBUS gate, but it was throwing LUA errors, so there needs to be some kind of software lock on the features. + +SHA256 sums of firmware updates for the modules in the same version: + +``` +834eb9e88ad4e2ffb5bbd93fe4fa66e5858d082b35eaa9c83bbe8dd2b2c4b751 CLU_GATE_ALARM-18-2-2-1.1.10-2140.fw +834eb9e88ad4e2ffb5bbd93fe4fa66e5858d082b35eaa9c83bbe8dd2b2c4b751 CLU_GATE_HTTP-18-2-3-1.1.10-2140.fw +834eb9e88ad4e2ffb5bbd93fe4fa66e5858d082b35eaa9c83bbe8dd2b2c4b751 CLU_GATE_MODBUS-18-2-1-1.1.10-2140.fw +``` + +# Debug Port + +The gate has exposed pins for what seems like a 2x5 pin debug port. + +# Datasheets +[8720a.pdf](datasheets%2F8720a.pdf) +[esp32-wrover-b_datasheet_en.pdf](datasheets%2Fesp32-wrover-b_datasheet_en.pdf) +[st3485eb.pdf](datasheets%2Fst3485eb.pdf) + +# Interfaces +[clu_GATE_HTTP_ft00000003_fv00000456_ht00000012_hv00000002.xml](http%2Finterfaces%2Fclu_GATE_HTTP_ft00000003_fv00000456_ht00000012_hv00000002.xml) +[object_gate_timer_v2.xml](http%2Finterfaces%2Fobject_gate_timer_v2.xml) +[object_http_listener_v1.xml](http%2Finterfaces%2Fobject_http_listener_v1.xml) +[object_http_request_v1.xml](http%2Finterfaces%2Fobject_http_request_v1.xml) + +[clu_GATE_MODBUS_ft00000001_fv00000456_ht00000012_hv00000002.xml](modbus%2Finterfaces%2Fclu_GATE_MODBUS_ft00000001_fv00000456_ht00000012_hv00000002.xml) +[object_modbus_v2.xml](modbus%2Finterfaces%2Fobject_modbus_v2.xml) +[object_modbus_val_v1.xml](modbus%2Finterfaces%2Fobject_modbus_val_v1.xml) \ No newline at end of file diff --git a/docs/modules/gates/datasheets/8720a.pdf b/docs/modules/gates/datasheets/8720a.pdf new file mode 100644 index 0000000..97f652c Binary files /dev/null and b/docs/modules/gates/datasheets/8720a.pdf differ diff --git a/docs/modules/gates/datasheets/esp32-wrover-b_datasheet_en.pdf b/docs/modules/gates/datasheets/esp32-wrover-b_datasheet_en.pdf new file mode 100644 index 0000000..3c874db Binary files /dev/null and b/docs/modules/gates/datasheets/esp32-wrover-b_datasheet_en.pdf differ diff --git a/docs/modules/gates/datasheets/st3485eb.pdf b/docs/modules/gates/datasheets/st3485eb.pdf new file mode 100644 index 0000000..498a8f3 Binary files /dev/null and b/docs/modules/gates/datasheets/st3485eb.pdf differ diff --git a/docs/modules/gates/http/files/a/CLOUD-PRIVATE.PEM b/docs/modules/gates/http/files/a/CLOUD-PRIVATE.PEM new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/gates/http/files/a/CLOUD-PUBLIC.CRT b/docs/modules/gates/http/files/a/CLOUD-PUBLIC.CRT new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/gates/http/files/a/CLOUD-PUBLIC.CSR b/docs/modules/gates/http/files/a/CLOUD-PUBLIC.CSR new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/gates/http/files/a/CLOUD-ROOT.PEM b/docs/modules/gates/http/files/a/CLOUD-ROOT.PEM new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/gates/http/files/a/CONFIG.JSON b/docs/modules/gates/http/files/a/CONFIG.JSON new file mode 100644 index 0000000..5912aa5 --- /dev/null +++ b/docs/modules/gates/http/files/a/CONFIG.JSON @@ -0,0 +1,11 @@ +{ + "sn": 52XXXXXXX, + "mac": "1c:9d:XX:XX:XX:XX", + "hwType": 18, + "hwVer": 2, + "fwType": 3, + "fwApiVer": 1110, + "fwVer": "1.1.10-2140", + "tfbusDevices": [], + "zwaveDevices": [] +} \ No newline at end of file diff --git a/docs/modules/gates/http/files/a/MAIN.LUA b/docs/modules/gates/http/files/a/MAIN.LUA new file mode 100644 index 0000000..1251485 --- /dev/null +++ b/docs/modules/gates/http/files/a/MAIN.LUA @@ -0,0 +1,15 @@ + +collectgarbage("collect") +require "user" + +collectgarbage("collect") +require "om" +collectgarbage("collect") + + +function checkAlive() + print("true") +end + +SYSTEM.Init() + diff --git a/docs/modules/gates/http/files/a/OM.LUA b/docs/modules/gates/http/files/a/OM.LUA new file mode 100644 index 0000000..9c89cd0 --- /dev/null +++ b/docs/modules/gates/http/files/a/OM.LUA @@ -0,0 +1,41 @@ +-- FwType 00000003 +-- FwVersion 00000456 +-- HwType 00000012 +-- HwVersion 00000002 + +CLU52XXXXXXX = GATE:new(5000, 0xA489004, 0xFFFF0000, 0xA484801, "", "") +-- NAME_CLU CLUHTTP=CLU50XXXXXXX + +CLU2XXXXXXXX = OBJECT:new(1, 0xA489001, "CLU2XXXXXXXX") +CLU50XXXXXXX = OBJECT:new(1, 0xA489008, "CLU50XXXXXXX") + + +-- MODULES + +-- IO_MODULES + + +function setVar(name, value) + _G[name] = value +end + +function getVar(name) + return _G[name] +end + + + +function OnInit() + +-- INIT_CLU_OBJECTS +CLU50XXXXXXX:set(1, 1000) +CLU50XXXXXXX:set(14, 0) +CLU50XXXXXXX:set(18, 0) +CLU50XXXXXXX:set(20, 5000) +CLU50XXXXXXX:set(21, 1) +CLU50XXXXXXX:set(2, "8.8.8.8") +CLU50XXXXXXX:set(3, "8.8.4.4") + +end + +CLU50XXXXXXX:add_event(0, OnInit) diff --git a/docs/modules/gates/http/files/a/USER.LUA b/docs/modules/gates/http/files/a/USER.LUA new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/gates/http/files/a/config.txt b/docs/modules/gates/http/files/a/config.txt new file mode 100644 index 0000000..5067893 --- /dev/null +++ b/docs/modules/gates/http/files/a/config.txt @@ -0,0 +1,7 @@ +00000001 +1fXXXXXX +1c:9d:XX:XX:XX:XX +00000003 +00000456 +00000012 +00000002 diff --git a/docs/modules/gates/http/files/a/settings.usr b/docs/modules/gates/http/files/a/settings.usr new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/gates/http/files/m/image.fw b/docs/modules/gates/http/files/m/image.fw new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/gates/http/interfaces/clu_GATE_HTTP_ft00000003_fv00000456_ht00000012_hv00000002.xml b/docs/modules/gates/http/interfaces/clu_GATE_HTTP_ft00000003_fv00000456_ht00000012_hv00000002.xml new file mode 100644 index 0000000..df2173e --- /dev/null +++ b/docs/modules/gates/http/interfaces/clu_GATE_HTTP_ft00000003_fv00000456_ht00000012_hv00000002.xml @@ -0,0 +1,200 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/modules/gates/http/interfaces/object_gate_timer_v2.xml b/docs/modules/gates/http/interfaces/object_gate_timer_v2.xml new file mode 100644 index 0000000..bbaed06 --- /dev/null +++ b/docs/modules/gates/http/interfaces/object_gate_timer_v2.xml @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/modules/gates/http/interfaces/object_http_listener_v1.xml b/docs/modules/gates/http/interfaces/object_http_listener_v1.xml new file mode 100644 index 0000000..e0dbb27 --- /dev/null +++ b/docs/modules/gates/http/interfaces/object_http_listener_v1.xml @@ -0,0 +1,145 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/modules/gates/http/interfaces/object_http_request_v1.xml b/docs/modules/gates/http/interfaces/object_http_request_v1.xml new file mode 100644 index 0000000..c4f6269 --- /dev/null +++ b/docs/modules/gates/http/interfaces/object_http_request_v1.xml @@ -0,0 +1,197 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/modules/gates/modbus/files/a/CLOUD-PRIVATE.PEM b/docs/modules/gates/modbus/files/a/CLOUD-PRIVATE.PEM new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/gates/modbus/files/a/CLOUD-PUBLIC.CRT b/docs/modules/gates/modbus/files/a/CLOUD-PUBLIC.CRT new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/gates/modbus/files/a/CLOUD-PUBLIC.CSR b/docs/modules/gates/modbus/files/a/CLOUD-PUBLIC.CSR new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/gates/modbus/files/a/CLOUD-ROOT.PEM b/docs/modules/gates/modbus/files/a/CLOUD-ROOT.PEM new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/gates/modbus/files/a/CONFIG.JSON b/docs/modules/gates/modbus/files/a/CONFIG.JSON new file mode 100644 index 0000000..1346633 --- /dev/null +++ b/docs/modules/gates/modbus/files/a/CONFIG.JSON @@ -0,0 +1,11 @@ +{ + "sn": 50XXXXXXX, + "mac": "1c:9d:XX:XX:XX:XX", + "hwType": 18, + "hwVer": 2, + "fwType": 1, + "fwApiVer": 1110, + "fwVer": "1.1.10-2140", + "tfbusDevices": [], + "zwaveDevices": [] +} \ No newline at end of file diff --git a/docs/modules/gates/modbus/files/a/MAIN.LUA b/docs/modules/gates/modbus/files/a/MAIN.LUA new file mode 100644 index 0000000..1251485 --- /dev/null +++ b/docs/modules/gates/modbus/files/a/MAIN.LUA @@ -0,0 +1,15 @@ + +collectgarbage("collect") +require "user" + +collectgarbage("collect") +require "om" +collectgarbage("collect") + + +function checkAlive() + print("true") +end + +SYSTEM.Init() + diff --git a/docs/modules/gates/modbus/files/a/OM.LUA b/docs/modules/gates/modbus/files/a/OM.LUA new file mode 100644 index 0000000..d1de406 --- /dev/null +++ b/docs/modules/gates/modbus/files/a/OM.LUA @@ -0,0 +1,41 @@ +-- FwType 00000001 +-- FwVersion 00000456 +-- HwType 00000012 +-- HwVersion 00000002 + +CLU50XXXXXXX = GATE:new(5000, 0xA489008, 0xFFFF0000, 0xA484801, "", "") +-- NAME_CLU CLUMODBUS=CLU50XXXXXXX + +CLU22XXXXXXX = OBJECT:new(1, 0xA489001, "CLU22XXXXXXX") +CLU52XXXXXXX = OBJECT:new(1, 0xA489004, "CLU52XXXXXXX") + + +-- MODULES + +-- IO_MODULES + + +function setVar(name, value) + _G[name] = value +end + +function getVar(name) + return _G[name] +end + + + +function OnInit() + +-- INIT_CLU_OBJECTS +CLU50XXXXXXX:set(1, 1000) +CLU50XXXXXXX:set(14, 0) +CLU50XXXXXXX:set(18, 0) +CLU50XXXXXXX:set(20, 5000) +CLU50XXXXXXX:set(21, 1) +CLU50XXXXXXX:set(2, "8.8.8.8") +CLU50XXXXXXX:set(3, "8.8.4.4") + +end + +CLU50XXXXXXX:add_event(0, OnInit) diff --git a/docs/modules/gates/modbus/files/a/USER.LUA b/docs/modules/gates/modbus/files/a/USER.LUA new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/gates/modbus/files/a/config.txt b/docs/modules/gates/modbus/files/a/config.txt new file mode 100644 index 0000000..ea0eff8 --- /dev/null +++ b/docs/modules/gates/modbus/files/a/config.txt @@ -0,0 +1,7 @@ +00000001 +1dXXXXXX +1c:9d:XX:XX:XX:XX +00000001 +00000456 +00000012 +00000002 diff --git a/docs/modules/gates/modbus/files/a/settings.usr b/docs/modules/gates/modbus/files/a/settings.usr new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/gates/modbus/files/m/image.fw b/docs/modules/gates/modbus/files/m/image.fw new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/gates/modbus/interfaces/clu_GATE_MODBUS_ft00000001_fv00000456_ht00000012_hv00000002.xml b/docs/modules/gates/modbus/interfaces/clu_GATE_MODBUS_ft00000001_fv00000456_ht00000012_hv00000002.xml new file mode 100644 index 0000000..2886c33 --- /dev/null +++ b/docs/modules/gates/modbus/interfaces/clu_GATE_MODBUS_ft00000001_fv00000456_ht00000012_hv00000002.xml @@ -0,0 +1,199 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/modules/gates/modbus/interfaces/object_modbus_v2.xml b/docs/modules/gates/modbus/interfaces/object_modbus_v2.xml new file mode 100644 index 0000000..35b8033 --- /dev/null +++ b/docs/modules/gates/modbus/interfaces/object_modbus_v2.xml @@ -0,0 +1,300 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/modules/gates/modbus/interfaces/object_modbus_val_v1.xml b/docs/modules/gates/modbus/interfaces/object_modbus_val_v1.xml new file mode 100644 index 0000000..6c4953d --- /dev/null +++ b/docs/modules/gates/modbus/interfaces/object_modbus_val_v1.xml @@ -0,0 +1,430 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/modules/zwave2/README.md b/docs/modules/zwave2/README.md new file mode 100644 index 0000000..4e8c635 --- /dev/null +++ b/docs/modules/zwave2/README.md @@ -0,0 +1,34 @@ +# Service Port + +The CLU has an exposed 3 pin (2.54mm) header that contains ground and UART pins. + +When the CLU is facing forward the pinouts are as follows (GND is the closest to the Grenton logo): GND, TX, RX (?) + +The UART voltage level is 3V3. + +Here are the logs from CLU bootup sequence: +[logs/bootloader.log](logs/bootloader.log) + +# Images +![clu_zwave2_base.JPG](img%2Fclu_zwave2_base.JPG) + +![clu_zwave2_mcu.JPG](img%2Fclu_zwave2_mcu.JPG) + +# Logs +[boot.log](logs%2Fboot.log) +[firmware.log](logs%2Ffirmware.log) +[telnet_port_24.log](logs%2Ftelnet_port_24.log) + +# Datasheets + +# Interfaces +[clu_ZWAVE_2_ft00000003_fv200_ht00000013_hv00000001.xml](interfaces%2Fclu_ZWAVE_2_ft00000003_fv200_ht00000013_hv00000001.xml) +[object_calendar_v1.xml](interfaces%2Fobject_calendar_v1.xml) +[object_event_scheduler_v1.xml](interfaces%2Fobject_event_scheduler_v1.xml) +[object_PIDcontroller_v1.xml](interfaces%2Fobject_PIDcontroller_v1.xml) +[object_presence_sensor_v2.xml](interfaces%2Fobject_presence_sensor_v2.xml) +[object_push_v1.xml](interfaces%2Fobject_push_v1.xml) +[object_scheduler_v1.xml](interfaces%2Fobject_scheduler_v1.xml) +[object_sunrise_sunset_calendar_v3.xml](interfaces%2Fobject_sunrise_sunset_calendar_v3.xml) +[object_thermostat_v2.xml](interfaces%2Fobject_thermostat_v2.xml) +[object_timer_v1.xml](interfaces%2Fobject_timer_v1.xml) \ No newline at end of file diff --git a/docs/modules/zwave2/files/a/CLOUD-PRIVATE.PEM b/docs/modules/zwave2/files/a/CLOUD-PRIVATE.PEM new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/zwave2/files/a/CLOUD-PUBLIC.CRT b/docs/modules/zwave2/files/a/CLOUD-PUBLIC.CRT new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/zwave2/files/a/CLOUD-PUBLIC.CSR b/docs/modules/zwave2/files/a/CLOUD-PUBLIC.CSR new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/zwave2/files/a/CLOUD-ROOT.PEM b/docs/modules/zwave2/files/a/CLOUD-ROOT.PEM new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/zwave2/files/a/CONFIG.JSON b/docs/modules/zwave2/files/a/CONFIG.JSON new file mode 100644 index 0000000..943e238 --- /dev/null +++ b/docs/modules/zwave2/files/a/CONFIG.JSON @@ -0,0 +1,12 @@ +{ + "sn": 22XXXXXXX, + "mac": "80:34:XX:XX:XX:XX", + "hwType": 19, + "hwVer": 1, + "fwType": 3, + "fwApiVer": 512, + "fwVer": "5.12.1-2330", + "status": "OK", + "tfbusDevices": [], + "zwaveDevices": [] +} \ No newline at end of file diff --git a/docs/modules/zwave2/files/a/EMERGNCY.LUA b/docs/modules/zwave2/files/a/EMERGNCY.LUA new file mode 100644 index 0000000..ca69ff8 --- /dev/null +++ b/docs/modules/zwave2/files/a/EMERGNCY.LUA @@ -0,0 +1,8 @@ +SYSTEM.Init() +function checkAlive() + return "emergency" +end + +repeat + SYSTEM.Loop() +until 1==2 diff --git a/docs/modules/zwave2/files/a/MAIN.LUA b/docs/modules/zwave2/files/a/MAIN.LUA new file mode 100644 index 0000000..2d22b9d --- /dev/null +++ b/docs/modules/zwave2/files/a/MAIN.LUA @@ -0,0 +1,20 @@ + +collectgarbage("collect") +require "user" + +collectgarbage("collect") +require "om" +collectgarbage("collect") + + +function checkAlive() + return "0dxxxxxx" +end + +SYSTEM.Init() + + +repeat + SYSTEM.Loop() +until 1==2 + diff --git a/docs/modules/zwave2/files/a/OM.LUA b/docs/modules/zwave2/files/a/OM.LUA new file mode 100644 index 0000000..5834223 --- /dev/null +++ b/docs/modules/zwave2/files/a/OM.LUA @@ -0,0 +1,48 @@ +-- FwType 00000003 +-- FwVersion 00000200 +-- HwType 00000013 +-- HwVersion 00000001 + +--STORAGE +STO99999 = OBJECT:new(44, "STO99999") + +CLU22XXXXXXX = OBJECT:new(0, 0xA489002, "CLU22XXXXXXX") +-- NAME_CLU CLU22XXXXXXX=CLU22XXXXXXX + +CLU52XXXXXXX = OBJECT:new(1, 0xA489004, "CLU52XXXXXXX") +CLU50XXXXXXX = OBJECT:new(1, 0xA489008, "CLU50XXXXXXX") + + +-- MODULES + +-- IO_MODULES + + +function setVar(name, value) + _G[name] = value +end + +function getVar(name) + return _G[name] +end + + + +function OnInit() + +-- INIT_CLU_OBJECTS +CLU22XXXXXXX:set(18, 0) +CLU22XXXXXXX:set(20, 50) +CLU22XXXXXXX:set(21, 230) +CLU22XXXXXXX:set(22, "tempus1.gum.gov.pl") +CLU22XXXXXXX:set(23, 0) +CLU22XXXXXXX:set(25, "8.8.8.8") +CLU22XXXXXXX:set(26, "8.8.4.4") +CLU22XXXXXXX:set(28, 0.5) +CLU22XXXXXXX:set(29, 25) +CLU22XXXXXXX:set(30, 23) +CLU22XXXXXXX:set(31, 0) + +end + +CLU22XXXXXXX:add_event(0, OnInit) diff --git a/docs/modules/zwave2/files/a/TEST b/docs/modules/zwave2/files/a/TEST new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/zwave2/files/a/USER.LUA b/docs/modules/zwave2/files/a/USER.LUA new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/zwave2/files/a/config.txt b/docs/modules/zwave2/files/a/config.txt new file mode 100644 index 0000000..8d33f31 --- /dev/null +++ b/docs/modules/zwave2/files/a/config.txt @@ -0,0 +1,7 @@ +00000000 +0dxxxxxx +80:34:XX:XX:XX:XX +00000003 +00000200 +00000013 +00000001 diff --git a/docs/modules/zwave2/files/a/settings.usr b/docs/modules/zwave2/files/a/settings.usr new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/zwave2/files/m/DIAGNOSTIC_PACK.JSON b/docs/modules/zwave2/files/m/DIAGNOSTIC_PACK.JSON new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/zwave2/files/m/debug.bin b/docs/modules/zwave2/files/m/debug.bin new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/zwave2/files/m/image.fw b/docs/modules/zwave2/files/m/image.fw new file mode 100644 index 0000000..e69de29 diff --git a/docs/modules/zwave2/files/p/meas.bin b/docs/modules/zwave2/files/p/meas.bin new file mode 100644 index 0000000..1936c7b Binary files /dev/null and b/docs/modules/zwave2/files/p/meas.bin differ diff --git a/docs/modules/zwave2/img/clu_zwave2_base.JPG b/docs/modules/zwave2/img/clu_zwave2_base.JPG new file mode 100755 index 0000000..6f60efa Binary files /dev/null and b/docs/modules/zwave2/img/clu_zwave2_base.JPG differ diff --git a/docs/modules/zwave2/img/clu_zwave2_mcu.JPG b/docs/modules/zwave2/img/clu_zwave2_mcu.JPG new file mode 100755 index 0000000..4b4b7c8 Binary files /dev/null and b/docs/modules/zwave2/img/clu_zwave2_mcu.JPG differ diff --git a/docs/modules/zwave2/interfaces/clu_ZWAVE_2_ft00000003_fv200_ht00000013_hv00000001.xml b/docs/modules/zwave2/interfaces/clu_ZWAVE_2_ft00000003_fv200_ht00000013_hv00000001.xml new file mode 100644 index 0000000..54e4e22 --- /dev/null +++ b/docs/modules/zwave2/interfaces/clu_ZWAVE_2_ft00000003_fv200_ht00000013_hv00000001.xml @@ -0,0 +1,416 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/modules/zwave2/interfaces/object_PIDcontroller_v1.xml b/docs/modules/zwave2/interfaces/object_PIDcontroller_v1.xml new file mode 100644 index 0000000..ae402d2 --- /dev/null +++ b/docs/modules/zwave2/interfaces/object_PIDcontroller_v1.xml @@ -0,0 +1,177 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/modules/zwave2/interfaces/object_calendar_v1.xml b/docs/modules/zwave2/interfaces/object_calendar_v1.xml new file mode 100644 index 0000000..4239686 --- /dev/null +++ b/docs/modules/zwave2/interfaces/object_calendar_v1.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/modules/zwave2/interfaces/object_event_scheduler_v1.xml b/docs/modules/zwave2/interfaces/object_event_scheduler_v1.xml new file mode 100644 index 0000000..fb5d1b2 --- /dev/null +++ b/docs/modules/zwave2/interfaces/object_event_scheduler_v1.xml @@ -0,0 +1,149 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/modules/zwave2/interfaces/object_presence_sensor_v2.xml b/docs/modules/zwave2/interfaces/object_presence_sensor_v2.xml new file mode 100644 index 0000000..4663c19 --- /dev/null +++ b/docs/modules/zwave2/interfaces/object_presence_sensor_v2.xml @@ -0,0 +1,146 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/modules/zwave2/interfaces/object_push_v1.xml b/docs/modules/zwave2/interfaces/object_push_v1.xml new file mode 100644 index 0000000..c1a1680 --- /dev/null +++ b/docs/modules/zwave2/interfaces/object_push_v1.xml @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/modules/zwave2/interfaces/object_scheduler_v1.xml b/docs/modules/zwave2/interfaces/object_scheduler_v1.xml new file mode 100644 index 0000000..0835e85 --- /dev/null +++ b/docs/modules/zwave2/interfaces/object_scheduler_v1.xml @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/modules/zwave2/interfaces/object_sunrise_sunset_calendar_v3.xml b/docs/modules/zwave2/interfaces/object_sunrise_sunset_calendar_v3.xml new file mode 100755 index 0000000..89c1ada --- /dev/null +++ b/docs/modules/zwave2/interfaces/object_sunrise_sunset_calendar_v3.xml @@ -0,0 +1,196 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/modules/zwave2/interfaces/object_thermostat_v2.xml b/docs/modules/zwave2/interfaces/object_thermostat_v2.xml new file mode 100644 index 0000000..7abf48e --- /dev/null +++ b/docs/modules/zwave2/interfaces/object_thermostat_v2.xml @@ -0,0 +1,247 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/modules/zwave2/interfaces/object_timer_v1.xml b/docs/modules/zwave2/interfaces/object_timer_v1.xml new file mode 100644 index 0000000..04b78b6 --- /dev/null +++ b/docs/modules/zwave2/interfaces/object_timer_v1.xml @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/modules/zwave2/logs/boot.log b/docs/modules/zwave2/logs/boot.log new file mode 100644 index 0000000..16d59fc --- /dev/null +++ b/docs/modules/zwave2/logs/boot.log @@ -0,0 +1,79 @@ + === MII registers === + CR = 0x3100 + SR = 0x782D + IDR1 = 0x0007 + IDR2 = 0xC0D1 + ANAR = 0x0DE1 + ANLPAR = 0xDDE1 + ANER = 0x0009 + ANNPTR = 0xFFFF + ICR = 0x0040 + PSR = 0x0002 + PCR = 0x00E1 + + +Parameters loaded from Flash. + +************************************************ + FNET Bootloader +************************************************ + FNET TCP/IP Stack for CLU-MCU-DIN-Rev0.3 + Version 1.0.1 + Built 2013-04-29 12:21 + Copyright 2005-2013 by Freescale Semiconductor + GNU LGPLv3 +************************************************ + Interface : eth0 + IP address : 10.72.144.1 (set manually) + Subnet mask : 255.255.0.0 + Gateway : 10.72.72.1 + MAC address : 80:34:XX:XX:XX:XX + Link status : connected + TX Packets : 4 + RX Packets : 0 + Free Heap : 14096 + TELNET server : disabled + TFTP server : disabled + + Enter 'help' for command list. +************************************************ + +Press any key to stop (go): 0 +[TFBUS] TFBus: "Reset" (7) command. + Przywrocony zapamietany klucz AES: + Przywrocony zapamietany IV: +Generuje klucz secret key: stary klucz: + NOWY klucz: +OK +[LUA_TASK] -- Start Lua Task --- +[LUA_TASK] Execute LUA script: a:\main.lua +[TFBUS] Sending Force Ask to TF-BUS module: 255 +[TFBUS] Requested ident of local address 255 - Returning DUMMY (empty) +WAR: TFBus: Sending Replay to local module 0. data: 32554... (length=4) +[TFBUS] Requested ident of local address 255 - Returning DUMMY (empty) +WAR: TFBus: Sending Replay to local module 0. data: 32554... (length=4) +[TFBUS] Requested ident of local address 255 - Returning DUMMY (empty) +WAR: TFBus: Sending Replay to local module 0. data: 32554... (length=4) +[TFBUS] Requested ident of local address 255 - Returning DUMMY (empty) +WAR: TFBus: Sending Replay to local module 0. data: 32554... (length=4) +[TFBUS] Requested ident of local address 255 - Returning DUMMY (empty) +WAR: TFBus: Sending Replay to local module 0. data: 32554... (length=4) +[TFBUS] Requested ident of local address 255 - Returning DUMMY (empty) +WAR: TFBus: Sending Replay to local module 0. data: 32554... (length=4) +Try to reconnect module SN: 25XXXXXXX + +[TFBUS] TFBus: FrameAction for module 25XXXXXXX ignored (Lua not ready) +WAR: RS485 Killed +WAR: RS485 Killed +Kill done. +hub discovery state: 1W done, DALI start +WAR: RS485 Killed +WAR: RS485 Killed +MEASURE TASK CREATED +Module: 25XXXXXXX, Version v6.3.7 +[SYSTEM] Reset reason 0x100: Software + +RTC: 2023-12-05 17:12:20 +Login: +Generate config file +Get time from NTP Server diff --git a/docs/modules/zwave2/logs/firmware.log b/docs/modules/zwave2/logs/firmware.log new file mode 100644 index 0000000..801db9d --- /dev/null +++ b/docs/modules/zwave2/logs/firmware.log @@ -0,0 +1,95 @@ + === MII registers === + CR = 0x3100 + SR = 0x782D + IDR1 = 0x0007 + IDR2 = 0xC0D1 + ANAR = 0x0DE1 + ANLPAR = 0xDDE1 + ANER = 0x0009 + ANNPTR = 0xFFFF + ICR = 0x0040 + PSR = 0x0002 + PCR = 0x00E1 + + +Parameters loaded from Flash. + +************************************************ + FNET Bootloader +************************************************ + FNET TCP/IP Stack for CLU-MCU-DIN-Rev0.3 + Version 1.0.1 + Built 2013-04-29 12:21 + Copyright 2005-2013 by Freescale Semiconductor + GNU LGPLv3 +************************************************ + Interface : eth0 + IP address : 10.72.144.1 (set manually) + Subnet mask : 255.255.0.0 + Gateway : 10.72.72.1 + MAC address : 80:34:XX:XX:XX:XX + Link status : connected + TX Packets : 4 + RX Packets : 0 + Free Heap : 14096 + TELNET server : disabled + TFTP server : disabled + + Enter 'help' for command list. +************************************************ + +Press any key to stop (script): 0 + +telnet; tftps; +************************************************ + Telnet server started. + Use: telnet 10.72.144.1 +************************************************ +************************************************ + TFTP server (10.72.144.1) started. +************************************************ +BOOT> +BOOT> get + ip : 10.72.144.1 + netmask : 255.255.0.0 + gateway : 10.72.72.1 + mac : 80:34:XX:XX:XX:XX + boot : script + delay : 0 + script : telnet; tftps; + raw : 0xC000 + tftp : 192.168.1.123 + image : firmware.bin + type : raw + go : 0xCDC1 +BOOT> set boot go + boot : go +BOOT> save +Parameters saved +BOOT> get + ip : 10.72.144.1 + netmask : 255.255.0.0 + gateway : 10.72.72.1 + mac : 80:34:XX:XX:XX:XX + boot : go + delay : 0 + script : telnet; tftps; + raw : 0xC000 + tftp : 192.168.1.123 + image : firmware.bin + type : raw + go : 0xCDC1 +BOOT> info + Interface : eth0 + IP address : 10.72.144.1 (set manually) + Subnet mask : 255.255.0.0 + Gateway : 10.72.72.1 + MAC address : 80:34:XX:XX:XX:XX + Link status : connected + TX Packets : 193 + RX Packets : 184 + Free Heap : 13184 + TELNET server : enabled + TFTP server : enabled +BOOT> reset +Connection closed by foreign host. \ No newline at end of file diff --git a/docs/modules/zwave2/logs/telnet_port_24.log b/docs/modules/zwave2/logs/telnet_port_24.log new file mode 100644 index 0000000..12d5322 --- /dev/null +++ b/docs/modules/zwave2/logs/telnet_port_24.log @@ -0,0 +1,40 @@ +a:\> dir +TEST 0 12-05-2023 16:28:30 A TEST +EMERGNCY.LUA 113 12-04-2023 16:29:22 A EMERGNCY.LUA +CLOUD-~1.PEM 227 12-04-2023 16:29:24 A CLOUD-PRIVATE.PEM +CLOUD-~1.CSR 444 12-04-2023 16:29:24 A CLOUD-PUBLIC.CSR +CONFIG~1.JSO 322 12-05-2023 08:24:40 A CONFIG.JSON +CONFIG.TXT 98 12-05-2023 16:11:58 A CONFIG.TXT +SETTINGS.USR 0 12-04-2023 16:31:42 A SETTINGS.USR +MAIN.LUA 226 12-05-2023 14:47:32 A MAIN.LUA +OM.LUA 7203 12-05-2023 14:47:32 A OM.LUA +USER.LUA 0 12-05-2023 14:47:32 A USER.LUA +a:\> mem + System allocator: +Allocator size 626688 B +Max allocated: 118672 B -> 18 % +Current usage: 104704 B -> 16 % +--------------------------------- + FLASH disk: +Disk free space: 933888 B +--------------------------------- +a:\> mount +Disc mfs_ram: and part m: created +a:\> ipconfig staticip 10.72.144.1 255.255.0.0 10.72.72.1 +Static ip bind successful. +a:\> ipconfig +Eth#: 0 +Link: on +Bind: staticip +MAC : 80:34:XX:XX:XX:XX +IP : 10.72.144.1 +MASK: 255.255.0.0 +GATE: 10.72.72.1 +DNS1: 8.8.8.8 +Link status task stopped +a:\> tftpd start +TFTP Server Started. +a:\> test +Z-Wave OK +a:\> version +5.12.01-2330-0-g293758f9 \ No newline at end of file diff --git a/docs/om/README.md b/docs/om/README.md new file mode 100644 index 0000000..b682a15 --- /dev/null +++ b/docs/om/README.md @@ -0,0 +1,25 @@ +# Run in Wayland using xwayland +Since OM uses legacy Java8, to run under Wayland, we need to force X11/XWayland GDK support. + +Export the following environment variable: +> GDK_BACKEND=x11 + +If you're affected by the issue, you will see the following message: + +``` +2023-12-06 11:53:45.860 [ERROR][main] STDERR:63 Dec 06, 2023 11:53:45 AM com.sun.glass.ui.gtk.GtkApplication +WARNING: SWT-GTK uses unsupported major GTK version 0. GTK3 will be used as default. + +(Object Manager:85814): Gdk-CRITICAL **: 11:53:45.863: gdk_x11_display_set_window_scale: assertion 'GDK_IS_X11_DISPLAY (display)' failed +# +# A fatal error has been detected by the Java Runtime Environment: +# +# SIGSEGV (0xb) at pc=0x00007f53e00804ef, pid=85814, tid=0x00007f5423bff6c0 +# +# JRE version: Java(TM) SE Runtime Environment (8.0_202-b08) (build 1.8.0_202-b08) +# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.202-b08 mixed mode linux-amd64 compressed oops) +# Problematic frame: +# C [libX11.so.6+0x2d4ef] XInternAtom+0x3f +# +# Core dump written. (...) +``` \ No newline at end of file diff --git a/lib/pom.xml b/lib/pom.xml new file mode 100644 index 0000000..4375e6d --- /dev/null +++ b/lib/pom.xml @@ -0,0 +1,73 @@ + + + + + 4.0.0 + + + pl.psobiech.opengr8on + parent + 1.0-SNAPSHOT + + + lib + + + + pl.psobiech.opengr8on + tftp + + + + pl.psobiech.opengr8on + common + + + + ch.qos.logback + logback-classic + test + + + + commons-cli + commons-cli + + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + com.fasterxml.jackson.module + jackson-module-parameter-names + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + + org.bouncycastle + bcprov-jdk18on + + + \ No newline at end of file diff --git a/lib/src/main/java/pl/psobiech/opengr8on/client/CLUClient.java b/lib/src/main/java/pl/psobiech/opengr8on/client/CLUClient.java new file mode 100644 index 0000000..8fad65c --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/client/CLUClient.java @@ -0,0 +1,286 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Inet4Address; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import pl.psobiech.opengr8on.org.apache.commons.net.TFTPErrorPacket; +import pl.psobiech.opengr8on.org.apache.commons.net.TFTPPacketIOException; +import pl.psobiech.opengr8on.client.commands.LuaScriptCommand; +import pl.psobiech.opengr8on.client.commands.ResetCommand; +import pl.psobiech.opengr8on.client.commands.ResetCommand.Response; +import pl.psobiech.opengr8on.client.commands.SetIpCommand; +import pl.psobiech.opengr8on.client.commands.SetKeyCommand; +import pl.psobiech.opengr8on.client.commands.StartTFTPdCommand; +import pl.psobiech.opengr8on.client.device.CLUDevice; +import pl.psobiech.opengr8on.client.device.CipherTypeEnum; +import pl.psobiech.opengr8on.exceptions.UnexpectedException; +import pl.psobiech.opengr8on.org.apache.commons.net.TFTP; +import pl.psobiech.opengr8on.util.HexUtil; +import pl.psobiech.opengr8on.util.IPv4AddressUtil.NetworkInterfaceDto; +import pl.psobiech.opengr8on.util.RandomUtil; +import pl.psobiech.opengr8on.util.SocketUtil; +import pl.psobiech.opengr8on.util.SocketUtil.Payload; +import pl.psobiech.opengr8on.util.Util; + +public class CLUClient extends Client implements AutoCloseable { + private static Logger LOGGER = LoggerFactory.getLogger(CLUClient.class); + + private static final String TFTP_NOT_FOUND_ERROR_CODE = "Error code %d".formatted(TFTPErrorPacket.FILE_NOT_FOUND); + + private static final int TFTP_RETRIES = 3; + + private static final Duration DEFAULT_TIMEOUT_DURATION = Duration.ofMillis(SocketUtil.DEFAULT_TIMEOUT); + + private final CLUDevice cluDevice; + + private final TFTPClient tftpClient; + + private CipherKey cipherKey; + + public CLUClient(NetworkInterfaceDto networkInterface, CLUDevice cluDevice) { + this(networkInterface, cluDevice, cluDevice.getCipherKey()); + } + + public CLUClient(NetworkInterfaceDto networkInterface, Inet4Address ipAddress, CipherKey cipherKey) { + this(networkInterface, ipAddress, cipherKey, COMMAND_PORT); + } + + public CLUClient(NetworkInterfaceDto networkInterface, Inet4Address ipAddress, CipherKey cipherKey, int port) { + this( + networkInterface, + new CLUDevice(ipAddress, CipherTypeEnum.PROJECT), + cipherKey, + port + ); + } + + public CLUClient(NetworkInterfaceDto networkInterface, CLUDevice cluDevice, CipherKey cipherKey) { + this(networkInterface, cluDevice, cipherKey, COMMAND_PORT); + } + + public CLUClient(NetworkInterfaceDto networkInterface, CLUDevice cluDevice, CipherKey cipherKey, int port) { + super(networkInterface, port); + + this.cluDevice = cluDevice; + + this.tftpClient = createTFTPClient(); + + this.cipherKey = cipherKey; + } + + private static TFTPClient createTFTPClient() { + final TFTPClient tftpClient = new TFTPClient(); + tftpClient.setMaxTimeouts(TFTP_RETRIES); + tftpClient.setDefaultTimeout(DEFAULT_TIMEOUT_DURATION.dividedBy(TFTP_RETRIES)); + + return tftpClient; + } + + public Optional setCipherKey(CipherKey newCipherKey) { + final byte[] randomBytes = RandomUtil.bytes(Command.RANDOM_SIZE); + + return request( + newCipherKey, + SetKeyCommand.request( + newCipherKey.encrypt(randomBytes), newCipherKey.getSecretKey(), newCipherKey.getIV() + ), + DEFAULT_TIMEOUT_DURATION + ) + .flatMap(payload -> + SetKeyCommand.responseFromByteArray(payload.buffer()) + .map(response -> { + this.cipherKey = newCipherKey; + + return true; + }) + ); + } + + public Inet4Address getAddress() { + return getCluDevice().getAddress(); + } + + public Optional setAddress(Inet4Address newAddress, Inet4Address gatewayAddress) { + final SetIpCommand.Request command = SetIpCommand.request(cluDevice.getSerialNumber(), newAddress, gatewayAddress); + + return request(command, DEFAULT_TIMEOUT_DURATION) + .flatMap(payload -> { + final Optional responseOptional = SetIpCommand.responseFromByteArray(payload.buffer()); + if (responseOptional.isEmpty()) { + final Inet4Address ipAddress = payload.address(); + cluDevice.setAddress(ipAddress); + + return Optional.of(payload.address()); + } + + final SetIpCommand.Response response = responseOptional.get(); + final Inet4Address ipAddress = response.getIpAddress(); + cluDevice.setAddress(ipAddress); + + return Optional.of(ipAddress); + }); + } + + public CLUDevice getCluDevice() { + return cluDevice; + } + + public Optional reset(Duration timeout) { + final ResetCommand.Request command = ResetCommand.request(networkInterface.getAddress()); + + final Optional reset = request(command, DEFAULT_TIMEOUT_DURATION) + .flatMap(payload -> ResetCommand.responseFromByteArray(payload.buffer())); + + if (reset.isPresent()) { + return Optional.of(true); + } + + return Util.repeatUntilTrueOrTimeout( + timeout, + duration -> + checkAlive() + ); + } + + public Optional checkAlive() { + return execute(LuaScriptCommand.CHECK_ALIVE) + .map(returnValue -> Boolean.parseBoolean(returnValue) || Objects.equals(getCluDevice().getSerialNumber(), HexUtil.asLong(returnValue))); + } + + public Optional execute(String script) { + final Integer sessionId = HexUtil.asInt(RandomUtil.hexString(8)); + final LuaScriptCommand.Request command = LuaScriptCommand.request(networkInterface.getAddress(), sessionId, script); + + return request(command, DEFAULT_TIMEOUT_DURATION) + .flatMap(payload -> LuaScriptCommand.parse(sessionId, payload)); + } + + public Optional startTFTPdServer() { + return request(StartTFTPdCommand.request(), DEFAULT_TIMEOUT_DURATION) + .flatMap(payload -> StartTFTPdCommand.responseFromByteArray(payload.buffer())) + .map(response -> true); + } + + public Optional stopTFTPdServer() { + // not implemented? req_stop_ftp req_tftp_stop don't work + return Optional.of(true); + } + + public void uploadFile(Path file, String location) { + synchronized (tftpClient) { + try ( + tftpClient; + InputStream inputStream = Files.newInputStream(file) + ) { + tftpClient.open(); + + tftpClient.sendFile( + location, TFTP.BINARY_MODE, + inputStream, + cluDevice.getAddress(), TFTP_PORT + ); + } catch (IOException e) { + throw new UnexpectedException(e); + } + } + } + + public Optional downloadFile(String location, Path file) { + synchronized (tftpClient) { + try ( + tftpClient; + OutputStream outputStream = Files.newOutputStream(file) + ) { + tftpClient.open(); + + tftpClient.receiveFile( + location, TFTP.BINARY_MODE, + outputStream, + cluDevice.getAddress(), TFTP_PORT + ); + + return Optional.of(file); + } catch (IOException e) { + final boolean fileNotFound; + if (e instanceof TFTPPacketIOException) { + fileNotFound = ((TFTPPacketIOException) e).getErrorPacketCode() == TFTPErrorPacket.FILE_NOT_FOUND; + } else { + final String message = e.getMessage(); + + fileNotFound = (message != null && message.startsWith(TFTP_NOT_FOUND_ERROR_CODE)); + } + + if (fileNotFound) { + try { + Files.deleteIfExists(file); + } catch (IOException e2) { + LOGGER.warn(e2.getMessage(), e2); + } + + return Optional.empty(); + } + + throw new UnexpectedException(e); + } + } + } + + public void clientReport(String value) { + final LuaScriptCommand.Response response = LuaScriptCommand.response(cluDevice.getAddress(), HexUtil.asInt(RandomUtil.hexString(8)), value); + final String uuid = response.uuid(UUID.randomUUID()); + + synchronized (socket) { + send(uuid, cipherKey, cluDevice.getAddress(), response.asByteArray()); + } + } + + public Optional request(Command command, Duration timeout) { + return request(cipherKey, command, timeout); + } + + public Optional request(CipherKey responseCipherKey, Command command, Duration timeout) { + final String uuid = uuid(command); + + synchronized (socket) { + send(uuid, cipherKey, cluDevice.getAddress(), command.asByteArray()); + + return Util.repeatUntilTimeout( + timeout, + duration -> + awaitResponsePayload(uuid, responseCipherKey, duration) + ); + } + } + + public static class TFTPClient extends pl.psobiech.opengr8on.org.apache.commons.net.TFTPClient implements AutoCloseable { + // NOP + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/client/CLUFiles.java b/lib/src/main/java/pl/psobiech/opengr8on/client/CLUFiles.java new file mode 100644 index 0000000..9e30cb6 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/client/CLUFiles.java @@ -0,0 +1,88 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client; + +public enum CLUFiles { + USER_LUA("a", "USER.LUA"), + OM_LUA("a", "OM.LUA"), + MAIN_LUA("a", "MAIN.LUA"), + // + EMERGNCY_LUA("a", "EMERGNCY.LUA"), + // + SETTINGS_USR("a", "settings.usr"), + // + CONFIG_TXT("a", "config.txt", true, false), + CONFIG_JSON("a", "CONFIG.JSON", true, false), + // + MEASUREMENT_FILE("p", "meas.bin", true, false), + // + IMAGE_FW("m", "image.fw", false, true), + // + DEBUG_BIN("m", "debug.bin", true, false), + DIAGNOSTIC_PACK_JSON("m", "DIAGNOSTIC_PACK.JSON", true, false), + // + CLOUD_PRIVATE_PEM("a", "CLOUD-PRIVATE.PEM"), + CLOUD_PUBLIC_CSR("a", "CLOUD-PUBLIC.CSR"), + CLOUD_PUBLIC_CRT("a", "CLOUD-PUBLIC.CRT"), + CLOUD_ROOT_PEM("a", "CLOUD-ROOT.PEM"), + // + //INIT_LUA("a", "INIT.LUA"), + //LOADALL_SO("a", "loadall.so"), + //WATCHDOG_LOG("a", "watchdog.log"), + ; + + private final String device; + + private final String fileName; + + private final boolean readable; + + private final boolean writable; + + CLUFiles(String device, String fileName) { + this(device, fileName, true, true); + } + + CLUFiles(String device, String fileName, boolean readable, boolean writable) { + this.device = device; + this.fileName = fileName; + this.readable = readable; + this.writable = writable; + } + + public String getLocation() { + return getDevice() + ":\\" + getFileName(); + } + + public String getDevice() { + return device; + } + + public String getFileName() { + return fileName; + } + + public boolean isReadable() { + return readable; + } + + public boolean isWritable() { + return writable; + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/client/CipherKey.java b/lib/src/main/java/pl/psobiech/opengr8on/client/CipherKey.java new file mode 100644 index 0000000..773791e --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/client/CipherKey.java @@ -0,0 +1,232 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.Security; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.ShortBufferException; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import org.apache.commons.codec.binary.Base64; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import pl.psobiech.opengr8on.exceptions.UnexpectedException; + +public class CipherKey { + static { + Security.insertProviderAt(new BouncyCastleProvider(), 1); + } + + public static final int INPUT_BUFFER_SIZE = 256; + + private static final String ALGORITHM = "AES"; + + private static final String CIPHER = "AES/CBC/PKCS5Padding"; + + protected static final byte[] DEFAULT_KEY = Base64.decodeBase64("hd5SHpxl0N5+WEXTXlPQmw=="); + + protected static final byte[] DEFAULT_IV = Base64.decodeBase64("ua/jh/kZo9Og15rejhGhFg=="); + + protected static final byte[] DEFAULT_BROADCAST_IV = Base64.decodeBase64("BwYFBAMCAQAEAgkDBAEFBw=="); + + public static final CipherKey DEFAULT_BROADCAST = new CipherKey(CipherKey.DEFAULT_KEY, CipherKey.DEFAULT_BROADCAST_IV); + + private final SecretKeySpec keySpecification; + + private final IvParameterSpec ivParameterSpecification; + + public CipherKey(byte[] keyAsBytes, byte[] ivAsBytes) { + this(new SecretKeySpec(keyAsBytes, ALGORITHM), new IvParameterSpec(ivAsBytes)); + } + + public CipherKey(byte[] keyAsBytes, IvParameterSpec ivParameterSpecification) { + this(new SecretKeySpec(keyAsBytes, ALGORITHM), ivParameterSpecification); + } + + public CipherKey(SecretKeySpec keySpecification, byte[] ivAsBytes) { + this(keySpecification, new IvParameterSpec(ivAsBytes)); + } + + public CipherKey(SecretKeySpec keySpecification, IvParameterSpec ivParameterSpecification) { + this.keySpecification = keySpecification; + this.ivParameterSpecification = ivParameterSpecification; + } + + public static CipherKey getInitialCipherKey(byte[] iv, byte[] privateKey) { + return new CipherKey(generateDefaultKey(privateKey), iv); + } + + public static byte[] generateDefaultKey(byte[] privateKey) { + return generateKey(DEFAULT_IV, privateKey); + } + + public static byte[] generateKey(byte[] iv, byte[] privateKey) { + assert iv.length % 2 == 0; + assert privateKey.length == iv.length / 2; + + final int size = iv.length; + final byte[] result = new byte[size]; + + int i = 0; + for (; i < iv.length / 2; i++) { + result[i] = (byte) (iv[i] ^ privateKey[i]); + } + for (; i < size; i++) { + result[i] = (byte) (iv[i] ^ privateKey[(size - 1) - i]); + } + + return result; + } + + public CipherKey withIV(byte[] iv) { + return new CipherKey(keySpecification(), new IvParameterSpec(iv)); + } + + public Optional decrypt(byte[] input) { + return decrypt(input, 0, input.length); + } + + public Optional decrypt(byte[] input, int offset, int limit) { + try { + final Cipher cipher = Cipher.getInstance(CIPHER, BouncyCastleProvider.PROVIDER_NAME); + cipher.init(Cipher.DECRYPT_MODE, keySpecification(), ivSpecification()); + + return Optional.of( + process(cipher, input, offset, limit) + ); + } catch (IllegalBlockSizeException | BadPaddingException e) { + return Optional.empty(); + } catch (InvalidAlgorithmParameterException | NoSuchPaddingException | ShortBufferException | NoSuchAlgorithmException | InvalidKeyException | + NoSuchProviderException e) { + throw new UnexpectedException(e); + } + } + + public byte[] encrypt(byte[] message) { + try { + final Cipher cipher = Cipher.getInstance(CIPHER, BouncyCastleProvider.PROVIDER_NAME); + cipher.init(Cipher.ENCRYPT_MODE, keySpecification(), ivSpecification()); + + return process(cipher, message, 0, message.length); + } catch (InvalidAlgorithmParameterException | NoSuchPaddingException | ShortBufferException | IllegalBlockSizeException | NoSuchAlgorithmException | + BadPaddingException | InvalidKeyException | NoSuchProviderException e) { + throw new UnexpectedException(e); + } + } + + private static byte[] process(Cipher cipher, byte[] input, int offset, int limit) + throws IllegalBlockSizeException, ShortBufferException, BadPaddingException { + final byte[] inputBuffer = new byte[INPUT_BUFFER_SIZE]; + byte[] outputBuffer = new byte[cipher.getOutputSize(inputBuffer.length)]; + try ( + InputStream inputStream = new ByteArrayInputStream(input, offset, limit); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(cipher.getOutputSize(input.length)); + ) { + int read; + do { + read = inputStream.read(inputBuffer, 0, inputBuffer.length); + if (read < 0) { + outputBuffer = ensureCapacity(outputBuffer, cipher.getOutputSize(0)); + final int written = cipher.doFinal(outputBuffer, 0); + if (written > 0) { + outputStream.write(outputBuffer, 0, written); + } + + break; + } + + outputBuffer = ensureCapacity(outputBuffer, cipher.getOutputSize(read)); + final int written = cipher.update(inputBuffer, 0, read, outputBuffer, 0); + if (written > 0) { + outputStream.write(outputBuffer, 0, written); + } + } while (!Thread.interrupted()); + + return outputStream.toByteArray(); + } catch (IOException e) { + throw new UnexpectedException(e); + } + } + + private static byte[] ensureCapacity(byte[] buffer, int requiredCapacity) { + if (requiredCapacity > buffer.length) { + return new byte[requiredCapacity]; + } + + return buffer; + } + + public byte[] getSecretKey() { + return keySpecification().getEncoded(); + } + + protected SecretKeySpec keySpecification() { + return keySpecification; + } + + public byte[] getIV() { + return ivSpecification().getIV(); + } + + protected IvParameterSpec ivSpecification() { + return ivParameterSpecification; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + + if (!(o instanceof final CipherKey cipherKey)) { + return false; + } + + return Arrays.equals(keySpecification.getEncoded(), cipherKey.keySpecification.getEncoded()) + && Arrays.equals(ivParameterSpecification.getIV(), cipherKey.ivParameterSpecification.getIV()); + } + + @Override + public int hashCode() { + return Objects.hash(keySpecification, ivParameterSpecification); + } + + @Override + public String toString() { + return "CipherKey{" + + "key=" + Base64.encodeBase64String(keySpecification.getEncoded()) + + ", iv=" + Base64.encodeBase64String(ivParameterSpecification.getIV()) + + '}'; + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/client/Client.java b/lib/src/main/java/pl/psobiech/opengr8on/client/Client.java new file mode 100644 index 0000000..77018ea --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/client/Client.java @@ -0,0 +1,273 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client; + +import java.net.DatagramPacket; +import java.net.Inet4Address; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.Queue; +import java.util.Spliterators.AbstractSpliterator; +import java.util.UUID; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.Future.State; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import pl.psobiech.opengr8on.util.SocketUtil; +import pl.psobiech.opengr8on.util.SocketUtil.Payload; +import pl.psobiech.opengr8on.util.SocketUtil.UDPSocket; +import pl.psobiech.opengr8on.client.commands.DiscoverCLUsCommand; +import pl.psobiech.opengr8on.client.device.CLUDevice; +import pl.psobiech.opengr8on.util.IPv4AddressUtil; +import pl.psobiech.opengr8on.util.IPv4AddressUtil.NetworkInterfaceDto; +import pl.psobiech.opengr8on.util.RandomUtil; +import pl.psobiech.opengr8on.util.ThreadUtil; + +public class Client implements AutoCloseable { + private static final Logger LOGGER = LoggerFactory.getLogger(Client.class); + + public static final int COMMAND_PORT = 1234; + + public static final int TFTP_PORT = 69; + + private static final int BUFFER_SIZE = 2048; + + private int port; + + private final DatagramPacket responsePacket = new DatagramPacket(new byte[BUFFER_SIZE], BUFFER_SIZE); + + protected final NetworkInterfaceDto networkInterface; + + protected final UDPSocket socket; + + private final ExecutorService executor = Executors.newSingleThreadExecutor(ThreadUtil.daemonThreadFactory("cluClient")); + + public Client(NetworkInterfaceDto networkInterface) { + this(networkInterface, COMMAND_PORT); + } + + public Client(NetworkInterfaceDto networkInterface, int port) { + this.networkInterface = networkInterface; + + this.port = port; + + this.socket = SocketUtil.udp(networkInterface.getNetworkInterface(), networkInterface.getAddress()); + this.socket.open(); + } + + public Stream discover(CipherKey projectCipherKey, Map privateKeys, Duration timeout, int limit) { + final byte[] randomBytes = RandomUtil.bytes(Command.RANDOM_SIZE); + final DiscoverCLUsCommand.Request request = DiscoverCLUsCommand.request( + projectCipherKey.encrypt(randomBytes), projectCipherKey.getIV(), networkInterface.getAddress() + ); + + return broadcastStream( + CipherKey.DEFAULT_BROADCAST, CipherKey.DEFAULT_BROADCAST.withIV(projectCipherKey.getIV()), + request, + IPv4AddressUtil.parseIPv4("255.255.255.255"), // networkInterface.getBroadcastAddress(), + timeout, limit + ) + .flatMap(payload -> DiscoverCLUsCommand.parse(randomBytes, payload, privateKeys).stream()); + } + + public Collection broadcast( + CipherKey requestCipherKey, CipherKey responseCipherKey, + Command command, + Inet4Address ipAddress, + Duration timeout, int limit + ) { + return broadcastStream( + requestCipherKey, responseCipherKey, + command, + ipAddress, + timeout, limit + ) + .collect(Collectors.toList()); + } + + public Stream broadcastStream( + CipherKey requestCipherKey, CipherKey responseCipherKey, + Command command, + Inet4Address ipAddress, + Duration timeout, int limit + ) { + final String uuid = uuid(command); + final Queue queue = new ArrayBlockingQueue<>(8); + + final Future future = executor.submit(() -> { + synchronized (socket) { + send(uuid, requestCipherKey, ipAddress, command.asByteArray()); + + Duration threadTimeout = timeout; + + final ArrayList results = new ArrayList<>(Math.max(limit == Integer.MAX_VALUE ? -1 : limit, 0)); + do { + final long startedAt = System.nanoTime(); + + final Optional payloadOptional = awaitResponsePayload(uuid, responseCipherKey, threadTimeout); + if (payloadOptional.isPresent()) { + final Payload payload = payloadOptional.get(); + + results.add(payload); + + while (!queue.offer(payload) && !Thread.interrupted()) { + Thread.yield(); + } + } + + threadTimeout = threadTimeout.minusNanos(System.nanoTime() - startedAt); + } while (threadTimeout.isPositive() && results.size() < limit && !Thread.interrupted()); + + return null; + } + }); + + return StreamSupport.stream( + new AbstractSpliterator<>(8, 0) { + @Override + public boolean tryAdvance(Consumer action) { + final boolean futureDone = future.isDone(); + + final Payload payload = queue.poll(); + if (payload != null) { + try { + action.accept(payload); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + } + + return true; + } + + if (!futureDone) { + return true; + } + + if (future.state() == State.FAILED) { + LOGGER.error("Unexpected error while streaming broadcast responses", future.exceptionNow()); + } + + return false; + } + }, + false + ); + } + + protected void send(String uuid, CipherKey cipherKey, Inet4Address ipAddress, byte[] buffer) { + final Payload requestPayload = Payload.of(ipAddress, port, buffer); + LOGGER.trace( + "\n%s\n--D->\t%s // %s" + .formatted(uuid, requestPayload, cipherKey) + ); + + final byte[] encryptedRequest = cipherKey.encrypt(requestPayload.buffer()); + // LOGGER.trace( + // "\n%s\n--E->\t%s // %s" + // .formatted(uuid, Payload.of(ipAddress, port, encryptedRequest), cipherKey) + // ); + + synchronized (socket) { + socket.discard(responsePacket); + + final DatagramPacket requestPacket = new DatagramPacket(encryptedRequest, encryptedRequest.length); + requestPacket.setAddress(requestPayload.address()); + requestPacket.setPort(requestPayload.port()); + socket.send(requestPacket); + } + } + + protected Optional awaitResponsePayload(String uuid, CipherKey responseCipherKey, Duration timeout) { + final Optional encryptedPayload = socket.tryReceive(responsePacket, timeout); + if (encryptedPayload.isEmpty()) { + LOGGER.trace( + "\n%s\n-----\tTIMEOUT // %s" + .formatted(uuid, responseCipherKey) + ); + + return Optional.empty(); + } + + return Client.tryDecrypt(uuid, responseCipherKey, encryptedPayload.get()); + } + + public static Optional tryDecrypt( + String uuid, + CipherKey responseCipherKey, Payload encryptedPayload + ) { + final Optional payload = responseCipherKey.decrypt(encryptedPayload.buffer()) + .map(decryptedResponse -> + Payload.of( + encryptedPayload.address(), encryptedPayload.port(), + decryptedResponse + ) + ); + + if (LOGGER.isTraceEnabled()) { + if (payload.isPresent()) { + LOGGER.trace( + "\n%s\n<-D--\t%s // %s" + .formatted(uuid, payload.get(), responseCipherKey) + ); + } else { + LOGGER.trace( + "\n%s\n<-E--\t%s // %s" + .formatted(uuid, encryptedPayload, responseCipherKey) + ); + } + } + + return payload; + } + + @Override + public synchronized void close() { + executor.shutdown(); + + synchronized (socket) { + socket.close(); + } + } + + public static String uuid(Command command) { + return uuid(UUID.randomUUID(), command.getClass()); + } + + public static String uuid(UUID uuid, Command command) { + return uuid(uuid, command.getClass()); + } + + public static String uuid(UUID uuid, Class clazz) { + final String className = clazz.getName(); + final String[] classParts = className.split("\\."); + + return "%s\t%s".formatted(uuid, classParts[classParts.length - 1]); + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/client/Command.java b/lib/src/main/java/pl/psobiech/opengr8on/client/Command.java new file mode 100644 index 0000000..ce2a8b7 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/client/Command.java @@ -0,0 +1,110 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.Inet4Address; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.UUID; + +import pl.psobiech.opengr8on.exceptions.UnexpectedException; + +public interface Command { + int INITIAL_BUFFER_SIZE = 256; + + int MIN_IP_SIZE = 7; + + int IV_SIZE = 16; + + int KEY_SIZE = 16; + + int MAC_SIZE = 12; + + int MIN_SERIAL_NUMBER_SIZE = 4; + + int MIN_SESSION_SIZE = 6; + + int RANDOM_SIZE = 30; + + int RANDOM_ENCRYPTED_SIZE = 32; + + static boolean equals(String value1, byte[] buffer, int offset) { + if (value1 == null) { + return false; + } + + return value1.equals(asString(buffer, offset, value1.length())); + } + + static String asString(byte[] buffer) { + return asString(buffer, 0); + } + + static String asString(byte[] buffer, int offset) { + return asStringOfRange(buffer, offset, buffer.length); + } + + static String asString(byte[] buffer, int offset, int limit) { + return asStringOfRange(buffer, offset, offset + limit); + } + + private static String asStringOfRange(byte[] buffer, int from, int to) { + return new String(Arrays.copyOfRange(buffer, from, to)).trim(); + } + + default String uuid(UUID uuid) { + return Client.uuid(uuid, this); + } + + static byte[] serialize(Object... objects) { + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(INITIAL_BUFFER_SIZE)) { + for (Object object : objects) { + outputStream.write(serializeObject(object)); + } + + return outputStream.toByteArray(); + } catch (IOException e) { + throw new UnexpectedException(e); + } + } + + private static byte[] serializeObject(Object object) { + if (object instanceof byte[]) { + return (byte[]) object; + } + + if (object instanceof String) { + return ((String) object).getBytes(StandardCharsets.UTF_8); + } + + if (object instanceof Long || object instanceof Integer) { + return serializeObject(String.valueOf(object)); + } + + if (object instanceof Inet4Address) { + return serializeObject(((Inet4Address) object).getHostAddress()); + } + + throw new UnexpectedException("Unsupported object type: " + object); + } + + byte[] asByteArray(); +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/client/commands/DiscoverCLUsCommand.java b/lib/src/main/java/pl/psobiech/opengr8on/client/commands/DiscoverCLUsCommand.java new file mode 100644 index 0000000..373724a --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/client/commands/DiscoverCLUsCommand.java @@ -0,0 +1,279 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.commands; + +import java.net.Inet4Address; +import java.util.Arrays; +import java.util.Map; +import java.util.Optional; + +import org.apache.commons.lang3.StringUtils; +import pl.psobiech.opengr8on.client.CipherKey; +import pl.psobiech.opengr8on.client.Command; +import pl.psobiech.opengr8on.client.device.CipherTypeEnum; +import pl.psobiech.opengr8on.util.SocketUtil.Payload; +import pl.psobiech.opengr8on.client.device.CLUDevice; +import pl.psobiech.opengr8on.util.HexUtil; +import pl.psobiech.opengr8on.util.IPv4AddressUtil; +import pl.psobiech.opengr8on.util.Util; + +public class DiscoverCLUsCommand { + private DiscoverCLUsCommand() { + // NOP + } + + public static Request request(byte[] encrypted, byte[] iv, Inet4Address ipAddress) { + return new Request(encrypted, iv, ipAddress); + } + + public static Optional requestFromByteArray(byte[] buffer) { + if (!requestMatches(buffer)) { + return Optional.empty(); + } + + final byte[] encrypted = Arrays.copyOfRange(buffer, 0, Command.RANDOM_ENCRYPTED_SIZE); + final byte[] iv = Arrays.copyOfRange(buffer, Command.RANDOM_ENCRYPTED_SIZE + 1, Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE); + + final String requestAsString = Command.asString(buffer, Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1); + final Optional requestPartsOptional = Util.splitExact(requestAsString, ":", 2); + if (requestPartsOptional.isEmpty()) { + return Optional.empty(); + } + + final String[] requestParts = requestPartsOptional.get(); + + return Optional.of( + new Request( + encrypted, iv, + IPv4AddressUtil.parseIPv4(requestParts[1]) + ) + ); + } + + public static boolean requestMatches(byte[] buffer) { + if (buffer.length < Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1 + Request.COMMAND.length() + 1 + Command.MIN_IP_SIZE) { + return false; + } + + if (buffer[Command.RANDOM_ENCRYPTED_SIZE] != ':' + || buffer[Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE] != ':' + || buffer[Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1 + Request.COMMAND.length()] != ':') { + return false; + } + + return Request.COMMAND.equals( + Command.asString( + buffer, + Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1, + Request.COMMAND.length() + ) + ); + } + + public static Response response(byte[] encrypted, byte[] iv, Long serialNumber, String macAddress) { + return new Response(encrypted, iv, serialNumber, macAddress); + } + + public static Optional parse(byte[] randomBytes, Payload payload, Map privateKeys) { + final Optional responseOptional = responseFromByteArray(payload.buffer()); + if (responseOptional.isEmpty()) { + return Optional.empty(); + } + + final Response response = responseOptional.get(); + final byte[] iv = response.iv; + final Long serialNumberAsLong = response.serialNumber; + final byte[] privateKey = privateKeys.get(serialNumberAsLong); + + final CipherTypeEnum cipherType = getCipherType(randomBytes, response.encrypted, iv, privateKey); + + return Optional.of( + new CLUDevice( + serialNumberAsLong, response.macAddress, payload.address(), + cipherType, iv, privateKey + ) + ); + } + + public static Optional responseFromByteArray(byte[] buffer) { + if (!responseMatches(buffer)) { + return Optional.empty(); + } + + final byte[] encrypted = Arrays.copyOfRange(buffer, 0, Command.RANDOM_ENCRYPTED_SIZE); + final byte[] iv = Arrays.copyOfRange(buffer, Command.RANDOM_ENCRYPTED_SIZE + 1, Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE); + + final String responseAsString = Command.asString(buffer, Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1); + final Optional responsePartsOptional = Util.splitExact(responseAsString, ":", 3); + if (responsePartsOptional.isEmpty()) { + return Optional.empty(); + } + + final String[] responseParts = responsePartsOptional.get(); + + return Optional.of( + new Response( + encrypted, iv, + HexUtil.asLong(responseParts[1]), + responseParts[2] + ) + ); + } + + public static boolean responseMatches(byte[] buffer) { + if (buffer.length + < Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1 + Response.COMMAND.length() + 1 + Command.MIN_SERIAL_NUMBER_SIZE + 1 + Command.MAC_SIZE) { + return false; + } + + if (buffer[32] != ':' + || buffer[Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE] != ':' + || buffer[Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1 + Response.COMMAND.length()] != ':') { + return false; + } + + return Response.COMMAND.equals( + Command.asString( + buffer, + Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1, + Response.COMMAND.length() + ) + ); + } + + public static CipherTypeEnum getCipherType(byte[] randomBytes, byte[] encrypted, byte[] iv, byte[] privateKey) { + if (privateKey == null) { + return CipherTypeEnum.UNKNOWN; + } + + final byte[] randomBytesHash = hash(randomBytes); + final byte[] randomEncrypted = CipherKey.getInitialCipherKey(iv, privateKey) + .encrypt(randomBytesHash); + if (Arrays.equals(randomEncrypted, encrypted)) { + return CipherTypeEnum.PROJECT; + } + + return CipherTypeEnum.NONE; + } + + public static byte[] hash(byte[] buffer) { + final byte[] result = new byte[buffer.length]; + + int previousValue = (result[0] = (byte) (buffer[0] ^ buffer[buffer.length - 1])); + for (int i = 1; i < buffer.length; i++) { + final int a = previousValue % 0x0D; + final int b = buffer[i] % 0x13; + + previousValue = (result[i] = (byte) ((a + 1) * (b + 1))); + } + + return result; + } + + public static class Request implements Command { + protected static final String COMMAND = "req_discovery_clu"; + + private final byte[] encrypted; + + private final byte[] iv; + + private final Inet4Address ipAddress; + + private Request(byte[] encrypted, byte[] iv, Inet4Address ipAddress) { + this.encrypted = encrypted; + this.iv = iv; + this.ipAddress = ipAddress; + } + + @Override + public byte[] asByteArray() { + return Command.serialize( + encrypted, + ":", + iv, + ":", + COMMAND, + ":", + ipAddress + ); + } + + public byte[] getEncrypted() { + return encrypted; + } + + public byte[] getIV() { + return iv; + } + + public Inet4Address getIpAddress() { + return ipAddress; + } + } + + public static class Response implements Command { + protected static final String COMMAND = "resp_discovery_clu"; + + private final byte[] encrypted; + + private final byte[] iv; + + private final Long serialNumber; + + private final String macAddress; + + private Response(byte[] encrypted, byte[] iv, Long serialNumber, String macAddress) { + this.encrypted = encrypted; + this.iv = iv; + this.serialNumber = serialNumber; + this.macAddress = macAddress; + } + + @Override + public byte[] asByteArray() { + return Command.serialize( + encrypted, + ":", + iv, + ":", + COMMAND, + ":", + StringUtils.leftPad(StringUtils.lowerCase(HexUtil.asString(serialNumber)), 8, '0'), + ":", + macAddress + ); + } + + public byte[] getEncrypted() { + return encrypted; + } + + public byte[] getIv() { + return iv; + } + + public Long getSerialNumber() { + return serialNumber; + } + + public String getMacAddress() { + return macAddress; + } + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/client/commands/ErrorCommand.java b/lib/src/main/java/pl/psobiech/opengr8on/client/commands/ErrorCommand.java new file mode 100644 index 0000000..b958de4 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/client/commands/ErrorCommand.java @@ -0,0 +1,69 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.commands; + +import java.util.Optional; + +import pl.psobiech.opengr8on.client.Command; + +public class ErrorCommand { + private static final Response RESPONSE = new Response(); + + private ErrorCommand() { + // NOP + } + + public static Response response() { + return RESPONSE; + } + + public static Optional responseFromByteArray(byte[] buffer) { + if (!responseMatches(buffer)) { + return Optional.empty(); + } + + return Optional.of(RESPONSE); + } + + public static boolean responseMatches(byte[] buffer) { + if (buffer.length != Response.COMMAND.length() + && buffer.length != Response.COMMAND.length() + 2 /* \r\n */) { + return false; + } + + return Response.COMMAND.equals( + Command.asString(buffer, 0, Response.COMMAND.length()) + ); + } + + public static class Response implements Command { + static final String COMMAND = "resp:ERROR"; + + private Response() { + // NOP + } + + @Override + public byte[] asByteArray() { + return Command.serialize( + COMMAND + ); + } + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/client/commands/LuaScriptCommand.java b/lib/src/main/java/pl/psobiech/opengr8on/client/commands/LuaScriptCommand.java new file mode 100644 index 0000000..50a5750 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/client/commands/LuaScriptCommand.java @@ -0,0 +1,212 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.commands; + +import java.net.Inet4Address; +import java.util.Optional; + +import org.apache.commons.lang3.StringUtils; +import pl.psobiech.opengr8on.client.Command; +import pl.psobiech.opengr8on.util.IPv4AddressUtil; +import pl.psobiech.opengr8on.util.SocketUtil.Payload; +import pl.psobiech.opengr8on.util.HexUtil; + +public class LuaScriptCommand { + public static final String CHECK_ALIVE = "checkAlive()"; + + private LuaScriptCommand() { + // NOP + } + + public static Request request(Inet4Address ipAddress, Integer sessionId, String script) { + return new Request( + ipAddress, sessionId, script + ); + } + + public static Optional requestFromByteArray(byte[] buffer) { + if (!requestMatches(buffer)) { + return Optional.empty(); + } + + final String[] requestParts = Command.asString(buffer).split(":", 4); + final Inet4Address ipAddress = IPv4AddressUtil.parseIPv4(requestParts[1]); + final Integer sessionId = HexUtil.asInt(requestParts[2]); + final String script = requestParts[3]; + + return Optional.of( + new Request( + ipAddress, + sessionId, + script + ) + ); + } + + public static boolean requestMatches(byte[] buffer) { + if (buffer.length < Request.COMMAND.length() + 1 + Command.MIN_IP_SIZE + 1 + Command.MIN_SESSION_SIZE + 1 + 1 /* script */) { + return false; + } + + if (buffer[Request.COMMAND.length()] != ':') { + return false; + } + + return Request.COMMAND.equals( + Command.asString(buffer, 0, Request.COMMAND.length()) + ); + } + + public static Response response(Inet4Address ipAddress, int sessionId, String returnValue) { + return new Response( + ipAddress, sessionId, returnValue + ); + } + + public static Optional parse(Integer sessionId, Payload payload) { + final Optional responseOptional = responseFromByteArray(payload.buffer()); + if (responseOptional.isEmpty()) { + return Optional.empty(); + } + + final Response response = responseOptional.get(); + if (!sessionId.equals(response.sessionId)) { + return Optional.empty(); + } + + return Optional.of( + responseOptional.get().returnValue + ); + } + + public static Optional responseFromByteArray(byte[] buffer) { + if (!responseMatches(buffer)) { + return Optional.empty(); + } + + final String[] responseParts = Command.asString(buffer).split(":", 4); + final Inet4Address ipAddress = IPv4AddressUtil.parseIPv4(responseParts[1]); + final Integer sessionId = HexUtil.asInt(responseParts[2]); + final String returnValue = responseParts[3]; + + return Optional.of( + new Response( + ipAddress, + sessionId, + returnValue + ) + ); + } + + public static boolean responseMatches(byte[] buffer) { + if (buffer.length < Response.COMMAND.length() + 1 + Command.MIN_IP_SIZE + 1 + Command.MIN_SESSION_SIZE + 1 + 1 /* script */) { + return false; + } + + if (buffer[Response.COMMAND.length()] != ':') { + return false; + } + + return Response.COMMAND.equals( + Command.asString(buffer, 0, Response.COMMAND.length()) + ); + } + + public static class Request implements Command { + static final String COMMAND = "req"; + + private final Inet4Address ipAddress; + + private final Integer sessionId; + + private final String script; + + private Request(Inet4Address ipAddress, Integer sessionId, String script) { + this.ipAddress = ipAddress; + this.sessionId = sessionId; + this.script = script; + } + + @Override + public byte[] asByteArray() { + return Command.serialize( + COMMAND, + ":", + ipAddress, + ":", + StringUtils.leftPad(StringUtils.lowerCase(HexUtil.asString(sessionId)), 8, '0'), + ":", + script + "\r\n" + ); + } + + public Inet4Address getIpAddress() { + return ipAddress; + } + + public Integer getSessionId() { + return sessionId; + } + + public String getScript() { + return script; + } + } + + public static class Response implements Command { + static final String COMMAND = "resp"; + + private final Inet4Address ipAddress; + + private final Integer sessionId; + + private final String returnValue; + + private Response(Inet4Address ipAddress, Integer sessionId, String returnValue) { + this.ipAddress = ipAddress; + this.sessionId = sessionId; + this.returnValue = returnValue; + } + + @Override + public byte[] asByteArray() { + return Command.serialize( + COMMAND, + ":", + ipAddress, + ":", + StringUtils.leftPad(StringUtils.lowerCase(HexUtil.asString(sessionId)), 8, '0'), + ":", + returnValue + ); + } + + public Inet4Address getIpAddress() { + return ipAddress; + } + + public Integer getSessionId() { + return sessionId; + } + + public String getReturnValue() { + return returnValue; + } + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/client/commands/ResetCommand.java b/lib/src/main/java/pl/psobiech/opengr8on/client/commands/ResetCommand.java new file mode 100644 index 0000000..a4d6a08 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/client/commands/ResetCommand.java @@ -0,0 +1,154 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.commands; + +import java.net.Inet4Address; +import java.util.Optional; + +import pl.psobiech.opengr8on.client.Command; +import pl.psobiech.opengr8on.util.IPv4AddressUtil; +import pl.psobiech.opengr8on.util.Util; + +public class ResetCommand { + private ResetCommand() { + // NOP + } + + public static Request request(Inet4Address ipAddress) { + return new Request(ipAddress); + } + + public static Optional requestFromByteArray(byte[] buffer) { + if (!requestMatches(buffer)) { + return Optional.empty(); + } + + final Optional requestPartsOptional = Util.splitExact(Command.asString(buffer), ":", 2); + if (requestPartsOptional.isEmpty()) { + return Optional.empty(); + } + + final String[] requestParts = requestPartsOptional.get(); + final Inet4Address ipAddress = IPv4AddressUtil.parseIPv4(requestParts[1]); + + return Optional.of( + new Request( + ipAddress + ) + ); + } + + public static boolean requestMatches(byte[] buffer) { + if (buffer.length < Request.COMMAND.length() + 1 + Command.MIN_IP_SIZE) { + return false; + } + + if (buffer[Request.COMMAND.length()] != ':') { + return false; + } + + return Request.COMMAND.equals( + Command.asString(buffer, 0, Request.COMMAND.length()) + ); + } + + public static Response response(Inet4Address ipAddress) { + return new Response(ipAddress); + } + + public static Optional responseFromByteArray(byte[] buffer) { + if (!responseMatches(buffer)) { + return Optional.empty(); + } + + final Optional responsePartsOptional = Util.splitExact(Command.asString(buffer), ":", 2); + if (responsePartsOptional.isEmpty()) { + return Optional.empty(); + } + + final String[] responseParts = responsePartsOptional.get(); + final Inet4Address localAddress = IPv4AddressUtil.parseIPv4(responseParts[1]); + + return Optional.of( + new Response( + localAddress + ) + ); + } + + public static boolean responseMatches(byte[] buffer) { + if (buffer.length < Response.COMMAND.length() + 1 + Command.MIN_IP_SIZE) { + return false; + } + + if (buffer[Response.COMMAND.length()] != ':') { + return false; + } + + return Response.COMMAND.equals( + Command.asString(buffer, 0, Response.COMMAND.length()) + ); + } + + public static class Request implements Command { + protected static final String COMMAND = "req_reset"; + + private final Inet4Address ipAddress; + + private Request(Inet4Address ipAddress) { + this.ipAddress = ipAddress; + } + + @Override + public byte[] asByteArray() { + return Command.serialize( + COMMAND, + ":", + ipAddress + ); + } + + public Inet4Address getIpAddress() { + return ipAddress; + } + } + + public static class Response implements Command { + protected static final String COMMAND = "resp_reset"; + + private final Inet4Address ipAddress; + + private Response(Inet4Address ipAddress) { + this.ipAddress = ipAddress; + } + + @Override + public byte[] asByteArray() { + return Command.serialize( + COMMAND, + ":", + ipAddress + ); + } + + public Inet4Address getIpAddress() { + return ipAddress; + } + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/client/commands/SetIpCommand.java b/lib/src/main/java/pl/psobiech/opengr8on/client/commands/SetIpCommand.java new file mode 100644 index 0000000..c4e11f6 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/client/commands/SetIpCommand.java @@ -0,0 +1,188 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.commands; + +import java.net.Inet4Address; +import java.util.Optional; + +import org.apache.commons.lang3.StringUtils; +import pl.psobiech.opengr8on.client.Command; +import pl.psobiech.opengr8on.util.HexUtil; +import pl.psobiech.opengr8on.util.IPv4AddressUtil; +import pl.psobiech.opengr8on.util.Util; + +public class SetIpCommand { + private SetIpCommand() { + // NOP + } + + public static Request request(Long serialNumber, Inet4Address ipAddress, Inet4Address gatewayIpAddress) { + return new Request(serialNumber, ipAddress, gatewayIpAddress); + } + + public static Optional requestFromByteArray(byte[] buffer) { + if (!requestMatches(buffer)) { + return Optional.empty(); + } + + final Optional requestPartsOptional = Util.splitExact(Command.asString(buffer), ":", 4); + if (requestPartsOptional.isEmpty()) { + return Optional.empty(); + } + + final String[] requestParts = requestPartsOptional.get(); + final Long serialNumber = HexUtil.asLong(requestParts[1]); + final Inet4Address ipAddress = IPv4AddressUtil.parseIPv4(requestParts[2]); + final Inet4Address gatewayIpAddress = IPv4AddressUtil.parseIPv4(requestParts[3]); + + return Optional.of( + new Request( + serialNumber, + ipAddress, gatewayIpAddress + ) + ); + } + + public static boolean requestMatches(byte[] buffer) { + if (buffer.length < Request.COMMAND.length() + 1 + Command.MIN_SERIAL_NUMBER_SIZE + 1 + Command.MIN_IP_SIZE + 1 + Command.MIN_IP_SIZE) { + return false; + } + + if (buffer[Request.COMMAND.length()] != ':') { + return false; + } + + return Request.COMMAND.equals( + Command.asString(buffer, 0, Request.COMMAND.length()) + ); + } + + public static Response response(Long serialNumber, Inet4Address ipAddress) { + return new Response(serialNumber, ipAddress); + } + + public static Optional responseFromByteArray(byte[] buffer) { + if (!responseMatches(buffer)) { + return Optional.empty(); + } + + final Optional responsePartsOptional = Util.splitExact(Command.asString(buffer), ":", 3); + if (responsePartsOptional.isEmpty()) { + return Optional.empty(); + } + + final String[] responseParts = responsePartsOptional.get(); + final Long serialNumber = HexUtil.asLong(responseParts[1]); + final Inet4Address ipAddress = IPv4AddressUtil.parseIPv4(responseParts[2]); + + return Optional.of( + new Response( + serialNumber, + ipAddress + ) + ); + } + + public static boolean responseMatches(byte[] buffer) { + if (buffer.length < Response.COMMAND.length() + 1 + Command.MIN_SERIAL_NUMBER_SIZE + 1 + Command.MIN_IP_SIZE) { + return false; + } + + if (buffer[Response.COMMAND.length()] != ':') { + return false; + } + + return Response.COMMAND.equals( + Command.asString(buffer, 0, Response.COMMAND.length()) + ); + } + + public static class Request implements Command { + protected static final String COMMAND = "req_set_clu_ip"; + + private final Long serialNumber; + + private final Inet4Address ipAddress; + + private final Inet4Address gatewayIpAddress; + + private Request(Long serialNumber, Inet4Address ipAddress, Inet4Address gatewayIpAddress) { + this.serialNumber = serialNumber; + this.ipAddress = ipAddress; + this.gatewayIpAddress = gatewayIpAddress; + } + + @Override + public byte[] asByteArray() { + return Command.serialize( + COMMAND, + ":", + StringUtils.lowerCase(HexUtil.asString(serialNumber)), + ":", + ipAddress, + ":", + gatewayIpAddress + ); + } + + public Long getSerialNumber() { + return serialNumber; + } + + public Inet4Address getIpAddress() { + return ipAddress; + } + + public Inet4Address getGatewayIpAddress() { + return gatewayIpAddress; + } + } + + public static class Response implements Command { + protected static final String COMMAND = "resp_set_clu_ip"; + + private final Long serialNumber; + + private final Inet4Address ipAddress; + + private Response(Long serialNumber, Inet4Address ipAddress) { + this.serialNumber = serialNumber; + this.ipAddress = ipAddress; + } + + @Override + public byte[] asByteArray() { + return Command.serialize( + COMMAND, + ":", + StringUtils.leftPad(StringUtils.lowerCase(HexUtil.asString(serialNumber)), 8, '0'), + ":", + ipAddress + ); + } + + public Long getSerialNumber() { + return serialNumber; + } + + public Inet4Address getIpAddress() { + return ipAddress; + } + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/client/commands/SetKeyCommand.java b/lib/src/main/java/pl/psobiech/opengr8on/client/commands/SetKeyCommand.java new file mode 100644 index 0000000..1347e43 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/client/commands/SetKeyCommand.java @@ -0,0 +1,160 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.commands; + +import java.util.Arrays; +import java.util.Optional; + +import pl.psobiech.opengr8on.client.Command; + +public class SetKeyCommand { + private static final Response RESPONSE = new Response(); + + private SetKeyCommand() { + // NOP + } + + public static Request request(byte[] encrypted, byte[] key, byte[] iv) { + return new Request(encrypted, key, iv); + } + + public static Optional requestFromByteArray(byte[] buffer) { + if (!requestMatches(buffer)) { + return Optional.empty(); + } + + final byte[] encrypted = Arrays.copyOf(buffer, Command.RANDOM_ENCRYPTED_SIZE); + final byte[] iv = Arrays.copyOfRange(buffer, Command.RANDOM_ENCRYPTED_SIZE + 1, Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.KEY_SIZE); + final byte[] key = Arrays.copyOfRange( + buffer, + Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1 + Request.COMMAND.length() + 1, + Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1 + Request.COMMAND.length() + 1 + Command.KEY_SIZE + ); + + return Optional.of( + new Request( + encrypted, + key, iv + ) + ); + } + + public static boolean requestMatches(byte[] buffer) { + if ( + buffer.length != Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1 + Request.COMMAND.length() + 1 + Command.KEY_SIZE + && buffer.length != Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1 + Request.COMMAND.length() + 1 + Command.KEY_SIZE + 2 /* \r\n */ + ) { + return false; + } + + if (buffer[Command.RANDOM_ENCRYPTED_SIZE] != ':' + || buffer[Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE] != ':' + || buffer[Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1 + Request.COMMAND.length()] != ':' + ) { + return false; + } + + return Request.COMMAND.equals( + Command.asString( + buffer, + Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1, + Request.COMMAND.length() + ) + ); + } + + public static Response response() { + return RESPONSE; + } + + public static Optional responseFromByteArray(byte[] buffer) { + if (!responseMatches(buffer)) { + return Optional.empty(); + } + + return Optional.of(RESPONSE); + } + + public static boolean responseMatches(byte[] buffer) { + if (buffer.length != Response.COMMAND.length() + && buffer.length != Response.COMMAND.length() + 2 /* \r\n */) { + return false; + } + + return Response.COMMAND.equals( + Command.asString(buffer, 0, Response.COMMAND.length()) + ); + } + + public static class Request implements Command { + static final String COMMAND = "req_set_key"; + + private final byte[] encrypted; + + private final byte[] key; + + private final byte[] iv; + + private Request(byte[] encrypted, byte[] key, byte[] iv) { + this.encrypted = encrypted; + this.key = key; + this.iv = iv; + } + + @Override + public byte[] asByteArray() { + return Command.serialize( + encrypted, + ":", + iv, + ":", + COMMAND, + ":", + key + ); + } + + public byte[] getEncrypted() { + return encrypted; + } + + public byte[] getKey() { + return key; + } + + public byte[] getIV() { + return iv; + } + } + + public static class Response implements Command { + static final String COMMAND = "resp:OK"; + + private Response() { + // NOP + } + + @Override + public byte[] asByteArray() { + return Command.serialize( + COMMAND + ); + } + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/client/commands/StartTFTPdCommand.java b/lib/src/main/java/pl/psobiech/opengr8on/client/commands/StartTFTPdCommand.java new file mode 100644 index 0000000..ce2e621 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/client/commands/StartTFTPdCommand.java @@ -0,0 +1,107 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.commands; + +import java.util.Optional; + +import pl.psobiech.opengr8on.client.Command; + +public class StartTFTPdCommand { + private static final Request REQUEST = new Request(); + + private static final Response RESPONSE = new Response(); + + private StartTFTPdCommand() { + // NOP + } + + public static Request request() { + return REQUEST; + } + + public static Optional requestFromByteArray(byte[] buffer) { + if (!requestMatches(buffer)) { + return Optional.empty(); + } + + return Optional.of(REQUEST); + } + + public static boolean requestMatches(byte[] buffer) { + if (buffer.length != Request.COMMAND.length() + && buffer.length != Request.COMMAND.length() + 2 /* \r\n */) { + return false; + } + + return Request.COMMAND.equals( + Command.asString(buffer, 0, Request.COMMAND.length()) + ); + } + + public static Response response() { + return RESPONSE; + } + + public static Optional responseFromByteArray(byte[] buffer) { + if (!responseMatches(buffer)) { + return Optional.empty(); + } + + return Optional.of(RESPONSE); + } + + public static boolean responseMatches(byte[] buffer) { + if (buffer.length != Response.COMMAND.length() + && buffer.length != Response.COMMAND.length() + 2 /* \r\n */) { + return false; + } + + return Response.COMMAND.equals( + Command.asString(buffer, 0, Response.COMMAND.length()) + ); + } + + public static class Request implements Command { + static final String COMMAND = "req_start_ftp"; + + private Request() { + // NOP + } + + @Override + public byte[] asByteArray() { + return Command.serialize(COMMAND); + } + } + + public static class Response implements Command { + static final String COMMAND = "resp:OK"; + + private Response() { + // NOP + } + + @Override + public byte[] asByteArray() { + return Command.serialize( + COMMAND + ); + } + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/client/device/CLUDevice.java b/lib/src/main/java/pl/psobiech/opengr8on/client/device/CLUDevice.java new file mode 100644 index 0000000..8d75374 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/client/device/CLUDevice.java @@ -0,0 +1,168 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.device; + +import java.net.Inet4Address; +import java.util.Objects; + +import pl.psobiech.opengr8on.client.CipherKey; +import pl.psobiech.opengr8on.util.ToStringUtil; +import pl.psobiech.opengr8on.util.Util; +import pl.psobiech.opengr8on.xml.interfaces.CLUClassNameEnum; + +public class CLUDevice { + private final String name; + + private final Long serialNumber; + + private final String macAddress; + + private final byte[] iv; + + private Inet4Address address; + + private final CipherTypeEnum cipherType; + + private final byte[] privateKey; + + private final CipherKey cipherKey; + + public CLUDevice(Inet4Address address, CipherTypeEnum cipherType) { + this( + null, null, address, + cipherType + ); + } + + public CLUDevice(Long serialNumber, String macAddress, Inet4Address address, CipherTypeEnum cipherType) { + this( + serialNumber, macAddress, address, + cipherType, + null, null + ); + } + + public CLUDevice(Long serialNumber, String macAddress, Inet4Address address, CipherTypeEnum cipherType, byte[] iv, byte[] privateKey) { + this( + Util.mapNullSafe(serialNumber, value -> CLUClassNameEnum.CLU.name() + value), + serialNumber, macAddress, address, + cipherType, + iv, privateKey + ); + } + + public CLUDevice(String name, Long serialNumber, String macAddress, Inet4Address address, CipherTypeEnum cipherType, byte[] iv, byte[] privateKey) { + this( + name, + serialNumber, macAddress, address, + cipherType, + iv, privateKey, + (iv != null && privateKey != null) ? CipherKey.getInitialCipherKey(iv, privateKey) : null + ); + } + + public CLUDevice( + String name, + Long serialNumber, String macAddress, Inet4Address address, + CipherTypeEnum cipherType, + byte[] iv, byte[] privateKey, + CipherKey cipherKey + ) { + this.name = name; + + this.serialNumber = serialNumber; + this.macAddress = macAddress; + this.address = address; + + this.cipherType = cipherType; + + this.iv = iv; + this.privateKey = privateKey; + + this.cipherKey = cipherKey; + } + + public String getName() { + return name; + } + + public Long getSerialNumber() { + return serialNumber; + } + + public String getMacAddress() { + return macAddress; + } + + public Inet4Address getAddress() { + return address; + } + + public CipherTypeEnum getCipherType() { + return cipherType; + } + + public byte[] getIv() { + return iv; + } + + public byte[] getPrivateKey() { + return privateKey; + } + + public CipherKey getCipherKey() { + return cipherKey; + } + + public void setAddress(Inet4Address address) { + this.address = address; + } + + @Override + public String toString() { + return "GrentonDevice{" + + "name=" + name + + ", serialNumber=" + ToStringUtil.toString(serialNumber) + + ", macAddress=" + macAddress + + ", address=" + ToStringUtil.toString(address) + + ", cipherType=" + cipherType + + ", iv=" + ToStringUtil.toString(iv) + + ", privateKey=" + ToStringUtil.toString(privateKey) + + ", cipherKey=" + cipherKey + + '}'; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (!(o instanceof final CLUDevice that)) { + return false; + } + + return Objects.equals(getSerialNumber(), that.getSerialNumber()); + } + + @Override + public int hashCode() { + return Objects.hash(getSerialNumber()); + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/client/device/CLUDeviceConfig.java b/lib/src/main/java/pl/psobiech/opengr8on/client/device/CLUDeviceConfig.java new file mode 100644 index 0000000..05fb85f --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/client/device/CLUDeviceConfig.java @@ -0,0 +1,69 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.device; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import pl.psobiech.opengr8on.util.Util; + +public class CLUDeviceConfig extends DeviceConfig { + @JsonProperty("mac") + private final String macAddress; + + @JsonProperty("tfbusDevices") + private final List tfBusDevices; + + @JsonCreator + public CLUDeviceConfig( + String serialNumber, + String macAddress, + int hardwareType, long hardwareVersion, + int firmwareType, int firmwareVersion, + String status, + List tfBusDevices + ) { + super( + serialNumber, + hardwareType, hardwareVersion, + firmwareType, firmwareVersion, + status + ); + + this.macAddress = Util.mapNullSafe(macAddress, value -> value.replaceAll(":", "")); + this.tfBusDevices = tfBusDevices; + } + + public String getMacAddress() { + return macAddress; + } + + public List getTFBusDevices() { + return tfBusDevices; + } + + @Override + public String toString() { + return "CLUDeviceConfig{" + + "macAddress=" + macAddress + + ", tfBusDevices=" + tfBusDevices + + "} " + super.toString(); + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/client/device/CipherTypeEnum.java b/lib/src/main/java/pl/psobiech/opengr8on/client/device/CipherTypeEnum.java new file mode 100644 index 0000000..fe42061 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/client/device/CipherTypeEnum.java @@ -0,0 +1,28 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.device; + +public enum CipherTypeEnum { + NONE, + PROJECT, + // + UNKNOWN, + // + ; +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/client/device/DeviceConfig.java b/lib/src/main/java/pl/psobiech/opengr8on/client/device/DeviceConfig.java new file mode 100644 index 0000000..b97d8df --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/client/device/DeviceConfig.java @@ -0,0 +1,95 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.device; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import pl.psobiech.opengr8on.util.ToStringUtil; +import pl.psobiech.opengr8on.util.Util; + +public class DeviceConfig { + @JsonProperty("sn") + protected final Long serialNumber; + + @JsonProperty("hwType") + protected final int hardwareType; + + @JsonProperty("hwVer") + protected final long hardwareVersion; + + @JsonProperty("fwType") + protected final int firmwareType; + + @JsonProperty("fwApiVer") + protected final int firmwareVersion; + + @JsonProperty("status") + protected final String status; + + @JsonCreator + public DeviceConfig( + String serialNumber, + int hardwareType, long hardwareVersion, + int firmwareType, int firmwareVersion, + String status + ) { + this.serialNumber = Util.mapNullSafe(serialNumber, value -> Long.parseLong(value, 10)); + this.hardwareType = hardwareType; + this.hardwareVersion = hardwareVersion; + this.firmwareType = firmwareType; + this.firmwareVersion = firmwareVersion; + this.status = status; + } + + public Long getSerialNumber() { + return serialNumber; + } + + public int getHardwareType() { + return hardwareType; + } + + public long getHardwareVersion() { + return hardwareVersion; + } + + public int getFirmwareType() { + return firmwareType; + } + + public int getFirmwareVersion() { + return firmwareVersion; + } + + public String getStatus() { + return status; + } + + @Override + public String toString() { + return "DeviceConfig{" + + "serialNumber=" + ToStringUtil.toString(serialNumber) + + ", hardwareType=" + ToStringUtil.toString(hardwareType) + + ", hardwareVersion=" + ToStringUtil.toString(hardwareVersion) + + ", firmwareType=" + ToStringUtil.toString(firmwareType) + + ", firmwareVersion=" + ToStringUtil.toString(firmwareVersion) + + ", status=" + status + + '}'; + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLU.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLU.java new file mode 100644 index 0000000..00ed875 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLU.java @@ -0,0 +1,101 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; + +@XmlAccessorType(XmlAccessType.FIELD) +public class CLU { + @JacksonXmlProperty(isAttribute = true) + private CLUClassNameEnum className; + + @JacksonXmlProperty(isAttribute = true) + private String firmwareType; + + @JacksonXmlProperty(isAttribute = true) + private String firmwareVersion; + + @JacksonXmlProperty(isAttribute = true) + private String hardwareType; + + @JacksonXmlProperty(isAttribute = true) + private String hardwareVersion; + + @JacksonXmlProperty(isAttribute = true) + private String typeName; + + @JsonProperty("interface") + private CLUInterface _interface; + + private List objects; + + private List modulesVersionConstraints; + + private List options; + + public CLUClassNameEnum getClassName() { + if (className == null) { + return CLUClassNameEnum.CLU; + } + + return className; + } + + public String getFirmwareType() { + return firmwareType; + } + + public String getFirmwareVersion() { + return firmwareVersion; + } + + public String getHardwareType() { + return hardwareType; + } + + public String getHardwareVersion() { + return hardwareVersion; + } + + public String getTypeName() { + return typeName; + } + + public CLUInterface getInterface() { + return _interface; + } + + public List getObjects() { + return objects; + } + + public List getModuleVersionConstraints() { + return modulesVersionConstraints; + } + + public List getOptions() { + return options; + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUClassNameEnum.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUClassNameEnum.java new file mode 100644 index 0000000..abf0122 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUClassNameEnum.java @@ -0,0 +1,26 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +public enum CLUClassNameEnum { + CLU, + GATE, + // + ; +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUDataTypeEnum.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUDataTypeEnum.java new file mode 100644 index 0000000..5387396 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUDataTypeEnum.java @@ -0,0 +1,51 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +import pl.psobiech.opengr8on.exceptions.UnexpectedException; + +public enum CLUDataTypeEnum { + VOID("void"), + NUMBER("num"), + STRING("str"), + BOOLEAN("confirmation"), + TIMESTAMP("timestamp"), + // + ; + + private final String type; + + CLUDataTypeEnum(String type) { + this.type = type; + } + + public String getType() { + return type; + } + + public static CLUDataTypeEnum of(String type) { + for (CLUDataTypeEnum value : values()) { + if (value.getType().equals(type)) { + return value; + } + } + + throw new UnexpectedException("Unsupported data type: " + type); + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUInterface.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUInterface.java new file mode 100644 index 0000000..33dd474 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUInterface.java @@ -0,0 +1,41 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +import java.util.List; + +public class CLUInterface { + private List features; + + private List methods; + + private List events; + + public List getFeatures() { + return features; + } + + public List getMethods() { + return methods; + } + + public List getEvents() { + return events; + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUInterfaceEvent.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUInterfaceEvent.java new file mode 100644 index 0000000..2c7c553 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUInterfaceEvent.java @@ -0,0 +1,43 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; + +public class CLUInterfaceEvent { + @JacksonXmlProperty(isAttribute = true) + private long address; + + @JacksonXmlProperty(isAttribute = true) + private String name; + + private Desc desc; + + public long getAddress() { + return address; + } + + public String getName() { + return name; + } + + public Desc getDesc() { + return desc; + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUInterfaceFeature.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUInterfaceFeature.java new file mode 100644 index 0000000..ab17113 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUInterfaceFeature.java @@ -0,0 +1,114 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; + +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; +import pl.psobiech.opengr8on.util.ObjectMapperFactory; + +@XmlAccessorType(XmlAccessType.FIELD) +public class CLUInterfaceFeature { + @JacksonXmlProperty(isAttribute = true) + private String name; + + @JacksonXmlProperty(isAttribute = true) + private String type; + + @JacksonXmlProperty(isAttribute = true) + private String unit; + + @JacksonXmlProperty(isAttribute = true, localName = "default") + private String _default; + + @JacksonXmlProperty(isAttribute = true) + private Boolean get; + + @JacksonXmlProperty(isAttribute = true) + private Boolean set; + + @JacksonXmlProperty(isAttribute = true) + private int index; + + @JsonIgnore + private List enumValues; + + @JsonIgnore + private List enums = new ArrayList<>(); + + private Desc desc; + + public String getName() { + return name; + } + + public CLUDataTypeEnum getType() { + return CLUDataTypeEnum.of(type); + } + + public String getUnit() { + return unit; + } + + public String getDefault() { + return _default; + } + + public Boolean getGet() { + return get; + } + + public Boolean getSet() { + return set; + } + + public int getIndex() { + return index; + } + + public List getEnumValues() { + return enumValues; + } + + public List getEnums() { + return enums; + } + + public String getResKey() { + return desc.getResKey(); + } + + @JsonAnySetter + public void setServices(String name, Object value) { + if (name.equals("enum")) { + if (value instanceof String) { + enumValues = List.of(((String) value).split(",+")); + } else if (value instanceof Map) { + enums.add(ObjectMapperFactory.XML.convertValue(value, CLUInterfaceFeatureEnum.class)); + } + } + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUInterfaceFeatureEnum.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUInterfaceFeatureEnum.java new file mode 100644 index 0000000..d4bde9a --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUInterfaceFeatureEnum.java @@ -0,0 +1,44 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; + +public class CLUInterfaceFeatureEnum { + @JacksonXmlProperty(isAttribute = true) + private String name; + + @JacksonXmlProperty(isAttribute = true) + private String resKey; + + @JacksonXmlProperty(isAttribute = true) + private int value; + + public String getName() { + return name; + } + + public String getResKey() { + return resKey; + } + + public int getValue() { + return value; + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUInterfaceMethod.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUInterfaceMethod.java new file mode 100644 index 0000000..9deed5a --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUInterfaceMethod.java @@ -0,0 +1,73 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +import java.util.List; + +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; + +public class CLUInterfaceMethod { + @JacksonXmlProperty(isAttribute = true) + private int index; + + @JacksonXmlProperty(isAttribute = true) + private String call; + + @JacksonXmlProperty(isAttribute = true) + private String name; + + @JacksonXmlProperty(isAttribute = true, localName = "return") + private String _return; + + @JacksonXmlProperty(isAttribute = true) + private String unit; + + @JacksonXmlProperty(localName = "param") + private List params; + + private Desc desc; + + public int getIndex() { + return index; + } + + public String getCall() { + return call; + } + + public String getName() { + return name; + } + + public CLUDataTypeEnum getReturn() { + return CLUDataTypeEnum.of(_return); + } + + public String getUnit() { + return unit; + } + + public List getParams() { + return params; + } + + public Desc getDesc() { + return desc; + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUInterfaceMethodParam.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUInterfaceMethodParam.java new file mode 100644 index 0000000..70c1cf8 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUInterfaceMethodParam.java @@ -0,0 +1,44 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; + +public class CLUInterfaceMethodParam { + @JacksonXmlProperty(isAttribute = true) + private String name; + + @JacksonXmlProperty(isAttribute = true) + private String range; + + @JacksonXmlProperty(isAttribute = true) + private String type; + + public String getName() { + return name; + } + + public String getRange() { + return range; + } + + public CLUDataTypeEnum getType() { + return CLUDataTypeEnum.of(type); + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUModule.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUModule.java new file mode 100644 index 0000000..aaca693 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUModule.java @@ -0,0 +1,43 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; + +@XmlAccessorType(XmlAccessType.FIELD) +public class CLUModule { + private String name; + + private String typeId; + + private ModuleFirmware firmware; + + public String getName() { + return name; + } + + public String getTypeId() { + return typeId; + } + + public ModuleFirmware getFirmware() { + return firmware; + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUModuleVersionConstraint.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUModuleVersionConstraint.java new file mode 100644 index 0000000..80aa513 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUModuleVersionConstraint.java @@ -0,0 +1,37 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; + +public class CLUModuleVersionConstraint { + @JacksonXmlProperty(isAttribute = true) + private String type; + + @JacksonXmlProperty(isAttribute = true) + private int version; + + public String getType() { + return type; + } + + public int getVersion() { + return version; + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUObject.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUObject.java new file mode 100644 index 0000000..0e61429 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUObject.java @@ -0,0 +1,72 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; + +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; + +@XmlAccessorType(XmlAccessType.FIELD) +public class CLUObject { + @JacksonXmlProperty(isAttribute = true, localName = "class") + private String _class; + + private String className; + + private String name; + + private String version; + + private List features; + + private List methods; + + private List events; + + public String getClazz() { + return _class; + } + + public String getClassName() { + return className; + } + + public String getName() { + return name; + } + + public String getVersion() { + return version; + } + + public List getFeatures() { + return features; + } + + public List getMethods() { + return methods; + } + + public List getEvents() { + return events; + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUObjectRestriction.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUObjectRestriction.java new file mode 100644 index 0000000..0e0c115 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUObjectRestriction.java @@ -0,0 +1,44 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; + +public class CLUObjectRestriction { + @JacksonXmlProperty(isAttribute = true) + private int maxInstances; + + @JacksonXmlProperty(isAttribute = true) + private String name; + + @JacksonXmlProperty(isAttribute = true) + private int version; + + public int getMaxInstances() { + return maxInstances; + } + + public String getName() { + return name; + } + + public int getVersion() { + return version; + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUOption.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUOption.java new file mode 100644 index 0000000..970acad --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/CLUOption.java @@ -0,0 +1,37 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; + +public class CLUOption { + @JacksonXmlProperty(isAttribute = true) + private String name; + + @JacksonXmlProperty(isAttribute = true) + private String value; + + public String getName() { + return name; + } + + public String getValue() { + return value; + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/Desc.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/Desc.java new file mode 100644 index 0000000..e16b31d --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/Desc.java @@ -0,0 +1,30 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; + +public class Desc { + @JacksonXmlProperty(isAttribute = true) + private String resKey; + + public String getResKey() { + return resKey; + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/InterfaceRegistry.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/InterfaceRegistry.java new file mode 100644 index 0000000..0643bb0 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/InterfaceRegistry.java @@ -0,0 +1,232 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; + +import com.fasterxml.jackson.databind.ObjectReader; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import pl.psobiech.opengr8on.exceptions.UnexpectedException; +import pl.psobiech.opengr8on.util.ObjectMapperFactory; +import pl.psobiech.opengr8on.util.HexUtil; + +public class InterfaceRegistry { + public static final InterfaceRegistry EMPTY = new InterfaceRegistry(); + + private static final String SEPARATOR = ":"; + + private static Logger LOGGER = LoggerFactory.getLogger(InterfaceRegistry.class); + + private final Map clus; + + private final Map modules; + + private final Map> objects; + + public InterfaceRegistry(Path rootPath) { + final List cluInterfaceFiles = new ArrayList<>(); + final List moduleInterfaceFiles = new ArrayList<>(); + final List objectInterfaceFiles = new ArrayList<>(); + + try { + Files.walkFileTree( + rootPath, + new SimpleFileVisitor<>() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + final String fileName = String.valueOf(file.getFileName()); + if (fileName.startsWith("clu_")) { + cluInterfaceFiles.add(file); + } else if (fileName.startsWith("module_")) { + moduleInterfaceFiles.add(file); + } else if (fileName.startsWith("object_")) { + objectInterfaceFiles.add(file); + } + + return super.visitFile(file, attrs); + } + } + ); + } catch (IOException e) { + throw new UnexpectedException(e); + } + + final Map clus = new TreeMap<>(String::compareTo); + final Map modules = new TreeMap<>(String::compareTo); + final Map> objects = new TreeMap<>(String::compareTo); + + final ObjectReader cluDefinitionReader = ObjectMapperFactory.XML.readerFor(CLU.class); + for (Path cluInterfaceFile : cluInterfaceFiles) { + try { + final CLU clu = cluDefinitionReader.readValue(cluInterfaceFile.toFile()); + final String cluKey = createCluKey(clu); + LOGGER.trace("Loaded: " + cluKey); + + clus.put(cluKey, clu); + } catch (IOException e) { + throw new UnexpectedException("Error loading " + cluInterfaceFile, e); + } + } + + final ObjectReader moduleDefinitionReader = ObjectMapperFactory.XML.readerFor(CLUModule.class); + for (Path moduleInterfaceFile : moduleInterfaceFiles) { + try { + final CLUModule module = moduleDefinitionReader.readValue(moduleInterfaceFile.toFile()); + final String moduleKey = createModuleKey(module); + LOGGER.trace("Loaded: " + moduleKey); + + modules.put(moduleKey, module); + } catch (IOException e) { + throw new UnexpectedException("Error loading " + moduleInterfaceFile, e); + } + } + + final ObjectReader objectDefinitionReader = ObjectMapperFactory.XML.readerFor(CLUObject.class); + for (Path objectInterfaceFile : objectInterfaceFiles) { + try { + final CLUObject object = objectDefinitionReader.readValue(objectInterfaceFile.toFile()); + final String name = object.getName(); + final String version = createObjectVersionKey(object.getVersion()); + + objects.computeIfAbsent(name, ignored -> new TreeMap<>(String::compareTo)) + .put(version, object); + + LOGGER.trace("Loaded: " + name + SEPARATOR + version); + } catch (IOException e) { + throw new UnexpectedException("Error loading " + objectInterfaceFile, e); + } + } + + int objectNumbers = 0; + final Set objectKeys = new HashSet<>(objects.keySet()); + for (String objectKey : objectKeys) { + final Map objectVersions = objects.get(objectKey); + objectNumbers += objectVersions.size(); + + objects.put(objectKey, Collections.unmodifiableMap(objectVersions)); + } + + this.clus = Collections.unmodifiableMap(clus); + this.modules = Collections.unmodifiableMap(modules); + this.objects = Collections.unmodifiableMap(objects); + + LOGGER.debug("Loaded Interfaces: clus: {}, modules: {}, objects: {}", this.clus.size(), this.modules.size(), objectNumbers); + } + + private InterfaceRegistry() { + this.clus = Collections.emptyMap(); + this.modules = Collections.emptyMap(); + this.objects = Collections.emptyMap(); + } + + public Optional getCLU(int hardwareType, long hardwareVersion, int firmwareType, int firmwareVersion) { + return Optional.ofNullable( + clus.get( + createCluKey(hardwareType, hardwareVersion, firmwareType, firmwareVersion) + ) + ); + } + + private static String createCluKey(CLU clu) { + return createCluKey( + HexUtil.asInt(clu.getHardwareType()), HexUtil.asLong(clu.getHardwareVersion()), + HexUtil.asInt(clu.getFirmwareType()), HexUtil.asInt(clu.getFirmwareVersion()) + ); + } + + private static String createCluKey( + int hardwareType, long hardwareVersion, + int firmwareType, int firmwareVersion + ) { + return createKey( + hardwareType & 0xFFFFFFFFL, hardwareVersion, + firmwareType, firmwareVersion + ); + } + + public Optional getModule(long hardwareType, int firmwareType, int firmwareVersion) { + return Optional.ofNullable( + modules.get( + createModuleKey( + hardwareType, + firmwareType, firmwareVersion + ) + ) + ); + } + + private static String createModuleKey(CLUModule clu) { + final ModuleFirmware firmware = clu.getFirmware(); + + return createModuleKey( + HexUtil.asLong(clu.getTypeId()), + HexUtil.asInt(firmware.getTypeId()), HexUtil.asInt(firmware.getVersion()) + ); + } + + private static String createModuleKey(long hardwareType, int firmwareType, int firmwareVersion) { + return "MOD" + SEPARATOR + createKey( + hardwareType, 1, + firmwareType, firmwareVersion + ); + } + + private static String createKey(long hardwareType, long hardwareVersion, int firmwareType, int firmwareVersion) { + return parse(hardwareType, 16) + SEPARATOR + parse(hardwareVersion, 16) + SEPARATOR + + parse(firmwareType, 8) + SEPARATOR + parse(firmwareVersion, 4); + } + + public Optional getObject(String name, int version) { + final Map objectVersions = objects.get(name); + if (objectVersions == null) { + return Optional.empty(); + } + + return Optional.ofNullable( + objectVersions.get(createObjectVersionKey(version)) + ); + } + + private static String createObjectVersionKey(String version) { + return createObjectVersionKey(HexUtil.asInt(version)); + } + + private static String createObjectVersionKey(int version) { + return parse(version, 2); + } + + private static String parse(long hexAsLong, int length) { + return StringUtils.leftPad(HexUtil.asString(hexAsLong), length, '0'); + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/ModuleFirmware.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/ModuleFirmware.java new file mode 100644 index 0000000..134f0ef --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/ModuleFirmware.java @@ -0,0 +1,48 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +import java.util.ArrayList; +import java.util.List; + +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; + +public class ModuleFirmware { + @JacksonXmlProperty(isAttribute = true) + private String typeId; + + @JacksonXmlProperty(isAttribute = true) + private String version; + + @JacksonXmlElementWrapper(useWrapping = false) + private List object = new ArrayList<>(); + + public String getTypeId() { + return typeId; + } + + public String getVersion() { + return version; + } + + public List getObject() { + return object; + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/ModuleObject.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/ModuleObject.java new file mode 100644 index 0000000..c39b97b --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/ModuleObject.java @@ -0,0 +1,38 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; + +public class ModuleObject { + @JacksonXmlProperty(isAttribute = true, localName = "class") + private String _class; + + @JacksonXmlProperty(isAttribute = true) + private String count; + + @JacksonXmlProperty(isAttribute = true) + private String name; + + @JacksonXmlProperty(isAttribute = true) + private String type; + + @JacksonXmlProperty(localName = "interface") + private CLUInterface _interface; +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/Value.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/Value.java new file mode 100644 index 0000000..36d8a4b --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/interfaces/Value.java @@ -0,0 +1,38 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.interfaces; + +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlText; + +public class Value { + @JacksonXmlProperty(isAttribute = true) + private Long id; + + @JacksonXmlText + private String value; + + public Long getId() { + return id; + } + + public String getValue() { + return value; + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/omp/OmpReader.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/omp/OmpReader.java new file mode 100644 index 0000000..d43e3c0 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/omp/OmpReader.java @@ -0,0 +1,65 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.omp; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Path; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import com.fasterxml.jackson.databind.ObjectReader; +import org.apache.commons.codec.binary.Base64; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import pl.psobiech.opengr8on.client.CipherKey; +import pl.psobiech.opengr8on.exceptions.UnexpectedException; +import pl.psobiech.opengr8on.util.ObjectMapperFactory; + +public class OmpReader { + private static final Logger LOGGER = LoggerFactory.getLogger(OmpReader.class); + + private static final String PROPERTIES_XML_FILE_NAME = "properties.xml"; + + private OmpReader() { + // NOP + } + + public static CipherKey readProjectCipherKey(Path projectFile) { + try (ZipFile zipFile = new ZipFile(projectFile.toFile())) { + final ZipEntry propertiesXmlEntry = zipFile.getEntry(PROPERTIES_XML_FILE_NAME); + try (InputStream inputStream = zipFile.getInputStream(propertiesXmlEntry)) { + final ObjectReader propertiesReader = ObjectMapperFactory.XML.readerFor(ProjectPropertiesWrapper.class); + final ProjectPropertiesWrapper projectPropertiesWrapper = propertiesReader.readValue(inputStream, ProjectPropertiesWrapper.class); + final ProjectProperties projectProperties = projectPropertiesWrapper.getProjectProperties(); + final ProjectPropertiesCipherKey projectCipherKey = projectProperties.getProjectCipherKey(); + + final CipherKey cipherKey = new CipherKey( + Base64.decodeBase64(projectCipherKey.getKeyBytes().getValue()), + Base64.decodeBase64(projectCipherKey.getIvBytes().getValue()) + ); + + LOGGER.debug("Loaded project key: {}", cipherKey); + return cipherKey; + } + } catch (IOException e) { + throw new UnexpectedException("Cannot load omp project from file: " + projectFile, e); + } + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/omp/ProjectProperties.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/omp/ProjectProperties.java new file mode 100644 index 0000000..ccd7d9a --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/omp/ProjectProperties.java @@ -0,0 +1,30 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.omp; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ProjectProperties { + @JsonProperty("projectCipherKey") + private ProjectPropertiesCipherKey projectCipherKey; + + public ProjectPropertiesCipherKey getProjectCipherKey() { + return projectCipherKey; + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/omp/ProjectPropertiesCipherKey.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/omp/ProjectPropertiesCipherKey.java new file mode 100644 index 0000000..691be60 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/omp/ProjectPropertiesCipherKey.java @@ -0,0 +1,38 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.omp; + +import com.fasterxml.jackson.annotation.JsonProperty; +import pl.psobiech.opengr8on.xml.interfaces.Value; + +public class ProjectPropertiesCipherKey { + @JsonProperty("keyBytes") + private Value keyBytes; + + @JsonProperty("ivBytes") + private Value ivBytes; + + public Value getKeyBytes() { + return keyBytes; + } + + public Value getIvBytes() { + return ivBytes; + } +} diff --git a/lib/src/main/java/pl/psobiech/opengr8on/xml/omp/ProjectPropertiesWrapper.java b/lib/src/main/java/pl/psobiech/opengr8on/xml/omp/ProjectPropertiesWrapper.java new file mode 100644 index 0000000..c462926 --- /dev/null +++ b/lib/src/main/java/pl/psobiech/opengr8on/xml/omp/ProjectPropertiesWrapper.java @@ -0,0 +1,30 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.xml.omp; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ProjectPropertiesWrapper { + @JsonProperty("ProjectProperties") + private ProjectProperties projectProperties; + + public ProjectProperties getProjectProperties() { + return projectProperties; + } +} diff --git a/lib/src/test/java/pl/psobiech/opengr8on/client/CipherKeyTest.java b/lib/src/test/java/pl/psobiech/opengr8on/client/CipherKeyTest.java new file mode 100644 index 0000000..7174105 --- /dev/null +++ b/lib/src/test/java/pl/psobiech/opengr8on/client/CipherKeyTest.java @@ -0,0 +1,50 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client; + +import org.apache.commons.codec.binary.Base64; +import org.junit.jupiter.api.Test; +import pl.psobiech.opengr8on.util.RandomUtil; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +class CipherKeyTest { + @Test + void generateDefaultKey() { + final byte[] expected = Base64.decodeBase64("+O7WsrhYluaV4tufuyTgVw=="); + final byte[] actual = CipherKey.generateDefaultKey("AA55AA55".getBytes()); + + assertArrayEquals(expected, actual); + } + + @Test + void sane() { + final CipherKey cipherKey = Mocks.cipherKey(); + final byte[] expected = RandomUtil.bytes(30); + + // + + final byte[] actual = cipherKey.decrypt( + cipherKey.encrypt(expected) + ) + .get(); + + assertArrayEquals(expected, actual); + } +} \ No newline at end of file diff --git a/lib/src/test/java/pl/psobiech/opengr8on/client/Mocks.java b/lib/src/test/java/pl/psobiech/opengr8on/client/Mocks.java new file mode 100644 index 0000000..e766a74 --- /dev/null +++ b/lib/src/test/java/pl/psobiech/opengr8on/client/Mocks.java @@ -0,0 +1,59 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client; + +import java.net.Inet4Address; + +import pl.psobiech.opengr8on.util.IPv4AddressUtil; +import pl.psobiech.opengr8on.util.RandomUtil; +import pl.psobiech.opengr8on.util.HexUtil; + +public class Mocks { + private Mocks() { + // NOP + } + + public static CipherKey cipherKey() { + return new CipherKey(key(), iv()); + } + + public static byte[] key() { + return RandomUtil.bytes(16); + } + + public static byte[] iv() { + return RandomUtil.bytes(16); + } + + public static Inet4Address ipAddress() { + final int ipAsNumber = IPv4AddressUtil.getIPv4AsNumber("192.168.31.1"); + + return IPv4AddressUtil.parseIPv4( + ipAsNumber + RandomUtil.random(false).nextInt(255) + ); + } + + public static Long serialNumber() { + return HexUtil.asLong(RandomUtil.hexString(8)); + } + + public static Integer sessionId() { + return HexUtil.asInt(RandomUtil.hexString(8)); + } +} diff --git a/lib/src/test/java/pl/psobiech/opengr8on/client/commands/DiscoverCLUsTest.java b/lib/src/test/java/pl/psobiech/opengr8on/client/commands/DiscoverCLUsTest.java new file mode 100644 index 0000000..92c6154 --- /dev/null +++ b/lib/src/test/java/pl/psobiech/opengr8on/client/commands/DiscoverCLUsTest.java @@ -0,0 +1,257 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.commands; + +import java.net.Inet4Address; +import java.util.Map; +import java.util.Optional; + +import org.apache.commons.codec.binary.Base64; +import org.junit.jupiter.api.Test; +import pl.psobiech.opengr8on.client.CipherKey; +import pl.psobiech.opengr8on.client.Command; +import pl.psobiech.opengr8on.client.Mocks; +import pl.psobiech.opengr8on.client.commands.DiscoverCLUsCommand.Request; +import pl.psobiech.opengr8on.client.commands.DiscoverCLUsCommand.Response; +import pl.psobiech.opengr8on.client.device.CLUDevice; +import pl.psobiech.opengr8on.client.device.CipherTypeEnum; +import pl.psobiech.opengr8on.util.HexUtil; +import pl.psobiech.opengr8on.util.RandomUtil; +import pl.psobiech.opengr8on.util.SocketUtil.Payload; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static pl.psobiech.opengr8on.client.commands.DiscoverCLUsCommand.parse; +import static pl.psobiech.opengr8on.client.commands.DiscoverCLUsCommand.request; +import static pl.psobiech.opengr8on.client.commands.DiscoverCLUsCommand.response; + +class DiscoverCLUsTest { + @Test + void hash() { + final byte[] input = Base64.decodeBase64("dAp8ZAQI3fde2qg7AeXbe1ZJNZkaIzPcGGieBnTW"); + final byte[] expected = Base64.decodeBase64("ouqoyvvchxjk/wADCMGqutS84CNQM7aAxLoIPyTf"); + + // + + final byte[] actual = DiscoverCLUsCommand.hash(input); + + // + + assertArrayEquals(expected, actual); + } + + @Test + void parseProjectCipherKey() { + final CipherKey cipherKey = Mocks.cipherKey(); + + final byte[] privateKey = "00000000".getBytes(); + final CipherKey cluCipherKey = CipherKey.getInitialCipherKey(cipherKey.getIV(), privateKey); + + final Inet4Address ipAddress = Mocks.ipAddress(); + + final byte[] randomBytes = RandomUtil.bytes(Command.RANDOM_SIZE); + + final long serialNumber = Mocks.serialNumber(); + final String macAddress = RandomUtil.hexString(12); + + final Response input = response( + cluCipherKey.encrypt(DiscoverCLUsCommand.hash(randomBytes)), cipherKey.getIV(), + serialNumber, macAddress + ); + + // + + final CLUDevice cluDevice = parse( + randomBytes, + Payload.of(ipAddress, 404, input.asByteArray()), + Map.of( + serialNumber, privateKey + ) + ) + .get(); + + // + + assertEquals(ipAddress, cluDevice.getAddress()); + assertArrayEquals(cipherKey.getIV(), cluDevice.getIv()); + assertEquals(serialNumber, cluDevice.getSerialNumber()); + assertEquals(macAddress, cluDevice.getMacAddress()); + assertEquals(CipherTypeEnum.PROJECT, cluDevice.getCipherType()); + assertEquals(cluCipherKey, cluDevice.getCipherKey()); + assertArrayEquals(privateKey, cluDevice.getPrivateKey()); + } + + @Test + void parseUnknownCipherKey() { + final CipherKey cipherKey = Mocks.cipherKey(); + + final byte[] privateKey = "00000000".getBytes(); + final CipherKey cluCipherKey = CipherKey.getInitialCipherKey(cipherKey.getIV(), privateKey); + + final Inet4Address ipAddress = Mocks.ipAddress(); + + final byte[] randomBytes = RandomUtil.bytes(Command.RANDOM_SIZE); + + final long serialNumber = Mocks.serialNumber(); + final String macAddress = RandomUtil.hexString(12); + + final Response input = response( + cipherKey.encrypt(DiscoverCLUsCommand.hash(randomBytes)), cipherKey.getIV(), + serialNumber, macAddress + ); + + // + + final CLUDevice cluDevice = parse( + randomBytes, + Payload.of(ipAddress, 404, input.asByteArray()), + Map.of( + serialNumber, privateKey + ) + ) + .get(); + + // + + assertEquals(ipAddress, cluDevice.getAddress()); + assertArrayEquals(cipherKey.getIV(), cluDevice.getIv()); + assertEquals(serialNumber, cluDevice.getSerialNumber()); + assertEquals(macAddress, cluDevice.getMacAddress()); + assertEquals(CipherTypeEnum.NONE, cluDevice.getCipherType()); + assertEquals(cluCipherKey, cluDevice.getCipherKey()); + assertArrayEquals(privateKey, cluDevice.getPrivateKey()); + } + + @Test + void parseUnknownPrivateKey() { + final CipherKey cipherKey = Mocks.cipherKey(); + + final Inet4Address ipAddress = Mocks.ipAddress(); + + final byte[] randomBytes = RandomUtil.bytes(Command.RANDOM_SIZE); + + final long serialNumber = Mocks.serialNumber(); + final String macAddress = RandomUtil.hexString(12); + + final Response input = response( + cipherKey.encrypt(DiscoverCLUsCommand.hash(randomBytes)), cipherKey.getIV(), + serialNumber, macAddress + ); + + // + + final CLUDevice cluDevice = parse( + randomBytes, + Payload.of(ipAddress, 404, input.asByteArray()), + Map.of() + ) + .get(); + + // + + assertEquals(ipAddress, cluDevice.getAddress()); + assertArrayEquals(cipherKey.getIV(), cluDevice.getIv()); + assertEquals(serialNumber, cluDevice.getSerialNumber()); + assertEquals(macAddress, cluDevice.getMacAddress()); + assertEquals(CipherTypeEnum.UNKNOWN, cluDevice.getCipherType()); + assertNull(cluDevice.getCipherKey()); + assertNull(cluDevice.getPrivateKey()); + } + + @Test + void parseInvalid() { + final Inet4Address ipAddress = Mocks.ipAddress(); + + final byte[] randomBytes = RandomUtil.bytes(Command.RANDOM_SIZE); + + final Payload payload = Payload.of(ipAddress, 404, new byte[0]); + + // + + final Optional optional = parse(randomBytes, payload, Map.of()); + + // + + assertFalse(optional.isPresent()); + } + + @Test + void correctRequest() { + final Request input = request( + RandomUtil.bytes(32), RandomUtil.bytes(16), Mocks.ipAddress() + ); + + // + + final Request output = DiscoverCLUsCommand.requestFromByteArray(input.asByteArray()) + .get(); + + // + + assertArrayEquals(input.asByteArray(), output.asByteArray()); + } + + @Test + void correctResponse() { + final Response input = response( + RandomUtil.bytes(32), RandomUtil.bytes(16), + HexUtil.asLong(RandomUtil.hexString(8)), RandomUtil.hexString(12) + ); + + // + + final Response output = DiscoverCLUsCommand.responseFromByteArray(input.asByteArray()) + .get(); + + // + + assertArrayEquals(input.asByteArray(), output.asByteArray()); + } + + @Test + void invalid() { + byte[] buffer; + + // + + assertFalse(DiscoverCLUsCommand.requestFromByteArray(new byte[0]).isPresent()); + assertFalse(DiscoverCLUsCommand.requestFromByteArray(new byte[100]).isPresent()); + + buffer = new byte[100]; + buffer[Command.RANDOM_ENCRYPTED_SIZE] = ':'; + buffer[Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE] = ':'; + buffer[Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1 + Request.COMMAND.length()] = ':'; + buffer[Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1 + Request.COMMAND.length() + 1 + Command.MIN_SERIAL_NUMBER_SIZE] = ':'; + assertFalse(DiscoverCLUsCommand.requestFromByteArray(buffer).isPresent()); + + // + + assertFalse(DiscoverCLUsCommand.responseFromByteArray(new byte[0]).isPresent()); + assertFalse(DiscoverCLUsCommand.responseFromByteArray(new byte[100]).isPresent()); + + buffer = new byte[100]; + buffer[Command.RANDOM_ENCRYPTED_SIZE] = ':'; + buffer[Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE] = ':'; + buffer[Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1 + Response.COMMAND.length()] = ':'; + buffer[Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1 + Response.COMMAND.length() + 1 + Command.MIN_SERIAL_NUMBER_SIZE] = ':'; + assertFalse(DiscoverCLUsCommand.responseFromByteArray(buffer).isPresent()); + } +} diff --git a/lib/src/test/java/pl/psobiech/opengr8on/client/commands/ErrorCommandTest.java b/lib/src/test/java/pl/psobiech/opengr8on/client/commands/ErrorCommandTest.java new file mode 100644 index 0000000..068bfd3 --- /dev/null +++ b/lib/src/test/java/pl/psobiech/opengr8on/client/commands/ErrorCommandTest.java @@ -0,0 +1,55 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.commands; + +import org.junit.jupiter.api.Test; +import pl.psobiech.opengr8on.client.commands.ErrorCommand.Response; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +class ErrorCommandTest { + @Test + void correctResponse() { + final Response input = ErrorCommand.response(); + + // + + final Response output = ErrorCommand.responseFromByteArray(input.asByteArray()) + .get(); + + // + + assertArrayEquals(input.asByteArray(), output.asByteArray()); + } + + @Test + void invalid() { + byte[] buffer; + + // + + assertFalse(ErrorCommand.responseFromByteArray(new byte[0]).isPresent()); + assertFalse(ErrorCommand.responseFromByteArray(new byte[Response.COMMAND.length()]).isPresent()); + + buffer = new byte[100]; + buffer["resp".length()] = ':'; + assertFalse(ErrorCommand.responseFromByteArray(buffer).isPresent()); + } +} diff --git a/lib/src/test/java/pl/psobiech/opengr8on/client/commands/LuaScriptCommandTest.java b/lib/src/test/java/pl/psobiech/opengr8on/client/commands/LuaScriptCommandTest.java new file mode 100644 index 0000000..d437bab --- /dev/null +++ b/lib/src/test/java/pl/psobiech/opengr8on/client/commands/LuaScriptCommandTest.java @@ -0,0 +1,121 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.commands; + +import java.net.Inet4Address; +import java.util.Arrays; + +import org.junit.jupiter.api.Test; +import pl.psobiech.opengr8on.client.Command; +import pl.psobiech.opengr8on.client.commands.LuaScriptCommand.Request; +import pl.psobiech.opengr8on.client.commands.LuaScriptCommand.Response; +import pl.psobiech.opengr8on.util.SocketUtil.Payload; +import pl.psobiech.opengr8on.client.Mocks; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +class LuaScriptCommandTest { + @Test + void parsePayload() { + final Inet4Address ipAddress = Mocks.ipAddress(); + final Integer sessionId = Mocks.sessionId(); + final String expectedReturnValue = "nil"; + + final Response input = LuaScriptCommand.response( + ipAddress, sessionId, expectedReturnValue + ); + + // + + final String returnValue = LuaScriptCommand.parse( + sessionId, + Payload.of(ipAddress, 404, input.asByteArray()) + ) + .get(); + + // + + assertEquals(expectedReturnValue, returnValue); + } + + @Test + void correctRequest() { + final Request input = LuaScriptCommand.request( + Mocks.ipAddress(), Mocks.sessionId(), LuaScriptCommand.CHECK_ALIVE + ); + + // + + final Request output = LuaScriptCommand.requestFromByteArray(input.asByteArray()) + .get(); + + // + + assertArrayEquals(input.asByteArray(), output.asByteArray()); + assertArrayEquals( + "\r\n".getBytes(), + Arrays.copyOfRange(output.asByteArray(), output.asByteArray().length - 2, output.asByteArray().length) + ); + } + + @Test + void correctResponse() { + final Response input = LuaScriptCommand.response( + Mocks.ipAddress(), Mocks.sessionId(), "nil" + ); + + // + + final Response output = LuaScriptCommand.responseFromByteArray(input.asByteArray()) + .get(); + + // + + assertArrayEquals(input.asByteArray(), output.asByteArray()); + } + + @Test + void invalid() { + byte[] buffer; + + // + + assertFalse(LuaScriptCommand.requestFromByteArray(new byte[0]).isPresent()); + assertFalse(LuaScriptCommand.requestFromByteArray(new byte[100]).isPresent()); + + buffer = new byte[100]; + buffer[Request.COMMAND.length()] = ':'; + buffer[Request.COMMAND.length() + 1 + Command.MIN_IP_SIZE] = ':'; + buffer[Request.COMMAND.length() + 1 + Command.MIN_IP_SIZE + 1 + Command.MIN_SESSION_SIZE] = ':'; + assertFalse(LuaScriptCommand.requestFromByteArray(buffer).isPresent()); + + // + + assertFalse(LuaScriptCommand.responseFromByteArray(new byte[0]).isPresent()); + assertFalse(LuaScriptCommand.responseFromByteArray(new byte[100]).isPresent()); + + buffer = new byte[100]; + buffer[Response.COMMAND.length()] = ':'; + buffer[Response.COMMAND.length() + 1 + Command.MIN_IP_SIZE] = ':'; + buffer[Response.COMMAND.length() + 1 + Command.MIN_IP_SIZE + 1 + Command.MIN_SESSION_SIZE] = ':'; + assertFalse(LuaScriptCommand.responseFromByteArray(buffer).isPresent()); + } +} diff --git a/lib/src/test/java/pl/psobiech/opengr8on/client/commands/ResetCommandTest.java b/lib/src/test/java/pl/psobiech/opengr8on/client/commands/ResetCommandTest.java new file mode 100644 index 0000000..703b0ff --- /dev/null +++ b/lib/src/test/java/pl/psobiech/opengr8on/client/commands/ResetCommandTest.java @@ -0,0 +1,84 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.commands; + +import org.junit.jupiter.api.Test; +import pl.psobiech.opengr8on.client.commands.ResetCommand.Request; +import pl.psobiech.opengr8on.client.commands.ResetCommand.Response; +import pl.psobiech.opengr8on.client.Mocks; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +class ResetCommandTest { + @Test + void correctRequest() { + final Request input = ResetCommand.request( + Mocks.ipAddress() + ); + + // + + final Request output = ResetCommand.requestFromByteArray(input.asByteArray()) + .get(); + + // + + assertArrayEquals(input.asByteArray(), output.asByteArray()); + } + + @Test + void correctResponse() { + final Response input = ResetCommand.response( + Mocks.ipAddress() + ); + + // + + final Response output = ResetCommand.responseFromByteArray(input.asByteArray()) + .get(); + + // + + assertArrayEquals(input.asByteArray(), output.asByteArray()); + } + + @Test + void invalid() { + byte[] buffer; + + // + + assertFalse(ResetCommand.requestFromByteArray(new byte[0]).isPresent()); + assertFalse(ResetCommand.requestFromByteArray(new byte[100]).isPresent()); + + buffer = new byte[100]; + buffer[Request.COMMAND.length()] = ':'; + assertFalse(ResetCommand.requestFromByteArray(buffer).isPresent()); + + // + + assertFalse(ResetCommand.responseFromByteArray(new byte[0]).isPresent()); + assertFalse(ResetCommand.responseFromByteArray(new byte[100]).isPresent()); + + buffer = new byte[100]; + buffer[Response.COMMAND.length()] = ':'; + assertFalse(ResetCommand.responseFromByteArray(buffer).isPresent()); + } +} diff --git a/lib/src/test/java/pl/psobiech/opengr8on/client/commands/SetIpCommandTest.java b/lib/src/test/java/pl/psobiech/opengr8on/client/commands/SetIpCommandTest.java new file mode 100644 index 0000000..64712b1 --- /dev/null +++ b/lib/src/test/java/pl/psobiech/opengr8on/client/commands/SetIpCommandTest.java @@ -0,0 +1,90 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.commands; + +import org.junit.jupiter.api.Test; +import pl.psobiech.opengr8on.client.Command; +import pl.psobiech.opengr8on.client.commands.SetIpCommand.Request; +import pl.psobiech.opengr8on.client.commands.SetIpCommand.Response; +import pl.psobiech.opengr8on.client.Mocks; +import pl.psobiech.opengr8on.util.HexUtil; +import pl.psobiech.opengr8on.util.RandomUtil; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +class SetIpCommandTest { + @Test + void correctRequest() { + final Request input = SetIpCommand.request( + HexUtil.asLong(RandomUtil.hexString(8)), Mocks.ipAddress(), Mocks.ipAddress() + ); + + // + + final Request output = SetIpCommand.requestFromByteArray(input.asByteArray()) + .get(); + + // + + assertArrayEquals(input.asByteArray(), output.asByteArray()); + } + + @Test + void correctResponse() { + final Response input = SetIpCommand.response( + HexUtil.asLong(RandomUtil.hexString(8)), Mocks.ipAddress() + ); + + // + + final Response output = SetIpCommand.responseFromByteArray(input.asByteArray()) + .get(); + + // + + assertArrayEquals(input.asByteArray(), output.asByteArray()); + } + + @Test + void invalid() { + byte[] buffer; + + // + + assertFalse(SetIpCommand.requestFromByteArray(new byte[0]).isPresent()); + assertFalse(SetIpCommand.requestFromByteArray(new byte[100]).isPresent()); + + buffer = new byte[100]; + buffer[Request.COMMAND.length()] = ':'; + buffer[Request.COMMAND.length() + 1 + Command.MIN_SERIAL_NUMBER_SIZE] = ':'; + buffer[Request.COMMAND.length() + 1 + Command.MIN_SERIAL_NUMBER_SIZE + 1 + Command.MIN_IP_SIZE] = ':'; + assertFalse(SetIpCommand.requestFromByteArray(buffer).isPresent()); + + // + + assertFalse(SetIpCommand.responseFromByteArray(new byte[0]).isPresent()); + assertFalse(SetIpCommand.responseFromByteArray(new byte[100]).isPresent()); + + buffer = new byte[100]; + buffer[Response.COMMAND.length()] = ':'; + buffer[Response.COMMAND.length() + 1 + Command.MIN_SERIAL_NUMBER_SIZE] = ':'; + assertFalse(SetIpCommand.responseFromByteArray(buffer).isPresent()); + } +} diff --git a/lib/src/test/java/pl/psobiech/opengr8on/client/commands/SetKeyCommandTest.java b/lib/src/test/java/pl/psobiech/opengr8on/client/commands/SetKeyCommandTest.java new file mode 100644 index 0000000..d34a5aa --- /dev/null +++ b/lib/src/test/java/pl/psobiech/opengr8on/client/commands/SetKeyCommandTest.java @@ -0,0 +1,85 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.commands; + +import org.junit.jupiter.api.Test; +import pl.psobiech.opengr8on.client.Command; +import pl.psobiech.opengr8on.client.commands.SetKeyCommand.Request; +import pl.psobiech.opengr8on.client.commands.SetKeyCommand.Response; +import pl.psobiech.opengr8on.util.RandomUtil; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +class SetKeyCommandTest { + @Test + void correctRequest() { + final Request input = SetKeyCommand.request( + RandomUtil.bytes(32), RandomUtil.bytes(16), RandomUtil.bytes(16) + ); + + // + + final Request output = SetKeyCommand.requestFromByteArray(input.asByteArray()) + .get(); + + // + + assertArrayEquals(input.asByteArray(), output.asByteArray()); + } + + @Test + void correctResponse() { + final Response input = SetKeyCommand.response(); + + // + + final Response output = SetKeyCommand.responseFromByteArray(input.asByteArray()) + .get(); + + // + + assertArrayEquals(input.asByteArray(), output.asByteArray()); + } + + @Test + void invalid() { + byte[] buffer; + + // + + assertFalse(SetKeyCommand.requestFromByteArray(new byte[0]).isPresent()); + assertFalse(SetKeyCommand.requestFromByteArray(new byte[100]).isPresent()); + + buffer = new byte[100]; + buffer[Command.RANDOM_ENCRYPTED_SIZE] = ':'; + buffer[Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE] = ':'; + buffer[Command.RANDOM_ENCRYPTED_SIZE + 1 + Command.IV_SIZE + 1 + Request.COMMAND.length()] = ':'; + assertFalse(SetKeyCommand.requestFromByteArray(buffer).isPresent()); + + // + + assertFalse(SetKeyCommand.responseFromByteArray(new byte[0]).isPresent()); + assertFalse(SetKeyCommand.responseFromByteArray(new byte[100]).isPresent()); + + buffer = new byte[100]; + buffer[Response.COMMAND.length()] = ':'; + assertFalse(SetKeyCommand.responseFromByteArray(buffer).isPresent()); + } +} diff --git a/lib/src/test/java/pl/psobiech/opengr8on/client/commands/StartTFTPdTest.java b/lib/src/test/java/pl/psobiech/opengr8on/client/commands/StartTFTPdTest.java new file mode 100644 index 0000000..a471381 --- /dev/null +++ b/lib/src/test/java/pl/psobiech/opengr8on/client/commands/StartTFTPdTest.java @@ -0,0 +1,75 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.client.commands; + +import org.junit.jupiter.api.Test; +import pl.psobiech.opengr8on.client.commands.StartTFTPdCommand.Request; +import pl.psobiech.opengr8on.client.commands.StartTFTPdCommand.Response; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +class StartTFTPdTest { + @Test + void correctRequest() { + final Request input = StartTFTPdCommand.request(); + + // + + final Request output = StartTFTPdCommand.requestFromByteArray(input.asByteArray()) + .get(); + + // + + assertArrayEquals(input.asByteArray(), output.asByteArray()); + } + + @Test + void correctResponse() { + final Response input = StartTFTPdCommand.response(); + + // + + final Response output = StartTFTPdCommand.responseFromByteArray(input.asByteArray()) + .get(); + + // + + assertArrayEquals(input.asByteArray(), output.asByteArray()); + } + + @Test + void invalid() { + byte[] buffer; + + // + + assertFalse(StartTFTPdCommand.requestFromByteArray(new byte[0]).isPresent()); + assertFalse(StartTFTPdCommand.requestFromByteArray(new byte[Request.COMMAND.length()]).isPresent()); + + // + + assertFalse(StartTFTPdCommand.responseFromByteArray(new byte[0]).isPresent()); + assertFalse(StartTFTPdCommand.responseFromByteArray(new byte[Response.COMMAND.length()]).isPresent()); + + buffer = new byte[100]; + buffer["resp".length()] = ':'; + assertFalse(StartTFTPdCommand.responseFromByteArray(buffer).isPresent()); + } +} diff --git a/lib/src/test/resources/logback-test.xml b/lib/src/test/resources/logback-test.xml new file mode 100644 index 0000000..3af7c46 --- /dev/null +++ b/lib/src/test/resources/logback-test.xml @@ -0,0 +1,28 @@ + + + + + %date{"yyyy-MM-dd'T'HH:mm:ss,SSSXXX", UTC} [%level] %logger{15} - %message%n%xException{10} + + + + + + + diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..fccb9eb --- /dev/null +++ b/pom.xml @@ -0,0 +1,254 @@ + + + 4.0.0 + + pl.psobiech.opengr8on + parent + 1.0-SNAPSHOT + pom + + OpenGr8on Parent + + + tftp + lib + client + common + vclu + + + + 21 + 21 + + UTF-8 + + 1.0-SNAPSHOT + 2.22.0 + 1.3.4 + + + + + central + https://repo1.maven.org/maven2 + + + github + https://maven.pkg.github.com/psobiech/opengr8on + + true + + + + + + + github + https://maven.pkg.github.com/psobiech/opengr8on + + + + + + + pl.psobiech.opengr8on + tftp + ${project.version} + + + + pl.psobiech.opengr8on + common + ${project.version} + + + + pl.psobiech.opengr8on + lib + ${project.version} + + + + pl.psobiech.opengr8on + vclu + ${project.version} + + + + org.slf4j + slf4j-api + 2.0.7 + + + ch.qos.logback + logback-classic + 1.4.12 + + + + + + + + + + + + + + + + + + + + + + commons-codec + commons-codec + 1.16.0 + + + org.apache.commons + commons-lang3 + 3.12.0 + + + + + + + + + + commons-net + commons-net + + 3.10.0 + + + + commons-cli + commons-cli + 1.6.0 + + + + javax.xml.bind + jaxb-api + 2.3.1 + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + 2.16.0 + + + com.fasterxml.jackson.module + jackson-module-parameter-names + 2.16.0 + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + 2.16.0 + + + + org.bouncycastle + bcprov-jdk18on + 1.77 + + + + io.jstach + jstachio + ${jstachio.version} + + + + org.junit.jupiter + junit-jupiter-api + 5.9.1 + test + + + org.junit.jupiter + junit-jupiter-engine + 5.9.1 + test + + + + + + + org.slf4j + slf4j-api + + + + commons-codec + commons-codec + + + org.apache.commons + commons-lang3 + + + + javax.xml.bind + jaxb-api + 2.3.1 + + + + org.junit.jupiter + junit-jupiter-api + + + org.junit.jupiter + junit-jupiter-engine + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + ${maven.compiler.source} + ${maven.compiler.target} + ${project.build.sourceEncoding} + + -parameters + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.2.2 + + + org.junit.jupiter + junit-jupiter-api + 5.9.1 + + + org.junit.jupiter + junit-jupiter-engine + 5.9.1 + + + + + + + \ No newline at end of file diff --git a/runtime/device-interfaces/clu_VIRTUAL_ft00000001_fv001_htaa55aa55_hv00000001.xml b/runtime/device-interfaces/clu_VIRTUAL_ft00000001_fv001_htaa55aa55_hv00000001.xml new file mode 100644 index 0000000..4be4bd4 --- /dev/null +++ b/runtime/device-interfaces/clu_VIRTUAL_ft00000001_fv001_htaa55aa55_hv00000001.xml @@ -0,0 +1,175 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runtime/device-interfaces/object_calendar_v1.xml b/runtime/device-interfaces/object_calendar_v1.xml new file mode 100644 index 0000000..4239686 --- /dev/null +++ b/runtime/device-interfaces/object_calendar_v1.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runtime/device-interfaces/object_event_scheduler_v1.xml b/runtime/device-interfaces/object_event_scheduler_v1.xml new file mode 100644 index 0000000..fb5d1b2 --- /dev/null +++ b/runtime/device-interfaces/object_event_scheduler_v1.xml @@ -0,0 +1,149 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runtime/device-interfaces/object_http_listener_v2.xml b/runtime/device-interfaces/object_http_listener_v2.xml new file mode 100644 index 0000000..e56e9a8 --- /dev/null +++ b/runtime/device-interfaces/object_http_listener_v2.xml @@ -0,0 +1,149 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runtime/device-interfaces/object_http_request_v2.xml b/runtime/device-interfaces/object_http_request_v2.xml new file mode 100644 index 0000000..fc2bb08 --- /dev/null +++ b/runtime/device-interfaces/object_http_request_v2.xml @@ -0,0 +1,204 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runtime/device-interfaces/object_scheduler_v1.xml b/runtime/device-interfaces/object_scheduler_v1.xml new file mode 100644 index 0000000..0835e85 --- /dev/null +++ b/runtime/device-interfaces/object_scheduler_v1.xml @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runtime/device-interfaces/object_sunrise_sunset_calendar_v3.xml b/runtime/device-interfaces/object_sunrise_sunset_calendar_v3.xml new file mode 100755 index 0000000..89c1ada --- /dev/null +++ b/runtime/device-interfaces/object_sunrise_sunset_calendar_v3.xml @@ -0,0 +1,196 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runtime/device-interfaces/object_timer_v1.xml b/runtime/device-interfaces/object_timer_v1.xml new file mode 100644 index 0000000..04b78b6 --- /dev/null +++ b/runtime/device-interfaces/object_timer_v1.xml @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runtime/root/a/CONFIG.JSON b/runtime/root/a/CONFIG.JSON new file mode 100644 index 0000000..b5efa46 --- /dev/null +++ b/runtime/root/a/CONFIG.JSON @@ -0,0 +1,12 @@ +{ + "sn": 0, + "mac": "0e:aa:55:aa:55:aa", + "hwType": -1437226411, + "hwVer": 1, + "fwType": 1, + "fwApiVer": 1, + "fwVer": "0.0.0-ALPHA", + "status": "OK", + "tfbusDevices": [], + "zwaveDevices": [] +} \ No newline at end of file diff --git a/runtime/root/a/MAIN.LUA b/runtime/root/a/MAIN.LUA new file mode 100644 index 0000000..79ed1b0 --- /dev/null +++ b/runtime/root/a/MAIN.LUA @@ -0,0 +1,20 @@ + +collectgarbage("collect") +require "user" + +collectgarbage("collect") +require "om" +collectgarbage("collect") + + +function checkAlive() + return "00000000" +end + +SYSTEM.Init() + + +repeat + SYSTEM.Loop() +until 1==2 + diff --git a/runtime/root/a/OM.LUA b/runtime/root/a/OM.LUA new file mode 100644 index 0000000..884c795 --- /dev/null +++ b/runtime/root/a/OM.LUA @@ -0,0 +1,33 @@ +-- FwType 00000001 +-- FwVersion 00000001 +-- HwType aa55aa55 +-- HwVersion 00000001 + +CLU0 = OBJECT:new(0, 0xC0A81F27, "CLU0") +-- NAME_CLU CLU0=CLU0 + + + +-- MODULES + +-- IO_MODULES + + +function setVar(name, value) + _G[name] = value +end + +function getVar(name) + return _G[name] +end + + + +function OnInit() + +-- INIT_CLU_OBJECTS +CLU0:set(14, 22) + +end + +CLU0:add_event(0, OnInit) diff --git a/runtime/root/a/SETTINGS.USR b/runtime/root/a/SETTINGS.USR new file mode 100644 index 0000000..e69de29 diff --git a/runtime/root/a/USER.LUA b/runtime/root/a/USER.LUA new file mode 100644 index 0000000..e69de29 diff --git a/runtime/root/a/config.txt b/runtime/root/a/config.txt new file mode 100644 index 0000000..7b11aa3 --- /dev/null +++ b/runtime/root/a/config.txt @@ -0,0 +1,7 @@ +00000000 +00000000 +0e:aa:55:aa:55:aa +00000001 +00000001 +aa55aa55 +00000001 diff --git a/runtime/root/a/meas.bin b/runtime/root/a/meas.bin new file mode 100644 index 0000000..1936c7b Binary files /dev/null and b/runtime/root/a/meas.bin differ diff --git a/tftp/pom.xml b/tftp/pom.xml new file mode 100644 index 0000000..1e8e4d3 --- /dev/null +++ b/tftp/pom.xml @@ -0,0 +1,26 @@ + + + 4.0.0 + + pl.psobiech.opengr8on + parent + 1.0-SNAPSHOT + + + tftp + + + + ch.qos.logback + logback-classic + test + + + + commons-net + commons-net + + + \ No newline at end of file diff --git a/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTP.java b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTP.java new file mode 100644 index 0000000..89691f1 --- /dev/null +++ b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTP.java @@ -0,0 +1,262 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package pl.psobiech.opengr8on.org.apache.commons.net; + +import java.io.IOException; +import java.io.InterruptedIOException; +import java.net.DatagramPacket; +import java.net.SocketException; +import java.time.Duration; + +import org.apache.commons.net.DatagramSocketClient; + +/** + * The TFTP class exposes a set of methods to allow you to deal with the TFTP protocol directly, in case you want to write your own TFTP client or server. + * However, almost every user should only be concerned with the {@link DatagramSocketClient#open open() }, and {@link DatagramSocketClient#close close() }, + * methods. Additionally,the a {@link DatagramSocketClient#setDefaultTimeout setDefaultTimeout() } method may be of importance for performance tuning. + *

+ * Details regarding the TFTP protocol and the format of TFTP packets can be found in RFC 783. But the point of these classes is to keep you from having to + * worry about the internals. + * + * @see DatagramSocketClient + * @see TFTPPacket + * @see TFTPPacketException + * @see TFTPClient + */ +public class TFTP extends DatagramSocketClient { + /** + * The ascii transfer mode. Its value is 0 and equivalent to NETASCII_MODE + */ + public static final int ASCII_MODE = 0; + + /** + * The netascii transfer mode. Its value is 0. + */ + public static final int NETASCII_MODE = 0; + + /** + * The binary transfer mode. Its value is 1 and equivalent to OCTET_MODE. + */ + public static final int BINARY_MODE = 1; + + /** + * The image transfer mode. Its value is 1 and equivalent to OCTET_MODE. + */ + public static final int IMAGE_MODE = 1; + + /** + * The octet transfer mode. Its value is 1. + */ + public static final int OCTET_MODE = 1; + + /** + * The default number of milliseconds to wait to receive a datagram before timing out. The default is 5,000 milliseconds (5 seconds). + * + * @deprecated Use {@link #DEFAULT_TIMEOUT_DURATION}. + */ + @Deprecated + public static final int DEFAULT_TIMEOUT = 5000; + + /** + * The default duration to wait to receive a datagram before timing out. The default is 5 seconds. + * + * @since 3.10.0 + */ + public static final Duration DEFAULT_TIMEOUT_DURATION = Duration.ofSeconds(5); + + /** + * The default TFTP port according to RFC 783 is 69. + */ + public static final int DEFAULT_PORT = 69; + + /** + * The size to use for TFTP packet buffers. Its 4 plus the TFTPPacket.SEGMENT_SIZE, i.e. 516. + */ + static final int PACKET_SIZE = TFTPPacket.SEGMENT_SIZE + 4; + + /** + * Returns the TFTP string representation of a TFTP transfer mode. Will throw an ArrayIndexOutOfBoundsException if an invalid transfer mode is specified. + * + * @param mode The TFTP transfer mode. One of the MODE constants. + * @return The TFTP string representation of the TFTP transfer mode. + */ + public static String getModeName(final int mode) { + return TFTPRequestPacket.modeStrings[mode]; + } + + /** + * A buffer used to accelerate receives in bufferedReceive() + */ + private byte[] receiveBuffer; + + /** + * A datagram used to minimize memory allocation in bufferedReceive() + */ + private DatagramPacket receiveDatagram; + + /** + * A datagram used to minimize memory allocation in bufferedSend() + */ + private DatagramPacket sendDatagram; + + /** + * A buffer used to accelerate sends in bufferedSend(). It is left package visible so that TFTPClient may be slightly more efficient during file sends. It + * saves the creation of an additional buffer and prevents a buffer copy in _newDataPcket(). + */ + byte[] sendBuffer; + + /** + * Creates a TFTP instance with a default timeout of {@link #DEFAULT_TIMEOUT_DURATION}, a null socket, and buffered operations disabled. + */ + public TFTP() { + setDefaultTimeout(DEFAULT_TIMEOUT_DURATION); + receiveBuffer = null; + receiveDatagram = null; + } + + /** + * Initializes the internal buffers. Buffers are used by {@link #bufferedSend bufferedSend() } and {@link #bufferedReceive bufferedReceive() }. This method + * must be called before calling either one of those two methods. When you finish using buffered operations, you must call + * {@link #endBufferedOps endBufferedOps() }. + */ + public final void beginBufferedOps() { + receiveBuffer = new byte[PACKET_SIZE]; + receiveDatagram = new DatagramPacket(receiveBuffer, receiveBuffer.length); + sendBuffer = new byte[PACKET_SIZE]; + sendDatagram = new DatagramPacket(sendBuffer, sendBuffer.length); + } + + /** + * This is a special method to perform a more efficient packet receive. It should only be used after calling {@link #beginBufferedOps beginBufferedOps() }. + * beginBufferedOps() initializes a set of buffers used internally that prevent the new allocation of a DatagramPacket and byte array for each send and + * receive. To use these buffers you must call the bufferedReceive() and bufferedSend() methods instead of send() and receive(). You must also be certain + * that you don't manipulate the resulting packet in such a way that it interferes with future buffered operations. For example, a TFTPDataPacket received + * with bufferedReceive() will have a reference to the internal byte buffer. You must finish using this data before calling bufferedReceive() again, or else + * the data will be overwritten by the call. + * + * @return The TFTPPacket received. + * @throws InterruptedIOException If a socket timeout occurs. The Java documentation claims an InterruptedIOException is thrown on a DatagramSocket timeout, + * but in practice we find a SocketException is thrown. You should catch both to be safe. + * @throws SocketException If a socket timeout occurs. The Java documentation claims an InterruptedIOException is thrown on a DatagramSocket timeout, but in + * practice we find a SocketException is thrown. You should catch both to be safe. + * @throws IOException If some other I/O error occurs. + * @throws TFTPPacketException If an invalid TFTP packet is received. + */ + public final TFTPPacket bufferedReceive() throws IOException, InterruptedIOException, SocketException, TFTPPacketException { + receiveDatagram.setData(receiveBuffer); + receiveDatagram.setLength(receiveBuffer.length); + checkOpen().receive(receiveDatagram); + + final TFTPPacket newTFTPPacket = TFTPPacket.newTFTPPacket(receiveDatagram); + trace("<", newTFTPPacket); + return newTFTPPacket; + } + + /** + * This is a special method to perform a more efficient packet send. It should only be used after calling {@link #beginBufferedOps beginBufferedOps() }. + * beginBufferedOps() initializes a set of buffers used internally that prevent the new allocation of a DatagramPacket and byte array for each send and + * receive. To use these buffers you must call the bufferedReceive() and bufferedSend() methods instead of send() and receive(). You must also be certain + * that you don't manipulate the resulting packet in such a way that it interferes with future buffered operations. For example, a TFTPDataPacket received + * with bufferedReceive() will have a reference to the internal byte buffer. You must finish using this data before calling bufferedReceive() again, or else + * the data will be overwritten by the call. + * + * @param packet The TFTP packet to send. + * @throws IOException If some I/O error occurs. + */ + public final void bufferedSend(final TFTPPacket packet) throws IOException { + trace(">", packet); + checkOpen().send(packet.newDatagram(sendDatagram, sendBuffer)); + } + + /** + * This method synchronizes a connection by discarding all packets that may be in the local socket buffer. This method need only be called when you + * implement your own TFTP client or server. + * + * @throws IOException if an I/O error occurs. + */ + public final void discardPackets() throws IOException { + final DatagramPacket datagram = new DatagramPacket(new byte[PACKET_SIZE], PACKET_SIZE); + final Duration to = getSoTimeoutDuration(); + setSoTimeout(Duration.ofMillis(1)); + try { + while (true) { + checkOpen().receive(datagram); + } + } catch (final SocketException | InterruptedIOException e) { + // Do nothing. We timed out, so we hope we're caught up. + } + setSoTimeout(to); + } + + /** + * Releases the resources used to perform buffered sends and receives. + */ + public final void endBufferedOps() { + receiveBuffer = null; + receiveDatagram = null; + sendBuffer = null; + sendDatagram = null; + } + + /** + * Receives a TFTPPacket. + * + * @return The TFTPPacket received. + * @throws InterruptedIOException If a socket timeout occurs. The Java documentation claims an InterruptedIOException is thrown on a DatagramSocket timeout, + * but in practice we find a SocketException is thrown. You should catch both to be safe. + * @throws SocketException If a socket timeout occurs. The Java documentation claims an InterruptedIOException is thrown on a DatagramSocket timeout, but in + * practice we find a SocketException is thrown. You should catch both to be safe. + * @throws IOException If some other I/O error occurs. + * @throws TFTPPacketException If an invalid TFTP packet is received. + */ + public final TFTPPacket receive() throws IOException, InterruptedIOException, SocketException, TFTPPacketException { + final DatagramPacket packet; + + packet = new DatagramPacket(new byte[PACKET_SIZE], PACKET_SIZE); + + checkOpen().receive(packet); + + final TFTPPacket newTFTPPacket = TFTPPacket.newTFTPPacket(packet); + trace("<", newTFTPPacket); + return newTFTPPacket; + } + + /** + * Sends a TFTP packet to its destination. + * + * @param packet The TFTP packet to send. + * @throws IOException If some I/O error occurs. + */ + public final void send(final TFTPPacket packet) throws IOException { + trace(">", packet); + checkOpen().send(packet.newDatagram()); + } + + /** + * Trace facility; this implementation does nothing. + *

+ * Override it to trace the data, for example:
{@code System.out.println(direction + " " + packet.toString());} + * + * @param direction {@code >} or {@code <} + * @param packet the packet to be sent or that has been received respectively + * @since 3.6 + */ + protected void trace(final String direction, final TFTPPacket packet) { + // NOP + } +} diff --git a/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPAckPacket.java b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPAckPacket.java new file mode 100644 index 0000000..89bc439 --- /dev/null +++ b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPAckPacket.java @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package pl.psobiech.opengr8on.org.apache.commons.net; + +import java.net.DatagramPacket; +import java.net.InetAddress; + +/** + * A final class derived from TFTPPacket defining the TFTP Acknowledgement packet type. + *

+ * Details regarding the TFTP protocol and the format of TFTP packets can be found in RFC 783. But the point of these classes is to keep you from having to + * worry about the internals. Additionally, only very few people should have to care about any of the TFTPPacket classes or derived classes. Almost all users + * should only be concerned with the {@link TFTPClient} class {@link TFTPClient#receiveFile receiveFile()} and {@link TFTPClient#sendFile sendFile()} methods. + * + * @see TFTPPacket + * @see TFTPPacketException + * @see TFTP + */ +public final class TFTPAckPacket extends TFTPPacket { + /** + * The block number being acknowledged by the packet. + */ + int blockNumber; + + /** + * Creates an acknowledgement packet based from a received datagram. Assumes the datagram is at least length 4, else an ArrayIndexOutOfBoundsException may + * be thrown. + * + * @param datagram The datagram containing the received acknowledgement. + * @throws TFTPPacketException If the datagram isn't a valid TFTP acknowledgement packet. + */ + TFTPAckPacket(final DatagramPacket datagram) throws TFTPPacketException { + super(ACKNOWLEDGEMENT, datagram.getAddress(), datagram.getPort()); + final byte[] data; + + data = datagram.getData(); + + if (getType() != data[1]) { + throw new TFTPPacketException("TFTP operator code does not match type."); + } + + this.blockNumber = (data[2] & 0xff) << 8 | data[3] & 0xff; + } + + /** + * Creates an acknowledgment packet to be sent to a host at a given port acknowledging receipt of a block. + * + * @param destination The host to which the packet is going to be sent. + * @param port The port to which the packet is going to be sent. + * @param blockNumber The block number being acknowledged. + */ + public TFTPAckPacket(final InetAddress destination, final int port, final int blockNumber) { + super(ACKNOWLEDGEMENT, destination, port); + this.blockNumber = blockNumber; + } + + /** + * Returns the block number of the acknowledgement. + * + * @return The block number of the acknowledgement. + */ + public int getBlockNumber() { + return blockNumber; + } + + /** + * Creates a UDP datagram containing all the TFTP acknowledgement packet data in the proper format. This is a method exposed to the programmer in case he + * wants to implement his own TFTP client instead of using the {@link TFTPClient} class. Under normal circumstances, you should not have a need to call this + * method. + * + * @return A UDP datagram containing the TFTP acknowledgement packet. + */ + @Override + public DatagramPacket newDatagram() { + final byte[] data; + + data = new byte[4]; + data[0] = 0; + data[1] = (byte) type; + data[2] = (byte) ((blockNumber & 0xffff) >> 8); + data[3] = (byte) (blockNumber & 0xff); + + return new DatagramPacket(data, data.length, address, port); + } + + /** + * This is a method only available within the package for implementing efficient datagram transport by eliminating buffering. It takes a datagram as an + * argument, and a byte buffer in which to store the raw datagram data. Inside the method, the data is set as the datagram's data and the datagram + * returned. + * + * @param datagram The datagram to create. + * @param data The buffer to store the packet and to use in the datagram. + * @return The datagram argument. + */ + @Override + DatagramPacket newDatagram(final DatagramPacket datagram, final byte[] data) { + data[0] = 0; + data[1] = (byte) type; + data[2] = (byte) ((blockNumber & 0xffff) >> 8); + data[3] = (byte) (blockNumber & 0xff); + + datagram.setAddress(address); + datagram.setPort(port); + datagram.setData(data); + datagram.setLength(4); + + return datagram; + } + + /** + * Sets the block number of the acknowledgement. + * + * @param blockNumber the number to set + */ + public void setBlockNumber(final int blockNumber) { + this.blockNumber = blockNumber; + } + + /** + * For debugging + * + * @since 3.6 + */ + @Override + public String toString() { + return super.toString() + " ACK " + blockNumber; + } +} diff --git a/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPClient.java b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPClient.java new file mode 100644 index 0000000..a464549 --- /dev/null +++ b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPClient.java @@ -0,0 +1,458 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package pl.psobiech.opengr8on.org.apache.commons.net; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InterruptedIOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.SocketException; +import java.net.UnknownHostException; + +import org.apache.commons.net.io.FromNetASCIIOutputStream; +import org.apache.commons.net.io.ToNetASCIIInputStream; + +/** + * The TFTPClient class encapsulates all the aspects of the TFTP protocol necessary to receive and send files through TFTP. It is derived from the {@link TFTP} + * because it is more convenient than using aggregation, and as a result exposes the same set of methods to allow you to deal with the TFTP protocol directly. + * However, almost every user should only be concerned with the the {@link org.apache.commons.net.DatagramSocketClient#open open() }, + * {@link org.apache.commons.net.DatagramSocketClient#close close() }, {@link #sendFile sendFile() }, and {@link #receiveFile receiveFile() } methods. + * Additionally, the {@link #setMaxTimeouts setMaxTimeouts() } and {@link org.apache.commons.net.DatagramSocketClient#setDefaultTimeout setDefaultTimeout() } + * methods may be of importance for performance tuning. + *

+ * Details regarding the TFTP protocol and the format of TFTP packets can be found in RFC 783. But the point of these classes is to keep you from having to + * worry about the internals. + * + * @see TFTP + * @see TFTPPacket + * @see TFTPPacketException + */ +public class TFTPClient extends TFTP { + /** + * The default number of times a {@code receive} attempt is allowed to timeout before ending attempts to retry the {@code receive} and failing. The default + * is 5 timeouts. + */ + public static final int DEFAULT_MAX_TIMEOUTS = 5; + + /** + * The maximum number of timeouts allowed before failing. + */ + private int maxTimeouts; + + /** + * The number of bytes received in the ongoing download. + */ + private long totalBytesReceived; + + /** + * The number of bytes sent in the ongoing upload. + */ + private long totalBytesSent; + + /** + * Creates a TFTPClient instance with a default timeout of DEFAULT_TIMEOUT, maximum timeouts value of DEFAULT_MAX_TIMEOUTS, a null socket, and buffered + * operations disabled. + */ + public TFTPClient() { + maxTimeouts = DEFAULT_MAX_TIMEOUTS; + } + + /** + * Returns the maximum number of times a {@code receive} attempt is allowed to timeout before ending attempts to retry the {@code receive} and failing. + * + * @return The maximum number of timeouts allowed. + */ + public int getMaxTimeouts() { + return maxTimeouts; + } + + /** + * @return The number of bytes received in the ongoing download + */ + public long getTotalBytesReceived() { + return totalBytesReceived; + } + + /** + * @return The number of bytes sent in the ongoing download + */ + public long getTotalBytesSent() { + return totalBytesSent; + } + + /** + * Same as calling receiveFile(fileName, mode, output, host, TFTP.DEFAULT_PORT). + * + * @param fileName The name of the file to receive. + * @param mode The TFTP mode of the transfer (one of the MODE constants). + * @param output The OutputStream to which the file should be written. + * @param host The remote host serving the file. + * @return number of bytes read + * @throws IOException If an I/O error occurs. The nature of the error will be reported in the message. + */ + public int receiveFile(final String fileName, final int mode, final OutputStream output, final InetAddress host) throws IOException { + return receiveFile(fileName, mode, output, host, DEFAULT_PORT); + } + + /** + * Requests a named file from a remote host, writes the file to an OutputStream, closes the connection, and returns the number of bytes read. A local UDP + * socket must first be created by {@link org.apache.commons.net.DatagramSocketClient#open open()} before invoking this method. This method will not close + * the OutputStream containing the file; you must close it after the method invocation. + * + * @param fileName The name of the file to receive. + * @param mode The TFTP mode of the transfer (one of the MODE constants). + * @param output The OutputStream to which the file should be written. + * @param host The remote host serving the file. + * @param port The port number of the remote TFTP server. + * @return number of bytes read + * @throws IOException If an I/O error occurs. The nature of the error will be reported in the message. + */ + public int receiveFile(final String fileName, final int mode, OutputStream output, InetAddress host, final int port) throws IOException { + int bytesRead = 0; + int lastBlock = 0; + int block = 1; + int hostPort = 0; + int dataLength = 0; + + totalBytesReceived = 0; + + if (mode == ASCII_MODE) { + output = new FromNetASCIIOutputStream(output); + } + + TFTPPacket sent = new TFTPReadRequestPacket(host, port, fileName, mode); + final TFTPAckPacket ack = new TFTPAckPacket(host, port, 0); + + beginBufferedOps(); + + boolean justStarted = true; + try { + do { // while more data to fetch + bufferedSend(sent); // start the fetch/send an ack + boolean wantReply = true; + int timeouts = 0; + do { // until successful response + try { + final TFTPPacket received = bufferedReceive(); + final int recdPort = received.getPort(); + final InetAddress recdAddress = received.getAddress(); + + // The first time we receive we get the port number and + // answering host address( for hosts with multiple IPs) + if (justStarted) { + justStarted = false; + //if (recdPort == port) { // must not use the control port here + // final TFTPErrorPacket + // error = new TFTPErrorPacket(recdAddress, recdPort, TFTPErrorPacket.UNKNOWN_TID, "INCORRECT SOURCE PORT"); + // bufferedSend(error); + // throw new IOException("Incorrect source port (" + recdPort + ") in request reply."); + //} + hostPort = recdPort; + ack.setPort(hostPort); + if (!host.equals(recdAddress)) { + host = recdAddress; + ack.setAddress(host); + sent.setAddress(host); + } + } + + // Comply with RFC 783 indication that an error acknowledgment + // should be sent to originator if unexpected TID or host. + if (host.equals(recdAddress) && recdPort == hostPort) { + switch (received.getType()) { + case TFTPPacket.ERROR: + TFTPErrorPacket error = (TFTPErrorPacket) received; + throw new TFTPPacketIOException(error.getError(), "Error code " + error.getError() + " received: " + error.getMessage()); + case TFTPPacket.DATA: + final TFTPDataPacket data = (TFTPDataPacket) received; + dataLength = data.getDataLength(); + lastBlock = data.getBlockNumber(); + + if (lastBlock == block) { // is the next block number? + try { + output.write(data.getData(), data.getDataOffset(), dataLength); + } catch (final IOException e) { + TFTPErrorPacket newError = new TFTPErrorPacket(host, hostPort, TFTPErrorPacket.OUT_OF_SPACE, "File write failed."); + bufferedSend(newError); + throw new TFTPPacketIOException(TFTPErrorPacket.OUT_OF_SPACE, e); + } + ++block; + if (block > 65535) { + // wrap the block number + block = 0; + } + wantReply = false; // got the next block, drop out to ack it + } else { // unexpected block number + discardPackets(); + if (lastBlock == (block == 0 ? 65535 : block - 1)) { + wantReply = false; // Resend last acknowledgement + } + } + break; + default: + throw new IOException("Received unexpected packet type (" + received.getType() + ")"); + } + } else { // incorrect host or TID + final TFTPErrorPacket error = new TFTPErrorPacket( + recdAddress, recdPort, + TFTPErrorPacket.UNKNOWN_TID, "Unexpected host or port." + ); + bufferedSend(error); + } + } catch (final SocketException | InterruptedIOException e) { + if (++timeouts >= maxTimeouts) { + throw new IOException("Connection timed out."); + } + } catch (final TFTPPacketException e) { + throw new IOException("Bad packet: " + e.getMessage()); + } + } while (wantReply); // waiting for response + + ack.setBlockNumber(lastBlock); + sent = ack; + bytesRead += dataLength; + totalBytesReceived += dataLength; + } while (dataLength == TFTPPacket.SEGMENT_SIZE); // not eof + bufferedSend(sent); // send the final ack + } finally { + endBufferedOps(); + } + return bytesRead; + } + + /** + * Same as calling receiveFile(fileName, mode, output, hostname, TFTP.DEFAULT_PORT). + * + * @param fileName The name of the file to receive. + * @param mode The TFTP mode of the transfer (one of the MODE constants). + * @param output The OutputStream to which the file should be written. + * @param hostname The name of the remote host serving the file. + * @return number of bytes read + * @throws IOException If an I/O error occurs. The nature of the error will be reported in the message. + * @throws UnknownHostException If the hostname cannot be resolved. + */ + public int receiveFile(final String fileName, final int mode, final OutputStream output, final String hostname) throws UnknownHostException, IOException { + return receiveFile(fileName, mode, output, InetAddress.getByName(hostname), DEFAULT_PORT); + } + + /** + * Requests a named file from a remote host, writes the file to an OutputStream, closes the connection, and returns the number of bytes read. A local UDP + * socket must first be created by {@link org.apache.commons.net.DatagramSocketClient#open open()} before invoking this method. This method will not close + * the OutputStream containing the file; you must close it after the method invocation. + * + * @param fileName The name of the file to receive. + * @param mode The TFTP mode of the transfer (one of the MODE constants). + * @param output The OutputStream to which the file should be written. + * @param hostname The name of the remote host serving the file. + * @param port The port number of the remote TFTP server. + * @return number of bytes read + * @throws IOException If an I/O error occurs. The nature of the error will be reported in the message. + * @throws UnknownHostException If the hostname cannot be resolved. + */ + public int receiveFile(final String fileName, final int mode, final OutputStream output, final String hostname, final int port) + throws UnknownHostException, IOException { + return receiveFile(fileName, mode, output, InetAddress.getByName(hostname), port); + } + + /** + * Same as calling sendFile(fileName, mode, input, host, TFTP.DEFAULT_PORT). + * + * @param fileName The name the remote server should use when creating the file on its file system. + * @param mode The TFTP mode of the transfer (one of the MODE constants). + * @param input the input stream containing the data to be sent + * @param host The name of the remote host receiving the file. + * @throws IOException If an I/O error occurs. The nature of the error will be reported in the message. + * @throws UnknownHostException If the hostname cannot be resolved. + */ + public void sendFile(final String fileName, final int mode, final InputStream input, final InetAddress host) throws IOException { + sendFile(fileName, mode, input, host, DEFAULT_PORT); + } + + /** + * Requests to send a file to a remote host, reads the file from an InputStream, sends the file to the remote host, and closes the connection. A local UDP + * socket must first be created by {@link org.apache.commons.net.DatagramSocketClient#open open()} before invoking this method. This method will not close + * the InputStream containing the file; you must close it after the method invocation. + * + * @param fileName The name the remote server should use when creating the file on its file system. + * @param mode The TFTP mode of the transfer (one of the MODE constants). + * @param input the input stream containing the data to be sent + * @param host The remote host receiving the file. + * @param port The port number of the remote TFTP server. + * @throws IOException If an I/O error occurs. The nature of the error will be reported in the message. + */ + public void sendFile(final String fileName, final int mode, InputStream input, InetAddress host, final int port) throws IOException { + int block = 0; + int hostPort = 0; + boolean justStarted = true; + boolean lastAckWait = false; + + totalBytesSent = 0L; + + if (mode == ASCII_MODE) { + input = new ToNetASCIIInputStream(input); + } + + TFTPPacket sent = new TFTPWriteRequestPacket(host, port, fileName, mode); + final TFTPDataPacket data = new TFTPDataPacket(host, port, 0, sendBuffer, 4, 0); + + beginBufferedOps(); + + try { + do { // until eof + // first time: block is 0, lastBlock is 0, send a request packet. + // subsequent: block is integer starting at 1, send data packet. + bufferedSend(sent); + boolean wantReply = true; + int timeouts = 0; + do { + try { + final TFTPPacket received = bufferedReceive(); + final InetAddress recdAddress = received.getAddress(); + final int recdPort = received.getPort(); + + // The first time we receive we get the port number and + // answering host address (for hosts with multiple IPs) + if (justStarted) { + justStarted = false; + //if (recdPort == port) { // must not use the control port here + // final TFTPErrorPacket + // error = new TFTPErrorPacket(recdAddress, recdPort, TFTPErrorPacket.UNKNOWN_TID, "INCORRECT SOURCE PORT"); + // bufferedSend(error); + // throw new IOException("Incorrect source port (" + recdPort + ") in request reply."); + //} + hostPort = recdPort; + data.setPort(hostPort); + if (!host.equals(recdAddress)) { + host = recdAddress; + data.setAddress(host); + sent.setAddress(host); + } + } + + // Comply with RFC 783 indication that an error acknowledgment + // should be sent to originator if unexpected TID or host. + if (host.equals(recdAddress) && recdPort == hostPort) { + switch (received.getType()) { + case TFTPPacket.ERROR: + final TFTPErrorPacket error = (TFTPErrorPacket) received; + throw new TFTPPacketIOException(error.getError(), "Error code " + error.getError() + " received: " + error.getMessage()); + case TFTPPacket.ACKNOWLEDGEMENT: + + final int lastBlock = ((TFTPAckPacket) received).getBlockNumber(); + + if (lastBlock == block) { + ++block; + if (block > 65535) { + // wrap the block number + block = 0; + } + wantReply = false; // got the ack we want + } else { + discardPackets(); + } + break; + default: + throw new IOException("Received unexpected packet type."); + } + } else { // wrong host or TID; send error + final TFTPErrorPacket error = new TFTPErrorPacket( + recdAddress, recdPort, + TFTPErrorPacket.UNKNOWN_TID, "Unexpected host or port." + ); + bufferedSend(error); + } + } catch (final SocketException | InterruptedIOException e) { + if (++timeouts >= maxTimeouts) { + throw new IOException("Connection timed out."); + } + } catch (final TFTPPacketException e) { + throw new IOException("Bad packet: " + e.getMessage()); + } + // retry until a good ack + } while (wantReply); + + if (lastAckWait) { + break; // we were waiting for this; now all done + } + + int dataLength = TFTPPacket.SEGMENT_SIZE; + int offset = 4; + int totalThisPacket = 0; + int bytesRead = 0; + while (dataLength > 0 && (bytesRead = input.read(sendBuffer, offset, dataLength)) > 0) { + offset += bytesRead; + dataLength -= bytesRead; + totalThisPacket += bytesRead; + } + if (totalThisPacket < TFTPPacket.SEGMENT_SIZE) { + /* this will be our last packet -- send, wait for ack, stop */ + lastAckWait = true; + } + data.setBlockNumber(block); + data.setData(sendBuffer, 4, totalThisPacket); + sent = data; + totalBytesSent += totalThisPacket; + } while (true); // loops until after lastAckWait is set + } finally { + endBufferedOps(); + } + } + + /** + * Same as calling sendFile(fileName, mode, input, hostname, TFTP.DEFAULT_PORT). + * + * @param fileName The name the remote server should use when creating the file on its file system. + * @param mode The TFTP mode of the transfer (one of the MODE constants). + * @param input the input stream containing the data to be sent + * @param hostname The name of the remote host receiving the file. + * @throws IOException If an I/O error occurs. The nature of the error will be reported in the message. + * @throws UnknownHostException If the hostname cannot be resolved. + */ + public void sendFile(final String fileName, final int mode, final InputStream input, final String hostname) throws UnknownHostException, IOException { + sendFile(fileName, mode, input, InetAddress.getByName(hostname), DEFAULT_PORT); + } + + /** + * Requests to send a file to a remote host, reads the file from an InputStream, sends the file to the remote host, and closes the connection. A local UDP + * socket must first be created by {@link org.apache.commons.net.DatagramSocketClient#open open()} before invoking this method. This method will not close + * the InputStream containing the file; you must close it after the method invocation. + * + * @param fileName The name the remote server should use when creating the file on its file system. + * @param mode The TFTP mode of the transfer (one of the MODE constants). + * @param input the input stream containing the data to be sent + * @param hostname The name of the remote host receiving the file. + * @param port The port number of the remote TFTP server. + * @throws IOException If an I/O error occurs. The nature of the error will be reported in the message. + * @throws UnknownHostException If the hostname cannot be resolved. + */ + public void sendFile(final String fileName, final int mode, final InputStream input, final String hostname, final int port) + throws UnknownHostException, IOException { + sendFile(fileName, mode, input, InetAddress.getByName(hostname), port); + } + + /** + * Sets the maximum number of times a {@code receive} attempt is allowed to timeout during a receiveFile() or sendFile() operation before ending attempts to + * retry the {@code receive} and failing. The default is DEFAULT_MAX_TIMEOUTS. + * + * @param numTimeouts The maximum number of timeouts to allow. Values less than 1 should not be used, but if they are, they are treated as 1. + */ + public void setMaxTimeouts(final int numTimeouts) { + maxTimeouts = Math.max(numTimeouts, 1); + } +} diff --git a/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPDataPacket.java b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPDataPacket.java new file mode 100644 index 0000000..afc3d53 --- /dev/null +++ b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPDataPacket.java @@ -0,0 +1,235 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package pl.psobiech.opengr8on.org.apache.commons.net; + +import java.net.DatagramPacket; +import java.net.InetAddress; + +/** + * A final class derived from TFTPPacket defining the TFTP Data packet type. + *

+ * Details regarding the TFTP protocol and the format of TFTP packets can be found in RFC 783. But the point of these classes is to keep you from having to + * worry about the internals. Additionally, only very few people should have to care about any of the TFTPPacket classes or derived classes. Almost all users + * should only be concerned with the {@link TFTPClient} class {@link TFTPClient#receiveFile receiveFile()} and {@link TFTPClient#sendFile sendFile()} methods. + * + * @see TFTPPacket + * @see TFTPPacketException + * @see TFTP + */ +public final class TFTPDataPacket extends TFTPPacket { + /** + * The maximum number of bytes in a TFTP data packet (512) + */ + public static final int MAX_DATA_LENGTH = 512; + + /** + * The minimum number of bytes in a TFTP data packet (0) + */ + public static final int MIN_DATA_LENGTH = 0; + + /** + * The block number of the packet. + */ + int blockNumber; + + /** + * The length of the data. + */ + private int length; + + /** + * The offset into the _data array at which the data begins. + */ + private int offset; + + /** + * The data stored in the packet. + */ + private byte[] data; + + /** + * Creates a data packet based from a received datagram. Assumes the datagram is at least length 4, else an ArrayIndexOutOfBoundsException may be thrown. + * + * @param datagram The datagram containing the received data. + * @throws TFTPPacketException If the datagram isn't a valid TFTP data packet. + */ + TFTPDataPacket(final DatagramPacket datagram) throws TFTPPacketException { + super(DATA, datagram.getAddress(), datagram.getPort()); + + this.data = datagram.getData(); + this.offset = 4; + + if (getType() != this.data[1]) { + throw new TFTPPacketException("TFTP operator code does not match type."); + } + + this.blockNumber = (this.data[2] & 0xff) << 8 | this.data[3] & 0xff; + + this.length = datagram.getLength() - 4; + + if (this.length > MAX_DATA_LENGTH) { + this.length = MAX_DATA_LENGTH; + } + } + + public TFTPDataPacket(final InetAddress destination, final int port, final int blockNumber, final byte[] data) { + this(destination, port, blockNumber, data, 0, data.length); + } + + /** + * Creates a data packet to be sent to a host at a given port with a given block number. The actual data to be sent is passed as an array, an offset, and a + * length. The offset is the offset into the byte array where the data starts. The length is the length of the data. If the length is greater than + * MAX_DATA_LENGTH, it is truncated. + * + * @param destination The host to which the packet is going to be sent. + * @param port The port to which the packet is going to be sent. + * @param blockNumber The block number of the data. + * @param data The byte array containing the data. + * @param offset The offset into the array where the data starts. + * @param length The length of the data. + */ + public TFTPDataPacket(final InetAddress destination, final int port, final int blockNumber, final byte[] data, final int offset, final int length) { + super(DATA, destination, port); + + this.blockNumber = blockNumber; + this.data = data; + this.offset = offset; + + this.length = Math.min(length, MAX_DATA_LENGTH); + } + + /** + * Returns the block number of the data packet. + * + * @return The block number of the data packet. + */ + public int getBlockNumber() { + return blockNumber; + } + + /** + * Returns the byte array containing the packet data. + * + * @return The byte array containing the packet data. + */ + public byte[] getData() { + return data; + } + + /** + * Returns the length of the data part of the data packet. + * + * @return The length of the data part of the data packet. + */ + public int getDataLength() { + return length; + } + + /** + * Returns the offset into the byte array where the packet data actually starts. + * + * @return The offset into the byte array where the packet data actually starts. + */ + public int getDataOffset() { + return offset; + } + + /** + * Creates a UDP datagram containing all the TFTP data packet data in the proper format. This is a method exposed to the programmer in case he wants to + * implement his own TFTP client instead of using the {@link TFTPClient} class. Under normal circumstances, you should not have a need to call this method. + * + * @return A UDP datagram containing the TFTP data packet. + */ + @Override + public DatagramPacket newDatagram() { + final byte[] data; + + data = new byte[length + 4]; + data[0] = 0; + data[1] = (byte) type; + data[2] = (byte) ((blockNumber & 0xffff) >> 8); + data[3] = (byte) (blockNumber & 0xff); + + System.arraycopy(this.data, offset, data, 4, length); + + return new DatagramPacket(data, length + 4, address, port); + } + + /** + * This is a method only available within the package for implementing efficient datagram transport by eliminating buffering. It takes a datagram as an + * argument, and a byte buffer in which to store the raw datagram data. Inside the method, the data is set as the datagram's data and the datagram + * returned. + * + * @param datagram The datagram to create. + * @param data The buffer to store the packet and to use in the datagram. + * @return The datagram argument. + */ + @Override + DatagramPacket newDatagram(final DatagramPacket datagram, final byte[] data) { + data[0] = 0; + data[1] = (byte) type; + data[2] = (byte) ((blockNumber & 0xffff) >> 8); + data[3] = (byte) (blockNumber & 0xff); + + // Double-check we're not the same + if (data != this.data) { + System.arraycopy(this.data, offset, data, 4, length); + } + + datagram.setAddress(address); + datagram.setPort(port); + datagram.setData(data); + datagram.setLength(length + 4); + + return datagram; + } + + /** + * Sets the block number of the data packet. + * + * @param blockNumber the number to set + */ + public void setBlockNumber(final int blockNumber) { + this.blockNumber = blockNumber; + } + + /** + * Sets the data for the data packet. + * + * @param data The byte array containing the data. + * @param offset The offset into the array where the data starts. + * @param length The length of the data. + */ + public void setData(final byte[] data, final int offset, final int length) { + this.data = data; + this.offset = offset; + this.length = length; + + this.length = Math.min(length, MAX_DATA_LENGTH); + } + + /** + * For debugging + * + * @since 3.6 + */ + @Override + public String toString() { + return super.toString() + " DATA " + blockNumber + " " + length; + } +} diff --git a/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPErrorPacket.java b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPErrorPacket.java new file mode 100644 index 0000000..f63707d --- /dev/null +++ b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPErrorPacket.java @@ -0,0 +1,222 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package pl.psobiech.opengr8on.org.apache.commons.net; + +import java.net.DatagramPacket; +import java.net.InetAddress; + +/** + * A final class derived from TFTPPacket defining the TFTP Error packet type. + *

+ * Details regarding the TFTP protocol and the format of TFTP packets can be found in RFC 783. But the point of these classes is to keep you from having to + * worry about the internals. Additionally, only very few people should have to care about any of the TFTPPacket classes or derived classes. Almost all users + * should only be concerned with the {@link TFTPClient} class {@link TFTPClient#receiveFile receiveFile()} and {@link TFTPClient#sendFile sendFile()} methods. + * + * @see TFTPPacket + * @see TFTPPacketException + * @see TFTP + */ +public final class TFTPErrorPacket extends TFTPPacket { + /** + * The undefined error code according to RFC 783, value 0. + */ + public static final int UNDEFINED = 0; + + /** + * The file not found error code according to RFC 783, value 1. + */ + public static final int FILE_NOT_FOUND = 1; + + /** + * The access violation error code according to RFC 783, value 2. + */ + public static final int ACCESS_VIOLATION = 2; + + /** + * The disk full error code according to RFC 783, value 3. + */ + public static final int OUT_OF_SPACE = 3; + + /** + * The illegal TFTP operation error code according to RFC 783, value 4. + */ + public static final int ILLEGAL_OPERATION = 4; + + /** + * The unknown transfer id error code according to RFC 783, value 5. + */ + public static final int UNKNOWN_TID = 5; + + /** + * The file already exists error code according to RFC 783, value 6. + */ + public static final int FILE_EXISTS = 6; + + /** + * The no such user error code according to RFC 783, value 7. + */ + public static final int NO_SUCH_USER = 7; + + /** + * The error code of this packet. + */ + private final int error; + + /** + * The error message of this packet. + */ + private final String message; + + /** + * Creates an error packet based from a received datagram. Assumes the datagram is at least length 4, else an ArrayIndexOutOfBoundsException may be thrown. + * + * @param datagram The datagram containing the received error. + * @throws TFTPPacketException If the datagram isn't a valid TFTP error packet. + */ + TFTPErrorPacket(final DatagramPacket datagram) throws TFTPPacketException { + super(ERROR, datagram.getAddress(), datagram.getPort()); + int index; + final int length; + final byte[] data; + final StringBuilder buffer; + + data = datagram.getData(); + length = datagram.getLength(); + + if (getType() != data[1]) { + throw new TFTPPacketException("TFTP operator code does not match type."); + } + + error = (data[2] & 0xff) << 8 | data[3] & 0xff; + + if (length < 5) { + throw new TFTPPacketException("Bad error packet. No message."); + } + + index = 4; + buffer = new StringBuilder(); + + while (index < length && data[index] != 0) { + buffer.append((char) data[index]); + ++index; + } + + message = buffer.toString(); + } + + /** + * Creates an error packet to be sent to a host at a given port with an error code and error message. + * + * @param destination The host to which the packet is going to be sent. + * @param port The port to which the packet is going to be sent. + * @param error The error code of the packet. + * @param message The error message of the packet. + */ + public TFTPErrorPacket(final InetAddress destination, final int port, final int error, final String message) { + super(ERROR, destination, port); + + this.error = error; + this.message = message; + } + + /** + * Returns the error code of the packet. + * + * @return The error code of the packet. + */ + public int getError() { + return error; + } + + /** + * Returns the error message of the packet. + * + * @return The error message of the packet. + */ + public String getMessage() { + return message; + } + + /** + * Creates a UDP datagram containing all the TFTP error packet data in the proper format. This is a method exposed to the programmer in case he wants to + * implement his own TFTP client instead of using the {@link TFTPClient} class. Under normal circumstances, you should not have a need to call this method. + * + * @return A UDP datagram containing the TFTP error packet. + */ + @Override + public DatagramPacket newDatagram() { + final byte[] data; + final int length; + + length = message.length(); + + data = new byte[length + 5]; + data[0] = 0; + data[1] = (byte) type; + data[2] = (byte) ((error & 0xffff) >> 8); + data[3] = (byte) (error & 0xff); + + System.arraycopy(message.getBytes(), 0, data, 4, length); + + data[length + 4] = 0; + + return new DatagramPacket(data, data.length, address, port); + } + + /** + * This is a method only available within the package for implementing efficient datagram transport by eliminating buffering. It takes a datagram as an + * argument, and a byte buffer in which to store the raw datagram data. Inside the method, the data is set as the datagram's data and the datagram + * returned. + * + * @param datagram The datagram to create. + * @param data The buffer to store the packet and to use in the datagram. + * @return The datagram argument. + */ + @Override + DatagramPacket newDatagram(final DatagramPacket datagram, final byte[] data) { + final int length; + + length = message.length(); + + data[0] = 0; + data[1] = (byte) type; + data[2] = (byte) ((error & 0xffff) >> 8); + data[3] = (byte) (error & 0xff); + + System.arraycopy(message.getBytes(), 0, data, 4, length); + + data[length + 4] = 0; + + datagram.setAddress(address); + datagram.setPort(port); + datagram.setData(data); + datagram.setLength(length + 4); + + return datagram; + } + + /** + * For debugging + * + * @since 3.6 + */ + @Override + public String toString() { + return super.toString() + " ERR " + error + " " + message; + } +} diff --git a/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPPacket.java b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPPacket.java new file mode 100644 index 0000000..d774f37 --- /dev/null +++ b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPPacket.java @@ -0,0 +1,203 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package pl.psobiech.opengr8on.org.apache.commons.net; + +import java.net.DatagramPacket; +import java.net.InetAddress; + +/** + * TFTPPacket is an abstract class encapsulating the functionality common to the 5 types of TFTP packets. It also provides a static factory method that will + * create the correct TFTP packet instance from a datagram. This can relieve the programmer from having to figure out what kind of TFTP packet is contained in a + * datagram and create it himself. + *

+ * Details regarding the TFTP protocol and the format of TFTP packets can be found in RFC 783. But the point of these classes is to keep you from having to + * worry about the internals. Additionally, only very few people should have to care about any of the TFTPPacket classes or derived classes. Almost all users + * should only be concerned with the {@link TFTPClient} class {@link TFTPClient#receiveFile receiveFile()} and {@link TFTPClient#sendFile sendFile()} methods. + * + * @see TFTPPacketException + * @see TFTP + */ +public abstract class TFTPPacket { + /** + * The minimum size of a packet. This is 4 bytes. It is enough to store the opcode and block number or other required data depending on the packet type. + */ + static final int MIN_PACKET_SIZE = 4; + + /** + * This is the actual TFTP spec identifier and is equal to 1. Identifier returned by {@link #getType getType()} indicating a read request packet. + */ + public static final int READ_REQUEST = 1; + + /** + * This is the actual TFTP spec identifier and is equal to 2. Identifier returned by {@link #getType getType()} indicating a write request packet. + */ + public static final int WRITE_REQUEST = 2; + + /** + * This is the actual TFTP spec identifier and is equal to 3. Identifier returned by {@link #getType getType()} indicating a data packet. + */ + public static final int DATA = 3; + + /** + * This is the actual TFTP spec identifier and is equal to 4. Identifier returned by {@link #getType getType()} indicating an acknowledgement packet. + */ + public static final int ACKNOWLEDGEMENT = 4; + + /** + * This is the actual TFTP spec identifier and is equal to 5. Identifier returned by {@link #getType getType()} indicating an error packet. + */ + public static final int ERROR = 5; + + /** + * The TFTP data packet maximum segment size in bytes. This is 512 and is useful for those familiar with the TFTP protocol who want to use the {@link TFTP} + * class methods to implement their own TFTP servers or clients. + */ + public static final int SEGMENT_SIZE = 512; + + /** + * The type of packet. + */ + final int type; + + /** + * The port the packet came from or is going to. + */ + int port; + + /** + * The host the packet is going to be sent or where it came from. + */ + InetAddress address; + + /** + * This constructor is not visible outside the package. It is used by subclasses within the package to initialize base data. + * + * @param type The type of the packet. + * @param address The host the packet came from or is going to be sent. + * @param port The port the packet came from or is going to be sent. + **/ + TFTPPacket(final int type, final InetAddress address, final int port) { + this.type = type; + this.address = address; + this.port = port; + } + + /** + * When you receive a datagram that you expect to be a TFTP packet, you use this factory method to create the proper TFTPPacket object encapsulating the + * data contained in that datagram. This method is the only way you can instantiate a TFTPPacket derived class from a datagram. + * + * @param datagram The datagram containing a TFTP packet. + * @return The TFTPPacket object corresponding to the datagram. + * @throws TFTPPacketException If the datagram does not contain a valid TFTP packet. + */ + public static TFTPPacket newTFTPPacket(final DatagramPacket datagram) throws TFTPPacketException { + final byte[] data; + TFTPPacket packet; + + if (datagram.getLength() < MIN_PACKET_SIZE) { + throw new TFTPPacketException("Bad packet. Datagram data length is too short."); + } + + data = datagram.getData(); + packet = switch (data[1]) { + case READ_REQUEST -> new TFTPReadRequestPacket(datagram); + case WRITE_REQUEST -> new TFTPWriteRequestPacket(datagram); + case DATA -> new TFTPDataPacket(datagram); + case ACKNOWLEDGEMENT -> new TFTPAckPacket(datagram); + case ERROR -> new TFTPErrorPacket(datagram); + default -> throw new TFTPPacketException("Bad packet. Invalid TFTP operator code."); + }; + + return packet; + } + + /** + * Returns the address of the host where the packet is going to be sent or where it came from. + * + * @return The type of the packet. + */ + public final InetAddress getAddress() { + return address; + } + + /** + * Returns the port where the packet is going to be sent or where it came from. + * + * @return The port where the packet came from or where it is going. + */ + public final int getPort() { + return port; + } + + /** + * Returns the type of the packet. + * + * @return The type of the packet. + */ + public final int getType() { + return type; + } + + /** + * Creates a UDP datagram containing all the TFTP packet data in the proper format. This is an abstract method, exposed to the programmer in case he wants + * to implement his own TFTP client instead of using the {@link TFTPClient} class. Under normal circumstances, you should not have a need to call this + * method. + * + * @return A UDP datagram containing the TFTP packet. + */ + public abstract DatagramPacket newDatagram(); + + /** + * This is an abstract method only available within the package for implementing efficient datagram transport by eliminating buffering. It takes a datagram + * as an argument, and a byte buffer in which to store the raw datagram data. Inside the method, the data should be set as the datagram's data and the + * datagram returned. + * + * @param datagram The datagram to create. + * @param data The buffer to store the packet and to use in the datagram. + * @return The datagram argument. + */ + abstract DatagramPacket newDatagram(DatagramPacket datagram, byte[] data); + + /** + * Sets the host address where the packet is going to be sent. + * + * @param address the address to set + */ + public final void setAddress(final InetAddress address) { + this.address = address; + } + + /** + * Sets the port where the packet is going to be sent. + * + * @param port the port to set + */ + public final void setPort(final int port) { + this.port = port; + } + + /** + * For debugging + * + * @since 3.6 + */ + @Override + public String toString() { + return address + " " + port + " " + type; + } +} diff --git a/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPPacketException.java b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPPacketException.java new file mode 100644 index 0000000..f5a2fca --- /dev/null +++ b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPPacketException.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package pl.psobiech.opengr8on.org.apache.commons.net; + +/** + * A class used to signify the occurrence of an error in the creation of a TFTP packet. It is not declared final so that it may be subclassed to identify more + * specific errors. You would only want to do this if you were building your own TFTP client or server on top of the {@link TFTP} class if you wanted more + * functionality than the {@link TFTPClient#receiveFile receiveFile()} and {@link TFTPClient#sendFile sendFile()} methods provide. + * + * @see TFTPPacket + * @see TFTP + */ +public class TFTPPacketException extends Exception { + private static final long serialVersionUID = -8596448819569308689L; + + /** + * Simply calls the corresponding constructor of its superclass. + * + * @param message the message + */ + public TFTPPacketException(final String message) { + super(message); + } +} diff --git a/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPPacketIOException.java b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPPacketIOException.java new file mode 100644 index 0000000..1062166 --- /dev/null +++ b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPPacketIOException.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package pl.psobiech.opengr8on.org.apache.commons.net; + +import java.io.IOException; + +/** + * + */ +public class TFTPPacketIOException extends IOException { + private static final long serialVersionUID = 7959893294993558186L; + + private final int errorPacketCode; + + public TFTPPacketIOException(final int errorPacketCode, final IOException exception) { + super(exception); + + this.errorPacketCode = errorPacketCode; + } + + public TFTPPacketIOException(final int errorPacketCode, final String message) { + super(message); + + this.errorPacketCode = errorPacketCode; + } + + public int getErrorPacketCode() { + return errorPacketCode; + } +} diff --git a/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPReadRequestPacket.java b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPReadRequestPacket.java new file mode 100644 index 0000000..71e156e --- /dev/null +++ b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPReadRequestPacket.java @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package pl.psobiech.opengr8on.org.apache.commons.net; + +import java.net.DatagramPacket; +import java.net.InetAddress; + +/** + * A class derived from TFTPRequestPacket defining a TFTP read request packet type. + *

+ * Details regarding the TFTP protocol and the format of TFTP packets can be found in RFC 783. But the point of these classes is to keep you from having to + * worry about the internals. Additionally, only very few people should have to care about any of the TFTPPacket classes or derived classes. Almost all users + * should only be concerned with the {@link TFTPClient} class {@link TFTPClient#receiveFile receiveFile()} and {@link TFTPClient#sendFile sendFile()} methods. + * + * @see TFTPPacket + * @see TFTPRequestPacket + * @see TFTPPacketException + * @see TFTP + */ +public final class TFTPReadRequestPacket extends TFTPRequestPacket { + /** + * Creates a read request packet of based on a received datagram and assumes the datagram has already been identified as a read request. Assumes the + * datagram is at least length 4, else an ArrayIndexOutOfBoundsException may be thrown. + * + * @param datagram The datagram containing the received request. + * @throws TFTPPacketException If the datagram isn't a valid TFTP request packet. + */ + TFTPReadRequestPacket(final DatagramPacket datagram) throws TFTPPacketException { + super(READ_REQUEST, datagram); + } + + /** + * Creates a read request packet to be sent to a host at a given port with a file name and transfer mode request. + * + * @param destination The host to which the packet is going to be sent. + * @param port The port to which the packet is going to be sent. + * @param fileName The requested file name. + * @param mode The requested transfer mode. This should be on of the TFTP class MODE constants (e.g., TFTP.NETASCII_MODE). + */ + public TFTPReadRequestPacket(final InetAddress destination, final int port, final String fileName, final int mode) { + super(destination, port, READ_REQUEST, fileName, mode); + } + + /** + * For debugging + * + * @since 3.6 + */ + @Override + public String toString() { + return super.toString() + " RRQ " + getFilename() + " " + TFTP.getModeName(getMode()); + } +} diff --git a/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPRequestPacket.java b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPRequestPacket.java new file mode 100644 index 0000000..a28b081 --- /dev/null +++ b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPRequestPacket.java @@ -0,0 +1,211 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package pl.psobiech.opengr8on.org.apache.commons.net; + +import java.net.DatagramPacket; +import java.net.InetAddress; + +/** + * An abstract class derived from TFTPPacket defining a TFTP Request packet type. It is subclassed by the {@link TFTPReadRequestPacket} and + * {@link TFTPWriteRequestPacket} classes. + *

+ * Details regarding the TFTP protocol and the format of TFTP packets can be found in RFC 783. But the point of these classes is to keep you from having to + * worry about the internals. Additionally, only very few people should have to care about any of the TFTPPacket classes or derived classes. Almost all users + * should only be concerned with the {@link TFTPClient} class {@link TFTPClient#receiveFile receiveFile()} and {@link TFTPClient#sendFile sendFile()} methods. + * + * @see TFTPPacket + * @see TFTPReadRequestPacket + * @see TFTPWriteRequestPacket + * @see TFTPPacketException + * @see TFTP + */ +public abstract class TFTPRequestPacket extends TFTPPacket { + /** + * An array containing the string names of the transfer modes and indexed by the transfer mode constants. + */ + public static final String[] modeStrings = {"netascii", "octet"}; + + /** + * A null terminated byte array representation of the ascii names of the transfer mode constants. This is convenient for creating the TFTP request packets. + */ + private static final byte[][] modeBytes = { + {(byte) 'n', (byte) 'e', (byte) 't', (byte) 'a', (byte) 's', (byte) 'c', (byte) 'i', (byte) 'i', 0}, + {(byte) 'o', (byte) 'c', (byte) 't', (byte) 'e', (byte) 't', 0} + }; + + /** + * The transfer mode of the request. + */ + private final int mode; + + /** + * The file name of the request. + */ + private final String fileName; + + /** + * Creates a request packet of a given type to be sent to a host at a given port with a file name and transfer mode request. + * + * @param destination The host to which the packet is going to be sent. + * @param port The port to which the packet is going to be sent. + * @param type The type of the request (either TFTPPacket.READ_REQUEST or TFTPPacket.WRITE_REQUEST). + * @param fileName The requested file name. + * @param mode The requested transfer mode. This should be on of the TFTP class MODE constants (e.g., TFTP.NETASCII_MODE). + */ + TFTPRequestPacket(final InetAddress destination, final int port, final int type, final String fileName, final int mode) { + super(type, destination, port); + + this.fileName = fileName; + this.mode = mode; + } + + /** + * Creates a request packet of a given type based on a received datagram. Assumes the datagram is at least length 4, else an ArrayIndexOutOfBoundsException + * may be thrown. + * + * @param type The type of the request (either TFTPPacket.READ_REQUEST or TFTPPacket.WRITE_REQUEST). + * @param datagram The datagram containing the received request. + * @throws TFTPPacketException If the datagram isn't a valid TFTP request packet of the appropriate type. + */ + TFTPRequestPacket(final int type, final DatagramPacket datagram) throws TFTPPacketException { + super(type, datagram.getAddress(), datagram.getPort()); + + final byte[] data = datagram.getData(); + + if (getType() != data[1]) { + throw new TFTPPacketException("TFTP operator code does not match type."); + } + + final StringBuilder buffer = new StringBuilder(); + + int index = 2; + int length = datagram.getLength(); + + while (index < length && data[index] != 0) { + buffer.append((char) data[index]); + ++index; + } + + this.fileName = buffer.toString(); + + if (index >= length) { + throw new TFTPPacketException("Bad file name and mode format."); + } + + buffer.setLength(0); + ++index; // need to advance beyond the end of string marker + while (index < length && data[index] != 0) { + buffer.append((char) data[index]); + ++index; + } + + final String modeString = buffer.toString().toLowerCase(java.util.Locale.ENGLISH); + length = modeStrings.length; + + int mode = 0; + for (index = 0; index < length; index++) { + if (modeString.equals(modeStrings[index])) { + mode = index; + break; + } + } + + this.mode = mode; + + if (index >= length) { + throw new TFTPPacketException("Unrecognized TFTP transfer mode: " + modeString); + // May just want to default to binary mode instead of throwing + // exception. + // _mode = TFTP.OCTET_MODE; + } + } + + /** + * Returns the requested file name. + * + * @return The requested file name. + */ + public final String getFilename() { + return fileName; + } + + /** + * Returns the transfer mode of the request. + * + * @return The transfer mode of the request. + */ + public final int getMode() { + return mode; + } + + /** + * Creates a UDP datagram containing all the TFTP request packet data in the proper format. This is a method exposed to the programmer in case he wants to + * implement his own TFTP client instead of using the {@link TFTPClient} class. Under normal circumstances, you should not have a need to call this method. + * + * @return A UDP datagram containing the TFTP request packet. + */ + @Override + public final DatagramPacket newDatagram() { + final int fileLength; + final int modeLength; + final byte[] data; + + fileLength = fileName.length(); + modeLength = modeBytes[mode].length; + + data = new byte[fileLength + modeLength + 4]; + data[0] = 0; + data[1] = (byte) type; + System.arraycopy(fileName.getBytes(), 0, data, 2, fileLength); + data[fileLength + 2] = 0; + System.arraycopy(modeBytes[mode], 0, data, fileLength + 3, modeLength); + + return new DatagramPacket(data, data.length, address, port); + } + + /** + * This is a method only available within the package for implementing efficient datagram transport by eliminating buffering. It takes a datagram as an + * argument, and a byte buffer in which to store the raw datagram data. Inside the method, the data is set as the datagram's data and the datagram + * returned. + * + * @param datagram The datagram to create. + * @param data The buffer to store the packet and to use in the datagram. + * @return The datagram argument. + */ + @Override + final DatagramPacket newDatagram(final DatagramPacket datagram, final byte[] data) { + final int fileLength; + final int modeLength; + + fileLength = fileName.length(); + modeLength = modeBytes[mode].length; + + data[0] = 0; + data[1] = (byte) type; + System.arraycopy(fileName.getBytes(), 0, data, 2, fileLength); + data[fileLength + 2] = 0; + System.arraycopy(modeBytes[mode], 0, data, fileLength + 3, modeLength); + + datagram.setAddress(address); + datagram.setPort(port); + datagram.setData(data); + datagram.setLength(fileLength + modeLength + 3); + + return datagram; + } +} diff --git a/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPServer.java b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPServer.java new file mode 100644 index 0000000..ac50b1c --- /dev/null +++ b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPServer.java @@ -0,0 +1,703 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package pl.psobiech.opengr8on.org.apache.commons.net; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketTimeoutException; +import java.time.Duration; +import java.util.Enumeration; +import java.util.HashSet; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.net.io.FromNetASCIIOutputStream; +import org.apache.commons.net.io.ToNetASCIIInputStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A fully multi-threaded TFTP server. Can handle multiple clients at the same time. Implements RFC 1350 and wrapping block numbers for large file support. To + * launch, just create an instance of the class. An IOException will be thrown if the server fails to start for reasons such as port in use, port denied, etc. + * To stop, use the shutdown method. To check to see if the server is still running (or if it stopped because of an error), call the isRunning() method. By + * default, events are not logged to stdout/stderr. This can be changed with the setLog and setLogError methods. + * + *

+ * Example usage is below: + * + * public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("You must provide 1 argument - the base path for the + * server to serve from."); System.exit(1); } try (TFTPServer ts = new TFTPServer(new File(args[0]), new File(args[0]), GET_AND_PUT)) { + * ts.setSocketTimeout(2000); System.out.println("TFTP Server running. Press enter to stop."); new InputStreamReader(System.in).read(); } + * System.out.println("Server shut down."); System.exit(0); } + * + * + * @since 2.0 + */ +public class TFTPServer implements Runnable, AutoCloseable { + private static final Logger LOGGER = LoggerFactory.getLogger(TFTPServer.class); + + private final HashSet transfers = new HashSet<>(); + + private final int port; + + private final InetAddress localAddress; + + private final ServerMode mode; + + private volatile boolean shutdownServer; + + private TFTP serverTftp; + + private File serverDirectory; + + private Exception serverException; + + private int maxTimeoutRetries = 3; + + private int socketTimeout; + + private Thread serverThread; + + /** + * Start a TFTP Server on the specified port. Gets and Puts occur in the specified directory. + * + * The server will start in another thread, allowing this constructor to return immediately. + * + * If a get or a put comes in with a relative path that tries to get outside the serverDirectory, then the get or put will be denied. + * + * GET_ONLY mode only allows gets, PUT_ONLY mode only allows puts, and GET_AND_PUT allows both. Modes are defined as int constants in this class. + * + * @param port The local port to bind to. + * @param localAddress The local address to bind to. + * @param mode A value as specified above. + * @throws IOException if the server directory is invalid or does not exist. + */ + public TFTPServer( + final int port, final InetAddress localAddress, final ServerMode mode + ) throws IOException { + this.port = port; + this.mode = mode; + this.localAddress = localAddress; + } + + /** + * Start a TFTP Server on the specified port. Gets and Puts occur in the specified directory. + * + * The server will start in another thread, allowing this constructor to return immediately. + * + * If a get or a put comes in with a relative path that tries to get outside the serverDirectory, then the get or put will be denied. + * + * GET_ONLY mode only allows gets, PUT_ONLY mode only allows puts, and GET_AND_PUT allows both. Modes are defined as int constants in this class. + * + * @param port the port to use + * @param localiface The local network interface to bind to. The interface's first address wil be used. + * @param mode A value as specified above. + * @throws IOException if the server directory is invalid or does not exist. + */ + public TFTPServer( + final int port, final NetworkInterface localiface, final ServerMode mode + ) throws IOException { + this.mode = mode; + this.port = port; + InetAddress inetAddress = null; + if (localiface != null) { + final Enumeration ifaddrs = localiface.getInetAddresses(); + if (ifaddrs.hasMoreElements()) { + inetAddress = ifaddrs.nextElement(); + } + } + + this.localAddress = inetAddress; + } + + /** + * Start a TFTP Server on the specified port. Gets and Puts occur in the specified directory. + * + * The server will start in another thread, allowing this constructor to return immediately. + * + * If a get or a put comes in with a relative path that tries to get outside the serverDirectory, then the get or put will be denied. + * + * GET_ONLY mode only allows gets, PUT_ONLY mode only allows puts, and GET_AND_PUT allows both. Modes are defined as int constants in this class. + * + * @param serverDirectory directory for GET requests + * @param port the port to use + * @param mode A value as specified above. + * @throws IOException if the server directory is invalid or does not exist. + */ + public TFTPServer( + final File serverDirectory, final int port, final ServerMode mode + ) throws IOException { + this.port = port; + this.mode = mode; + this.localAddress = null; + + start(serverDirectory); + } + + /** + * Closes the TFTP server (and any currently running transfers) and release all opened network resources. + * + * @since 3.10.0 + */ + @Override + public void close() { + shutdownServer = true; + + synchronized (transfers) { + transfers.forEach(TFTPTransfer::close); + } + + try { + serverTftp.close(); + } catch (final RuntimeException e) { + // noop + } + + if (serverThread != null) { + try { + serverThread.join(); + } catch (final InterruptedException e) { + // we've done the best we could, return + } + } + } + + /** + * Gets the current value for maxTimeoutRetries + * + * @return the max allowed number of retries + */ + public int getMaxTimeoutRetries() { + return maxTimeoutRetries; + } + + /** + * Gets the server port number + * + * @return the server port number + */ + public int getPort() { + return port; + } + + /** + * Gets the current socket timeout used during transfers in milliseconds. + * + * @return the timeout value + */ + public int getSocketTimeout() { + return socketTimeout; + } + + /** + * check if the server thread is still running. + * + * @return true if running, false if stopped. + * @throws Exception throws the exception that stopped the server if the server is stopped from an exception. + */ + public boolean isRunning() throws Exception { + if (shutdownServer && serverException != null) { + throw serverException; + } + return !shutdownServer; + } + + /* + * start the server, throw an error if it can't start. + */ + public void start(final File newServerReadDirectory) throws IOException { + LOGGER.debug("Starting TFTP Server on port " + port + ". Server directory: " + newServerReadDirectory + ". Server Mode is " + mode); + + this.serverDirectory = newServerReadDirectory.getCanonicalFile(); + if (!serverDirectory.exists() || !newServerReadDirectory.isDirectory()) { + throw new IOException("The server directory " + this.serverDirectory + " does not exist"); + } + + serverTftp = new TFTP(); + + // This is the value used in response to each client. + socketTimeout = serverTftp.getDefaultTimeout(); + + // we want the server thread to listen forever. + serverTftp.setDefaultTimeout(Duration.ZERO); + + if (localAddress == null) { + serverTftp.open(port); + } else { + serverTftp.open(port, localAddress); + } + + serverThread = new Thread(this); + serverThread.setDaemon(true); + serverThread.start(); + } + + /* + * Allow test code to customise the TFTP instance + */ + TFTP newTFTP() { + return new TFTP(); + } + + @Override + public void run() { + try { + while (!shutdownServer && !Thread.interrupted()) { + final TFTPPacket tftpPacket; + + tftpPacket = serverTftp.receive(); + + final TFTPTransfer tt = new TFTPTransfer(tftpPacket); + synchronized (transfers) { + transfers.add(tt); + } + + final Thread thread = new Thread(tt); + thread.setDaemon(true); + thread.start(); + } + } catch (Exception e) { + if (!shutdownServer) { + serverException = e; + LOGGER.error("Unexpected Error in TFTP Server - Server shut down! + ", e); + } + } finally { + shutdownServer = true; // set this to true, so the launching thread can check to see if it started. + if (serverTftp != null && serverTftp.isOpen()) { + serverTftp.close(); + } + } + } + + /* + * Also allow customisation of sending data/ack so can generate errors if needed + */ + void sendData(final TFTP tftp, final TFTPPacket data) throws IOException { + tftp.bufferedSend(data); + } + + /** + * Set the max number of retries in response to a timeout. Default 3. Min 0. + * + * @param retries number of retries, must be > 0 + * @throws IllegalArgumentException if {@code retries} is less than 0. + */ + public void setMaxTimeoutRetries(final int retries) { + if (retries < 0) { + throw new IllegalArgumentException("Invalid Value"); + } + maxTimeoutRetries = retries; + } + + /** + * Set the socket timeout in milliseconds used in transfers. + *

+ * Defaults to the value {@link TFTP#DEFAULT_TIMEOUT_DURATION}. Minimum value of 10. + *

+ * + * @param timeout the timeout; must be equal to or larger than 10. + * @throws IllegalArgumentException if {@code timeout} is less than 10. + */ + public void setSocketTimeout(final int timeout) { + if (timeout < 10) { + throw new IllegalArgumentException("Invalid Value"); + } + socketTimeout = timeout; + } + + public enum ServerMode { + GET_ONLY, + PUT_ONLY, + GET_AND_PUT, + GET_AND_REPLACE + // + ; + } + + /* + * An ongoing transfer. + */ + private class TFTPTransfer implements Runnable { + private final TFTPPacket tftpPacket; + + private boolean shutdownTransfer; + + TFTP transferTftp; + + public TFTPTransfer(final TFTPPacket tftpPacket) { + this.tftpPacket = tftpPacket; + } + + @Override + public void run() { + try { + transferTftp = newTFTP(); + + transferTftp.beginBufferedOps(); + transferTftp.setDefaultTimeout(Duration.ofMillis(socketTimeout)); + + transferTftp.open(); + + if (tftpPacket instanceof TFTPReadRequestPacket) { + handleRead((TFTPReadRequestPacket) tftpPacket); + } else if (tftpPacket instanceof TFTPWriteRequestPacket) { + handleWrite((TFTPWriteRequestPacket) tftpPacket); + } else { + LOGGER.debug("Unsupported TFTP request (" + tftpPacket + ") - ignored."); + } + } catch (final Exception e) { + if (!shutdownTransfer) { + LOGGER.error("Unexpected Error in during TFTP file transfer. Transfer aborted. ", e); + } + } finally { + try { + if (transferTftp != null && transferTftp.isOpen()) { + transferTftp.endBufferedOps(); + transferTftp.close(); + } + } catch (final Exception e) { + // noop + } + synchronized (transfers) { + transfers.remove(this); + } + } + } + + /* + * Creates subdirectories recursively. + */ + private void createDirectory(final File file) throws IOException { + final File parent = file.getParentFile(); + if (parent == null) { + throw new IOException("Unexpected error creating requested directory"); + } + if (!parent.exists()) { + // recurse... + createDirectory(parent); + } + + if (!parent.isDirectory()) { + throw new IOException("Invalid directory path - file in the way of requested folder"); + } + if (file.isDirectory()) { + return; + } + final boolean result = file.mkdir(); + if (!result) { + throw new IOException("Couldn't create requested directory"); + } + } + + /* + * Handles a tftp read request. + */ + private void handleRead(final TFTPReadRequestPacket trrp) throws IOException, TFTPPacketException { + if (mode == ServerMode.PUT_ONLY) { + transferTftp + .bufferedSend(new TFTPErrorPacket(trrp.getAddress(), trrp.getPort(), TFTPErrorPacket.ILLEGAL_OPERATION, "Read not allowed by server.")); + return; + } + InputStream inputStream = null; + try { + try { + inputStream = new BufferedInputStream(new FileInputStream(buildSafeFile(serverDirectory, trrp.getFilename(), false))); + } catch (final FileNotFoundException e) { + transferTftp.bufferedSend(new TFTPErrorPacket(trrp.getAddress(), trrp.getPort(), TFTPErrorPacket.FILE_NOT_FOUND, e.getMessage())); + return; + } catch (final Exception e) { + transferTftp.bufferedSend(new TFTPErrorPacket(trrp.getAddress(), trrp.getPort(), TFTPErrorPacket.UNDEFINED, e.getMessage())); + return; + } + + if (trrp.getMode() == TFTP.NETASCII_MODE) { + inputStream = new ToNetASCIIInputStream(inputStream); + } + + final byte[] temp = new byte[TFTPDataPacket.MAX_DATA_LENGTH]; + + TFTPPacket answer; + + int block = 1; + boolean sendNext = true; + + int readLength = TFTPDataPacket.MAX_DATA_LENGTH; + + TFTPDataPacket lastSentData = null; + + // We are reading a file, so when we read less than the + // requested bytes, we know that we are at the end of the file. + while (readLength == TFTPDataPacket.MAX_DATA_LENGTH && !shutdownTransfer) { + if (sendNext) { + readLength = inputStream.read(temp); + if (readLength == -1) { + readLength = 0; + } + + lastSentData = new TFTPDataPacket(trrp.getAddress(), trrp.getPort(), block, temp, 0, readLength); + sendData(transferTftp, lastSentData); // send the data + } + + answer = null; + + int timeoutCount = 0; + + while (!shutdownTransfer && (answer == null || !answer.getAddress().equals(trrp.getAddress()) || answer.getPort() != trrp.getPort())) { + // listen for an answer. + if (answer != null) { + // The answer that we got didn't come from the + // expected source, fire back an error, and continue + // listening. + LOGGER.debug("TFTP Server ignoring message from unexpected source."); + transferTftp.bufferedSend( + new TFTPErrorPacket(answer.getAddress(), answer.getPort(), TFTPErrorPacket.UNKNOWN_TID, "Unexpected Host or Port")); + } + try { + answer = transferTftp.bufferedReceive(); + } catch (final SocketTimeoutException e) { + if (timeoutCount >= maxTimeoutRetries) { + throw e; + } + // didn't get an ack for this data. need to resend + // it. + timeoutCount++; + transferTftp.bufferedSend(lastSentData); + } + } + + if (!(answer instanceof final TFTPAckPacket ack)) { + if (!shutdownTransfer) { + LOGGER.error("Unexpected response from tftp client during transfer (" + answer + "). Transfer aborted."); + } + break; + } + // once we get here, we know we have an answer packet + // from the correct host. + if (ack.getBlockNumber() == block) { + // send the next block + block++; + if (block > 65535) { + // wrap the block number + block = 0; + } + sendNext = true; + } else { + /* + * The origional tftp spec would have called on us to resend the previous data here, however, that causes the SAS Syndrome. + * http://www.faqs.org/rfcs/rfc1123.html section 4.2.3.1 The modified spec says that we ignore a duplicate ack. If the packet was really + * lost, we will time out on receive, and resend the previous data at that point. + */ + sendNext = false; + } + } + } finally { + try { + if (inputStream != null) { + inputStream.close(); + } + } catch (final IOException e) { + // noop + } + } + } + + /* + * handle a TFTP write request. + */ + private void handleWrite(final TFTPWriteRequestPacket twrp) throws IOException, TFTPPacketException { + OutputStream bos = null; + try { + if (mode == ServerMode.GET_ONLY) { + transferTftp.bufferedSend( + new TFTPErrorPacket(twrp.getAddress(), twrp.getPort(), TFTPErrorPacket.ILLEGAL_OPERATION, "Write not allowed by server.")); + return; + } + + int lastBlock = 0; + try { + final File temp = buildSafeFile(serverDirectory, twrp.getFilename(), true); + if (mode != ServerMode.GET_AND_REPLACE && temp.exists()) { + transferTftp.bufferedSend(new TFTPErrorPacket( + twrp.getAddress(), + twrp.getPort(), + TFTPErrorPacket.FILE_EXISTS, + "File already exists" + )); + return; + } + bos = new BufferedOutputStream(new FileOutputStream(temp)); + + if (twrp.getMode() == TFTP.NETASCII_MODE) { + bos = new FromNetASCIIOutputStream(bos); + } + } catch (final Exception e) { + transferTftp.bufferedSend(new TFTPErrorPacket(twrp.getAddress(), twrp.getPort(), TFTPErrorPacket.UNDEFINED, e.getMessage())); + return; + } + + TFTPAckPacket lastSentAck = new TFTPAckPacket(twrp.getAddress(), twrp.getPort(), 0); + sendData(transferTftp, lastSentAck); // send the data + + while (true) { + // get the response - ensure it is from the right place. + TFTPPacket dataPacket = null; + + int timeoutCount = 0; + + while (!shutdownTransfer + && (dataPacket == null || !dataPacket.getAddress().equals(twrp.getAddress()) || dataPacket.getPort() != twrp.getPort())) { + // listen for an answer. + if (dataPacket != null) { + // The data that we got didn't come from the + // expected source, fire back an error, and continue + // listening. + LOGGER.debug("TFTP Server ignoring message from unexpected source."); + transferTftp.bufferedSend( + new TFTPErrorPacket(dataPacket.getAddress(), dataPacket.getPort(), TFTPErrorPacket.UNKNOWN_TID, "Unexpected Host or Port")); + } + + try { + dataPacket = transferTftp.bufferedReceive(); + } catch (final SocketTimeoutException e) { + if (timeoutCount >= maxTimeoutRetries) { + throw e; + } + // It didn't get our ack. Resend it. + transferTftp.bufferedSend(lastSentAck); + timeoutCount++; + } + } + + if (dataPacket instanceof TFTPWriteRequestPacket) { + // it must have missed our initial ack. Send another. + lastSentAck = new TFTPAckPacket(twrp.getAddress(), twrp.getPort(), 0); + transferTftp.bufferedSend(lastSentAck); + } else if (dataPacket instanceof TFTPDataPacket) { + final int block = ((TFTPDataPacket) dataPacket).getBlockNumber(); + final byte[] data = ((TFTPDataPacket) dataPacket).getData(); + final int dataLength = ((TFTPDataPacket) dataPacket).getDataLength(); + final int dataOffset = ((TFTPDataPacket) dataPacket).getDataOffset(); + + if (block > lastBlock || lastBlock == 65535 && block == 0) { + // it might resend a data block if it missed our ack + // - don't rewrite the block. + bos.write(data, dataOffset, dataLength); + lastBlock = block; + } + + lastSentAck = new TFTPAckPacket(twrp.getAddress(), twrp.getPort(), block); + sendData(transferTftp, lastSentAck); // send the data + if (dataLength < TFTPDataPacket.MAX_DATA_LENGTH) { + // end of stream signal - The tranfer is complete. + bos.close(); + + // But my ack may be lost - so listen to see if I + // need to resend the ack. + for (int i = 0; i < maxTimeoutRetries; i++) { + try { + dataPacket = transferTftp.bufferedReceive(); + } catch (final SocketTimeoutException e) { + // this is the expected route - the client + // shouldn't be sending any more packets. + break; + } + + if (dataPacket != null && (!dataPacket.getAddress().equals(twrp.getAddress()) || dataPacket.getPort() != twrp.getPort())) { + // make sure it was from the right client... + transferTftp.bufferedSend(new TFTPErrorPacket(dataPacket.getAddress(), dataPacket.getPort(), TFTPErrorPacket.UNKNOWN_TID, + "Unexpected Host or Port" + )); + } else { + // This means they sent us the last + // datapacket again, must have missed our + // ack. resend it. + transferTftp.bufferedSend(lastSentAck); + } + } + + // all done. + break; + } + } else { + if (!shutdownTransfer) { + LOGGER.error("Unexpected response from tftp client during transfer (" + dataPacket + "). Transfer aborted."); + } + break; + } + } + } finally { + if (bos != null) { + bos.close(); + } + } + } + + /* + * Makes sure that paths provided by TFTP clients do not get outside the serverRoot directory. + */ + private File buildSafeFile(final File serverDirectory, String fileName, final boolean createSubDirs) throws IOException { + fileName = fileName.replaceAll("a:\\\\", ""); + File temp = new File(serverDirectory, fileName).getCanonicalFile(); + if (!temp.exists()) { + temp = new File(serverDirectory, StringUtils.upperCase(fileName)).getCanonicalFile(); + } + + if (!isSubdirectoryOf(serverDirectory, temp)) { + throw new IOException("Cannot access files outside of TFTP server root."); + } + + // ensure directory exists (if requested) + if (createSubDirs) { + createDirectory(temp.getParentFile()); + } + + return temp; + } + + /* + * recursively check to see if one directory is a parent of another. + */ + private boolean isSubdirectoryOf(final File parent, final File child) { + final File childsParent = child.getParentFile(); + if (childsParent == null) { + return false; + } + if (childsParent.equals(parent)) { + return true; + } + return isSubdirectoryOf(parent, childsParent); + } + + public void close() { + shutdownTransfer = true; + try { + transferTftp.close(); + } catch (final RuntimeException e) { + // noop + } + } + } +} diff --git a/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPWriteRequestPacket.java b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPWriteRequestPacket.java new file mode 100644 index 0000000..5440390 --- /dev/null +++ b/tftp/src/main/java/pl/psobiech/opengr8on/org/apache/commons/net/TFTPWriteRequestPacket.java @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package pl.psobiech.opengr8on.org.apache.commons.net; + +import java.net.DatagramPacket; +import java.net.InetAddress; + +/** + * A class derived from TFTPRequestPacket defining a TFTP write request packet type. + *

+ * Details regarding the TFTP protocol and the format of TFTP packets can be found in RFC 783. But the point of these classes is to keep you from having to + * worry about the internals. Additionally, only very few people should have to care about any of the TFTPPacket classes or derived classes. Almost all users + * should only be concerned with the {@link TFTPClient} class {@link TFTPClient#receiveFile receiveFile()} and {@link TFTPClient#sendFile sendFile()} methods. + * + * @see TFTPPacket + * @see TFTPRequestPacket + * @see TFTPPacketException + * @see TFTP + */ +public final class TFTPWriteRequestPacket extends TFTPRequestPacket { + /** + * Creates a write request packet of based on a received datagram and assumes the datagram has already been identified as a write request. Assumes the + * datagram is at least length 4, else an ArrayIndexOutOfBoundsException may be thrown. + * + * @param datagram The datagram containing the received request. + * @throws TFTPPacketException If the datagram isn't a valid TFTP request packet. + */ + TFTPWriteRequestPacket(final DatagramPacket datagram) throws TFTPPacketException { + super(WRITE_REQUEST, datagram); + } + + /** + * Creates a write request packet to be sent to a host at a given port with a file name and transfer mode request. + * + * @param destination The host to which the packet is going to be sent. + * @param port The port to which the packet is going to be sent. + * @param fileName The requested file name. + * @param mode The requested transfer mode. This should be on of the TFTP class MODE constants (e.g., TFTP.NETASCII_MODE). + */ + public TFTPWriteRequestPacket(final InetAddress destination, final int port, final String fileName, final int mode) { + super(destination, port, WRITE_REQUEST, fileName, mode); + } + + /** + * For debugging + * + * @since 3.6 + */ + @Override + public String toString() { + return super.toString() + " WRQ " + getFilename() + " " + TFTP.getModeName(getMode()); + } +} diff --git a/vclu/assembly/jar-with-dependencies.xml b/vclu/assembly/jar-with-dependencies.xml new file mode 100644 index 0000000..3174bdc --- /dev/null +++ b/vclu/assembly/jar-with-dependencies.xml @@ -0,0 +1,39 @@ + + + + jar-with-dependencies-and-exclude-classes + + + jar + + + false + + + + / + true + true + runtime + + + \ No newline at end of file diff --git a/vclu/pom.xml b/vclu/pom.xml new file mode 100644 index 0000000..82203a8 --- /dev/null +++ b/vclu/pom.xml @@ -0,0 +1,87 @@ + + + + + 4.0.0 + + + pl.psobiech.opengr8on + parent + 1.0-SNAPSHOT + + + vclu + + + + pl.psobiech.opengr8on + lib + + + + ch.qos.logback + logback-classic + + + + commons-net + commons-net + + + + + org.luaj + luaj-jse + 3.0.1 + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + vclu + false + + assembly/jar-with-dependencies.xml + + + + true + pl.psobiech.opengr8on.vclu.Main + + + + + + assemble-all + package + + single + + + + + + + \ No newline at end of file diff --git a/vclu/src/main/java/pl/psobiech/opengr8on/vclu/LuaServer.java b/vclu/src/main/java/pl/psobiech/opengr8on/vclu/LuaServer.java new file mode 100644 index 0000000..4fcac12 --- /dev/null +++ b/vclu/src/main/java/pl/psobiech/opengr8on/vclu/LuaServer.java @@ -0,0 +1,444 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.vclu; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; +import org.luaj.vm2.Globals; +import org.luaj.vm2.LoadState; +import org.luaj.vm2.LuaTable; +import org.luaj.vm2.LuaThread; +import org.luaj.vm2.LuaValue; +import org.luaj.vm2.Varargs; +import org.luaj.vm2.compiler.LuaC; +import org.luaj.vm2.lib.CoroutineLib; +import org.luaj.vm2.lib.LibFunction; +import org.luaj.vm2.lib.OneArgFunction; +import org.luaj.vm2.lib.PackageLib; +import org.luaj.vm2.lib.StringLib; +import org.luaj.vm2.lib.TableLib; +import org.luaj.vm2.lib.ThreeArgFunction; +import org.luaj.vm2.lib.TwoArgFunction; +import org.luaj.vm2.lib.jse.JseBaseLib; +import org.luaj.vm2.lib.jse.JseOsLib; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import pl.psobiech.opengr8on.client.CLUFiles; +import pl.psobiech.opengr8on.client.CipherKey; +import pl.psobiech.opengr8on.client.device.CLUDevice; +import pl.psobiech.opengr8on.exceptions.UnexpectedException; +import pl.psobiech.opengr8on.util.IPv4AddressUtil.NetworkInterfaceDto; +import pl.psobiech.opengr8on.vclu.VirtualSystem.Subscription; + +import static org.apache.commons.lang3.StringUtils.lowerCase; +import static org.apache.commons.lang3.StringUtils.stripToEmpty; +import static org.apache.commons.lang3.StringUtils.stripToNull; + +public class LuaServer { + private static final Logger LOGGER = LoggerFactory.getLogger(LuaServer.class); + + private LuaServer() { + // NOP + } + + public static LuaThreadWrapper create(NetworkInterfaceDto networkInterface, Path rootDirectory, CLUDevice cluDevice, CipherKey cipherKey) { + final VirtualSystem virtualSystem = new VirtualSystem(networkInterface, cluDevice, cipherKey); + + Globals globals = new Globals(); + globals.load(new JseBaseLib()); + globals.load(new PackageLib()); + //globals.load(new Bit32Lib()); + globals.load(new TableLib()); + globals.load(new StringLib()); + globals.load(new CoroutineLib()); + //globals.load(new JseMathLib()); + //globals.load(new JseIoLib()); + globals.load(new JseOsLib()); + //globals.load(new LuajavaLib()); + + globals.load(new TwoArgFunction() { + public LuaValue call(LuaValue modname, LuaValue env) { + final LuaValue library = tableOf(); + + library.set("setup", new LibFunction() { + @Override + public LuaValue call() { + virtualSystem.setup(); + + return LuaValue.NIL; + } + }); + + library.set("loop", new LibFunction() { + @Override + public LuaValue call() { + virtualSystem.loop(); + + return LuaValue.NIL; + } + }); + + library.set("sleep", new OneArgFunction() { + @Override + public LuaValue call(LuaValue arg) { + virtualSystem.sleep(arg.checklong()); + + return LuaValue.NIL; + } + }); + + library.set("logDebug", new OneArgFunction() { + @Override + public LuaValue call(LuaValue arg) { + LOGGER.debug(String.valueOf(arg.checkstring())); + + return LuaValue.NIL; + } + }); + + library.set("logInfo", new OneArgFunction() { + @Override + public LuaValue call(LuaValue arg) { + LOGGER.info(String.valueOf(arg.checkstring())); + + return LuaValue.NIL; + } + }); + + library.set("logWarning", new OneArgFunction() { + @Override + public LuaValue call(LuaValue arg) { + LOGGER.warn(String.valueOf(arg.checkstring())); + + return LuaValue.NIL; + } + }); + + library.set("logError", new OneArgFunction() { + @Override + public LuaValue call(LuaValue arg) { + LOGGER.error(String.valueOf(arg.checkstring())); + + return LuaValue.NIL; + } + }); + + library.set("clientRegister", new LibFunction() { + @Override + public LuaValue invoke(Varargs args) { + final LuaValue object = args.arg(4); + + final ArrayList subscriptions = new ArrayList<>(); + if (!object.istable()) { + return LuaValue.valueOf("values:{" + 99 + "}"); + } + final LuaTable checktable = object.checktable(); + for (LuaValue key : checktable.keys()) { + final LuaValue keyValue = checktable.get(key); + if (!keyValue.istable()) { + return LuaValue.valueOf("values:{" + 99 + "}"); + } + + subscriptions.add( + new Subscription( + String.valueOf(keyValue.checktable().get(1).checktable().get("name")), + keyValue.checktable().get(2).checkint() + ) + ); + } + + return LuaValue.valueOf( + virtualSystem.clientRegister( + String.valueOf(args.arg1().checkstring()), + args.arg(2).checkint(), + args.arg(3).checkint(), + subscriptions + ) + ); + } + }); + + library.set("clientDestroy", new LibFunction() { + @Override + public LuaValue invoke(Varargs args) { + return virtualSystem.clientDestroy( + String.valueOf(args.arg1().checkstring()), + args.arg(2).checkint(), + args.arg(3).checkint() + ); + } + }); + + library.set("fetchValues", new OneArgFunction() { + @Override + public LuaValue call(LuaValue object) { + final ArrayList subscriptions = new ArrayList<>(); + if (!object.istable()) { + return LuaValue.valueOf("values:{" + 99 + "}"); + } + + final LuaTable checktable = object.checktable(); + for (LuaValue key : checktable.keys()) { + final LuaValue keyValue = checktable.get(key); + if (!keyValue.istable()) { + return LuaValue.valueOf("values:{\"" + globals.load("return _G[\"%s\"]".formatted(keyValue)).call() + "\"}"); + } + + subscriptions.add( + new Subscription( + String.valueOf(keyValue.checktable().get(1).checktable().get("name")), + keyValue.checktable().get(2).checkint() + ) + ); + } + + return LuaValue.valueOf( + "values:" + virtualSystem.fetchValues( + subscriptions + ) + ); + } + + @Override + public LuaValue call(LuaValue object, LuaValue arg1, LuaValue arg2) { + virtualSystem.getObject(object.checkint()).addEvent(arg1.checkint(), arg2.checkfunction()); + + return LuaValue.NIL; + } + }); + + library.set("newObject", new ThreeArgFunction() { + @Override + public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) { + return LuaValue.valueOf( + virtualSystem.newObject(arg1.checkint(), String.valueOf(arg2.checkstring()), arg3.checkint()) + ); + } + }); + + library.set("newGate", new ThreeArgFunction() { + @Override + public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) { + return LuaValue.valueOf( + virtualSystem.newGate(arg1.checkint(), String.valueOf(arg2.checkstring())) + ); + } + }); + + library.set("get", new TwoArgFunction() { + @Override + public LuaValue call(LuaValue object, LuaValue arg) { + return virtualSystem.getObject(object.checkint()).get(arg.checkint()); + } + }); + + library.set("set", new ThreeArgFunction() { + @Override + public LuaValue call(LuaValue object, LuaValue arg1, LuaValue arg2) { + virtualSystem.getObject(object.checkint()).set(arg1.checkint(), arg2); + + return LuaValue.NIL; + } + }); + + library.set("execute", new ThreeArgFunction() { + @Override + public LuaValue call(LuaValue object, LuaValue arg1, LuaValue arg2) { + return virtualSystem.getObject(object.checkint()).execute(arg1.checkint(), arg2); + } + }); + + library.set("addEvent", new ThreeArgFunction() { + @Override + public LuaValue call(LuaValue object, LuaValue arg1, LuaValue arg2) { + virtualSystem.getObject(object.checkint()).addEvent(arg1.checkint(), arg2.checkfunction()); + + return LuaValue.NIL; + } + }); + + env.set("api", library); + + return library; + } + }); + + LoadState.install(globals); + LuaC.install(globals); + + globals.finder = filename -> { + try { + final Path filePath = rootDirectory.resolve(StringUtils.upperCase(filename)); + if (!filePath.getParent().equals(rootDirectory)) { + throw new UnexpectedException("Attempt to access external directory"); + } + + return Files.newInputStream( + filePath + ); + } catch (IOException e) { + throw new RuntimeException(e); + } + }; + + loadScript(globals, classPath(URI.create("classpath:/INIT.LUA")), "INIT.LUA"); + + return new LuaThreadWrapper( + globals, rootDirectory + ); + } + + private static LuaValue loadScript(Globals globals, Path path, String name) { + final String script; + try { + script = Files.readString(path); + } catch (IOException e) { + throw new UnexpectedException(e); + } + + return globals.load(script, name) + .call(); + } + + private static final String JAR_PATH_SEPARATOR = Pattern.quote("!"); + + private static Path classPath(URI uri) { + final String resourceUriPath = getResourceUriPath(uri); + + final URL url = LuaServer.class.getResource(resourceUriPath); + if (url == null) { + throw new UnexpectedException(uri + " not found!"); + } + + try { + final URI classPathUri = url.toURI(); + final String scheme = classPathUri.getScheme(); + final String classPathUriAsString = classPathUri.toString(); + + final Path path; + if (scheme.equals(SchemeEnum.JAR.toUrlScheme())) { + final String jarPath = classPathUriAsString.split(JAR_PATH_SEPARATOR, 2)[0]; + + path = getOrCreateJarFileSystemFor(jarPath).provider() + .getPath(classPathUri); + } else { + path = Paths.get(classPathUri); + } + + return path; + } catch (URISyntaxException e) { + throw new UnexpectedException(e); + } + } + + private static final Map jarFileSystems = new HashMap<>(); + + private static FileSystem getOrCreateJarFileSystemFor(String jarPath) { + synchronized (jarFileSystems) { + return jarFileSystems.computeIfAbsent( + jarPath, + ignored -> { + try { + final URI jarUri = URI.create(jarPath); + System.out.println(jarUri); + return FileSystems.newFileSystem(jarUri, Collections.emptyMap()); + } catch (IOException e) { + throw new UnexpectedException(e); + } + } + ); + } + } + + private static String getResourceUriPath(URI uri) { + final String path = stripToEmpty(uri.getPath()); + + final String host = stripToNull(uri.getHost()); + if (host == null) { + return path; + } + + return "/" + host + path; + } + + public enum SchemeEnum { + CLASSPATH, + JAR, + FILE, + // + ; + + public String toUrlScheme() { + return lowerCase(name()); + } + + public static SchemeEnum fromUrlScheme(String urlScheme) { + if (urlScheme == null) { + return FILE; + } + + for (SchemeEnum scheme : values()) { + if (scheme.toUrlScheme().equals(urlScheme)) { + return scheme; + } + } + + throw new UnexpectedException(String.format("Unsupported resource scheme: %s", urlScheme)); + } + } + + public static class LuaThreadWrapper extends Thread { + private final Globals globals; + + public LuaThreadWrapper(Globals globals, Path rootDirectory) { + super(() -> { + final LuaValue mainChunk = loadScript(globals, rootDirectory.resolve(CLUFiles.MAIN_LUA.getFileName()), CLUFiles.MAIN_LUA.getFileName()); + + final LuaThread luaThread = new LuaThread(globals, mainChunk); + + luaThread.resume(LuaValue.NIL); + }); + + setDaemon(true); + + this.globals = globals; + + start(); + } + + public Globals globals() { + return globals; + } + + } +} diff --git a/vclu/src/main/java/pl/psobiech/opengr8on/vclu/Main.java b/vclu/src/main/java/pl/psobiech/opengr8on/vclu/Main.java new file mode 100644 index 0000000..ce83905 --- /dev/null +++ b/vclu/src/main/java/pl/psobiech/opengr8on/vclu/Main.java @@ -0,0 +1,64 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.vclu; + +import java.nio.file.Path; +import java.nio.file.Paths; + +import org.apache.commons.codec.binary.Base64; +import pl.psobiech.opengr8on.client.CipherKey; +import pl.psobiech.opengr8on.client.device.CLUDevice; +import pl.psobiech.opengr8on.client.device.CipherTypeEnum; +import pl.psobiech.opengr8on.util.FileUtil; +import pl.psobiech.opengr8on.util.IPv4AddressUtil; +import pl.psobiech.opengr8on.util.IPv4AddressUtil.NetworkInterfaceDto; +import pl.psobiech.opengr8on.util.RandomUtil; + +public class Main { + public static void main(String[] args) throws Exception { + final Path rootDirectory = Paths.get("./runtime/root/a").toAbsolutePath(); + FileUtil.mkdir(rootDirectory); + + for (NetworkInterfaceDto localIPv4NetworkInterface : IPv4AddressUtil.getLocalIPv4NetworkInterfaces()) { + System.out.println(localIPv4NetworkInterface); + } + + final NetworkInterfaceDto networkInterface = IPv4AddressUtil.getLocalIPv4NetworkInterfaceByName(args[args.length - 1]).get(); + + final CipherKey projectCipherKey = new CipherKey( + Base64.decodeBase64("mVHTJ/sJd9qTzE1nfLrKxA=="), + Base64.decodeBase64("gOYp2Y1wrPT63icsX90aCA==") + ); + + // TODO: load from config + final CLUDevice cluDevice = new CLUDevice( + 0L, "0eaa55aa55aa", + networkInterface.getAddress(), + CipherTypeEnum.PROJECT, RandomUtil.bytes(16), "00000000".getBytes() + ); + + try (Server server = new Server(networkInterface, rootDirectory, projectCipherKey, cluDevice)) { + server.listen(); + + while (!Thread.interrupted()) { + Thread.yield(); + } + } + } +} \ No newline at end of file diff --git a/vclu/src/main/java/pl/psobiech/opengr8on/vclu/Server.java b/vclu/src/main/java/pl/psobiech/opengr8on/vclu/Server.java new file mode 100644 index 0000000..5a6a4c2 --- /dev/null +++ b/vclu/src/main/java/pl/psobiech/opengr8on/vclu/Server.java @@ -0,0 +1,448 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.vclu; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.Inet4Address; +import java.nio.file.Path; +import java.time.Duration; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.ImmutableTriple; +import org.apache.commons.lang3.tuple.Pair; +import org.luaj.vm2.LuaError; +import org.luaj.vm2.LuaValue; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import pl.psobiech.opengr8on.client.commands.ErrorCommand; +import pl.psobiech.opengr8on.org.apache.commons.net.TFTPServer; +import pl.psobiech.opengr8on.org.apache.commons.net.TFTPServer.ServerMode; +import pl.psobiech.opengr8on.client.CipherKey; +import pl.psobiech.opengr8on.client.Client; +import pl.psobiech.opengr8on.client.Command; +import pl.psobiech.opengr8on.client.commands.DiscoverCLUsCommand; +import pl.psobiech.opengr8on.client.commands.LuaScriptCommand; +import pl.psobiech.opengr8on.client.commands.ResetCommand; +import pl.psobiech.opengr8on.client.commands.SetIpCommand; +import pl.psobiech.opengr8on.client.commands.SetKeyCommand; +import pl.psobiech.opengr8on.client.commands.StartTFTPdCommand; +import pl.psobiech.opengr8on.client.device.CLUDevice; +import pl.psobiech.opengr8on.exceptions.UnexpectedException; +import pl.psobiech.opengr8on.util.IPv4AddressUtil; +import pl.psobiech.opengr8on.util.IPv4AddressUtil.NetworkInterfaceDto; +import pl.psobiech.opengr8on.util.RandomUtil; +import pl.psobiech.opengr8on.util.SocketUtil; +import pl.psobiech.opengr8on.util.SocketUtil.Payload; +import pl.psobiech.opengr8on.util.SocketUtil.UDPSocket; +import pl.psobiech.opengr8on.util.ThreadUtil; +import pl.psobiech.opengr8on.vclu.LuaServer.LuaThreadWrapper; + +public class Server implements AutoCloseable { + private static final Logger LOGGER = LoggerFactory.getLogger(Server.class); + + protected static final int BUFFER_SIZE = 2048; + + private static final byte[] EMPTY_BUFFER = new byte[0]; + + private final DatagramPacket requestPacket = new DatagramPacket(EMPTY_BUFFER, 0); + + private final DatagramPacket responsePacket = new DatagramPacket(new byte[BUFFER_SIZE], BUFFER_SIZE); + + protected final NetworkInterfaceDto networkInterface; + + private final Path rootDirectory; + + private final CLUDevice cluDevice; + + protected final UDPSocket broadcastSocket; + + protected final UDPSocket socket; + + private final TFTPServer tftpServer; + + private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1, ThreadUtil.daemonThreadFactory("cluServer")); + + private LuaThreadWrapper luaThread; + + private CipherKey broadcastCipherKey = CipherKey.DEFAULT_BROADCAST; + + private CipherKey currentCipherKey; + + public Server(NetworkInterfaceDto networkInterface, Path rootDirectory, CipherKey projectCipherKey, CLUDevice cluDevice) { + this.networkInterface = networkInterface; + this.rootDirectory = rootDirectory; + + this.currentCipherKey = projectCipherKey; + this.cluDevice = cluDevice; + + this.luaThread = LuaServer.create(networkInterface, rootDirectory, cluDevice, currentCipherKey); + + try { + this.tftpServer = new TFTPServer( + Client.TFTP_PORT, networkInterface.getAddress(), + ServerMode.GET_AND_REPLACE + ); + + this.broadcastSocket = SocketUtil.udp( + IPv4AddressUtil.parseIPv4("255.255.255.255"), +// networkInterface.getBroadcastAddress(), + Client.COMMAND_PORT + ); + this.socket = SocketUtil.udp(networkInterface.getAddress(), Client.COMMAND_PORT); + } catch (IOException e) { + throw new UnexpectedException(e); + } + } + + public void listen() { + socket.open(); + broadcastSocket.open(); + + try { + this.tftpServer.start( + rootDirectory.toFile() + ); + } catch (IOException e) { + throw new UnexpectedException(e); + } + + executorService + .scheduleAtFixedRate(() -> { + try { + final UUID uuid = UUID.randomUUID(); + + awaitRequestPayload(String.valueOf(uuid), broadcastSocket, broadcastCipherKey, Duration.ofMillis(1000)) + .flatMap(payload -> + onBroadcastCommand(payload) + .map(pair -> + ImmutableTriple.of( + payload, pair.getLeft(), pair.getRight() + ) + ) + ) + .ifPresent(triple -> + respond(uuid, triple.getLeft(), triple.getMiddle(), triple.getRight()) + ); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + } + }, + 1000, 1000, TimeUnit.MILLISECONDS + ); + + executorService + .scheduleAtFixedRate(() -> { + try { + final UUID uuid = UUID.randomUUID(); + + awaitRequestPayload(String.valueOf(uuid), socket, currentCipherKey, Duration.ofMillis(100)) + .flatMap(payload -> + onCommand(payload) + .map(pair -> + ImmutableTriple.of( + payload, pair.getLeft(), pair.getRight() + ) + ) + ) + .ifPresent(triple -> + respond(uuid, triple.getLeft(), triple.getMiddle(), triple.getRight()) + ); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + } + }, + 1000, 100, TimeUnit.MILLISECONDS + ); + } + + private void respond(UUID uuid, Payload requestPayload, CipherKey cipherKey, Command command) { + respond(uuid, cipherKey, requestPayload.address(), requestPayload.port(), command); + } + + private Optional> onBroadcastCommand(Payload payload) { + final byte[] buffer = payload.buffer(); + if (DiscoverCLUsCommand.requestMatches(buffer)) { + return onDiscoverCommand(payload); + } + + if (SetIpCommand.requestMatches(buffer)) { + return onSetIpCommand(payload); + } + + return Optional.empty(); + } + + private Optional> onDiscoverCommand(Payload payload) { + final byte[] buffer = payload.buffer(); + final Optional requestOptional = DiscoverCLUsCommand.requestFromByteArray(buffer); + if (requestOptional.isPresent()) { + final DiscoverCLUsCommand.Request request = requestOptional.get(); + + final byte[] encrypted = request.getEncrypted(); + final byte[] iv = request.getIV(); + final byte[] hash = DiscoverCLUsCommand.hash(currentCipherKey.decrypt(encrypted) + .orElse(RandomUtil.bytes(Command.RANDOM_SIZE))); + + currentCipherKey = cluDevice.getCipherKey(); + broadcastCipherKey = cluDevice.getCipherKey(); + + return Optional.of( + ImmutablePair.of( + CipherKey.DEFAULT_BROADCAST.withIV(iv), + DiscoverCLUsCommand.response( + currentCipherKey.encrypt(hash), + currentCipherKey.getIV(), + cluDevice.getSerialNumber(), + cluDevice.getMacAddress() + ) + ) + ); + } + + return sendError(); + } + + private Optional> onCommand(Payload payload) { + final byte[] buffer = payload.buffer(); + + if (SetIpCommand.requestMatches(buffer)) { + return onSetIpCommand(payload); + } + + if (SetKeyCommand.requestMatches(buffer)) { + return onSetKeyCommand(payload); + } + + if (ResetCommand.requestMatches(buffer)) { + return onResetCommand(payload); + } + + if (LuaScriptCommand.requestMatches(buffer)) { + return onLuaScriptCommand(payload); + } + + if (StartTFTPdCommand.requestMatches(buffer)) { + return onStartFTPdCommand(payload); + } + + return sendError(); + } + + private Optional> onSetIpCommand(Payload payload) { + final byte[] buffer = payload.buffer(); + final Optional requestOptional = SetIpCommand.requestFromByteArray(buffer); + if (requestOptional.isPresent()) { + final SetIpCommand.Request request = requestOptional.get(); + + if (Objects.equals(cluDevice.getSerialNumber(), request.getSerialNumber())) { + return Optional.of( + ImmutablePair.of( + currentCipherKey, + SetIpCommand.response( + cluDevice.getSerialNumber(), + cluDevice.getAddress() + ) + ) + ); + } + } + + return sendError(); + } + + private Optional> onSetKeyCommand(Payload payload) { + final byte[] buffer = payload.buffer(); + final Optional requestOptional = SetKeyCommand.requestFromByteArray(buffer); + if (requestOptional.isPresent()) { + final SetKeyCommand.Request request = requestOptional.get(); + + //final byte[] encrypted = request.getEncrypted(); // Real CLU sends only dummy data + final byte[] key = request.getKey(); + final byte[] iv = request.getIV(); + + final CipherKey newCipherKey = new CipherKey(key, iv); + //if (newCipherKey.decrypt(encrypted).isEmpty()) { + // return sendError(); + //} + + currentCipherKey = newCipherKey; + broadcastCipherKey = CipherKey.DEFAULT_BROADCAST; + + return Optional.of( + ImmutablePair.of( + currentCipherKey, + SetKeyCommand.response() + ) + ); + } + + return sendError(); + } + + private Optional> onResetCommand(Payload payload) { + final byte[] buffer = payload.buffer(); + final Optional requestOptional = ResetCommand.requestFromByteArray(buffer); + if (requestOptional.isPresent()) { + final ResetCommand.Request request = requestOptional.get(); + + try { + this.luaThread.interrupt(); + + this.luaThread.join(); + } catch (InterruptedException e) { + LOGGER.error(e.getMessage(), e); + } + + this.luaThread = LuaServer.create(networkInterface, rootDirectory, cluDevice, currentCipherKey); + + return Optional.of( + ImmutablePair.of( + currentCipherKey, + ResetCommand.response( + cluDevice.getAddress() + ) + ) + ); + } + + return sendError(); + } + + private Optional> onLuaScriptCommand(Payload payload) { + final byte[] buffer = payload.buffer(); + final Optional requestOptional = LuaScriptCommand.requestFromByteArray(buffer); + if (requestOptional.isPresent()) { + final LuaScriptCommand.Request request = requestOptional.get(); + + final LuaValue luaValue; + try { + luaValue = luaThread.globals() + .load("return %s".formatted(request.getScript())) + .call(); + } catch (LuaError e) { + LOGGER.error(e.getMessage(), e); + + return sendError(); + } + + String returnValue; + if (luaValue.isstring()) { + returnValue = String.valueOf(luaValue); + } else { + returnValue = "nil"; + } + + return Optional.of( + ImmutablePair.of( + currentCipherKey, + LuaScriptCommand.response( + cluDevice.getAddress(), + request.getSessionId(), + returnValue + ) + ) + ); + } + + return sendError(); + } + + private Optional> onStartFTPdCommand(Payload payload) { + final byte[] buffer = payload.buffer(); + final Optional requestOptional = StartTFTPdCommand.requestFromByteArray(buffer); + if (requestOptional.isPresent()) { + return Optional.of( + ImmutablePair.of( + currentCipherKey, + StartTFTPdCommand.response() + ) + ); + } + + return sendError(); + } + + private Optional> sendError() { + return Optional.of( + ImmutablePair.of( + currentCipherKey, + ErrorCommand.response() + ) + ); + } + + protected Optional awaitRequestPayload(String uuid, UDPSocket socket, CipherKey responseCipherKey, Duration timeout) { + final Optional encryptedPayload = socket.tryReceive(responsePacket, timeout); + if (encryptedPayload.isEmpty()) { + return Optional.empty(); + } + + return Client.tryDecrypt(uuid, responseCipherKey, encryptedPayload.get()); + } + + protected void respond(UUID uuid, CipherKey cipherKey, Inet4Address ipAddress, int port, Command command) { + respond(command.uuid(uuid), cipherKey, ipAddress, port, command.asByteArray()); + } + + protected void respond(String uuid, CipherKey cipherKey, Inet4Address ipAddress, int port, byte[] buffer) { + final Payload requestPayload = Payload.of(ipAddress, port, buffer); + LOGGER.trace( + "\n%s\n--D->\t%s // %s" + .formatted(uuid, requestPayload, cipherKey) + ); + + final byte[] encryptedRequest = cipherKey.encrypt(requestPayload.buffer()); + // LOGGER.trace( + // "\n%s\n--E->\t%s // %s" + // .formatted(uuid, Payload.of(ipAddress, port, encryptedRequest), cipherKey) + // ); + + synchronized (this) { + requestPacket.setData(encryptedRequest); + requestPacket.setAddress(requestPayload.address()); + requestPacket.setPort(requestPayload.port()); + + socket.send(requestPacket); + + requestPacket.setData(EMPTY_BUFFER); + } + } + + @Override + public void close() { + tftpServer.close(); + + synchronized (this) { + broadcastSocket.close(); + } + + synchronized (this) { + socket.close(); + } + + executorService.shutdown(); + } +} diff --git a/vclu/src/main/java/pl/psobiech/opengr8on/vclu/VirtualCLU.java b/vclu/src/main/java/pl/psobiech/opengr8on/vclu/VirtualCLU.java new file mode 100644 index 0000000..57a01f5 --- /dev/null +++ b/vclu/src/main/java/pl/psobiech/opengr8on/vclu/VirtualCLU.java @@ -0,0 +1,200 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.vclu; + +import java.lang.management.ManagementFactory; +import java.net.Inet4Address; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import org.luaj.vm2.LuaValue; +import org.luaj.vm2.lib.OneArgFunction; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class VirtualCLU extends VirtualObject { + private static final Logger LOGGER = LoggerFactory.getLogger(VirtualCLU.class); + + private final static Map TIME_ZONES = Map.ofEntries( + Map.entry(0, ZoneId.of("Europe/Warsaw")), + Map.entry(1, ZoneId.of("Europe/London")), + Map.entry(2, ZoneId.of("Europe/Moscow")), + Map.entry(3, ZoneId.of("Europe/Istanbul")), + Map.entry(4, ZoneId.of("Europe/Athens")), + Map.entry(5, ZoneId.of("Asia/Dubai")), + Map.entry(6, ZoneId.of("Asia/Jakarta")), + Map.entry(7, ZoneId.of("Asia/Hong_Kong")), + Map.entry(8, ZoneId.of("Australia/Sydney")), + Map.entry(9, ZoneId.of("Australia/Perth")), + Map.entry(10, ZoneId.of("Australia/Brisbane")), + Map.entry(11, ZoneId.of("Pacific/Auckland")), + Map.entry(12, ZoneId.of("Pacific/Honolulu")), + Map.entry(13, ZoneId.of("America/Anchorage")), + Map.entry(14, ZoneId.of("America/Chicago")), + Map.entry(15, ZoneId.of("America/New_York")), + Map.entry(16, ZoneId.of("America/Barbados")), + Map.entry(17, ZoneId.of("America/Sao_Paulo")), + Map.entry(18, ZoneId.of("America/Bogota")), + Map.entry(19, ZoneId.of("America/Buenos_Aires")), + Map.entry(20, ZoneId.of("America/Chicago")), + Map.entry(21, ZoneId.of("America/Los_Angeles")), + Map.entry(22, ZoneOffset.UTC) + ); + + public VirtualCLU(String name, Inet4Address address) { + super(name); + + funcs.put(0, new OneArgFunction() { + @Override + public LuaValue call(LuaValue arg) { + VirtualCLU.this.vars.put(1, arg); + + if (!arg.isnil()) { + final String logValue = String.valueOf(arg.checkstring()); + LOGGER.info(VirtualCLU.this.name + ": " + logValue); + } + + return LuaValue.NIL; + } + }); + + funcs.put(1, new OneArgFunction() { + @Override + public LuaValue call(LuaValue arg) { + VirtualCLU.this.vars.put(1, LuaValue.NIL); + + return LuaValue.NIL; + } + }); + + features.put(0, new OneArgFunction() { + @Override + public LuaValue call(LuaValue arg) { + return LuaValue.valueOf( + TimeUnit.MILLISECONDS.toSeconds(ManagementFactory.getRuntimeMXBean().getUptime()) + ); + } + }); + + VirtualCLU.this.vars.put(2, LuaValue.valueOf(1)); + + features.put(5, new OneArgFunction() { + @Override + public LuaValue call(LuaValue arg) { + return LuaValue.valueOf( + ZonedDateTime.now() + .withZoneSameInstant(TIME_ZONES.get(VirtualCLU.this.vars.get(14).checkint())) + .format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + ); + } + }); + + features.put(6, new OneArgFunction() { + @Override + public LuaValue call(LuaValue arg) { + return LuaValue.valueOf( + ZonedDateTime.now() + .withZoneSameInstant(TIME_ZONES.get(VirtualCLU.this.vars.get(14).checkint())) + .format(DateTimeFormatter.ofPattern("HH:mm:ss")) + ); + } + }); + + features.put(7, new OneArgFunction() { + @Override + public LuaValue call(LuaValue arg) { + return LuaValue.valueOf( + ZonedDateTime.now() + .withZoneSameInstant(TIME_ZONES.get(VirtualCLU.this.vars.get(14).checkint())) + .getDayOfMonth() + ); + } + }); + + features.put(8, new OneArgFunction() { + @Override + public LuaValue call(LuaValue arg) { + return LuaValue.valueOf( + ZonedDateTime.now() + .withZoneSameInstant(TIME_ZONES.get(VirtualCLU.this.vars.get(14).checkint())) + .getMonthValue() + ); + } + }); + + features.put(9, new OneArgFunction() { + @Override + public LuaValue call(LuaValue arg) { + return LuaValue.valueOf( + ZonedDateTime.now() + .withZoneSameInstant(TIME_ZONES.get(VirtualCLU.this.vars.get(14).checkint())) + .getYear() + ); + } + }); + + features.put(10, new OneArgFunction() { + @Override + public LuaValue call(LuaValue arg) { + return LuaValue.valueOf( + ZonedDateTime.now() + .withZoneSameInstant(TIME_ZONES.get(VirtualCLU.this.vars.get(14).checkint())) + .getDayOfWeek() + .getValue() + ); + } + }); + + features.put(11, new OneArgFunction() { + @Override + public LuaValue call(LuaValue arg) { + return LuaValue.valueOf( + ZonedDateTime.now() + .withZoneSameInstant(TIME_ZONES.get(VirtualCLU.this.vars.get(14).checkint())) + .getHour() + ); + } + }); + + features.put(12, new OneArgFunction() { + @Override + public LuaValue call(LuaValue arg) { + return LuaValue.valueOf( + ZonedDateTime.now() + .withZoneSameInstant(TIME_ZONES.get(VirtualCLU.this.vars.get(14).checkint())) + .getMinute() + ); + } + }); + + features.put(13, new OneArgFunction() { + @Override + public LuaValue call(LuaValue arg) { + return LuaValue.valueOf( + Instant.now().getEpochSecond() + ); + } + }); + } +} diff --git a/vclu/src/main/java/pl/psobiech/opengr8on/vclu/VirtualGate.java b/vclu/src/main/java/pl/psobiech/opengr8on/vclu/VirtualGate.java new file mode 100644 index 0000000..183f90a --- /dev/null +++ b/vclu/src/main/java/pl/psobiech/opengr8on/vclu/VirtualGate.java @@ -0,0 +1,25 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.vclu; + +public class VirtualGate extends VirtualObject { + public VirtualGate(String name) { + super(name); + } +} diff --git a/vclu/src/main/java/pl/psobiech/opengr8on/vclu/VirtualObject.java b/vclu/src/main/java/pl/psobiech/opengr8on/vclu/VirtualObject.java new file mode 100644 index 0000000..5d9b5eb --- /dev/null +++ b/vclu/src/main/java/pl/psobiech/opengr8on/vclu/VirtualObject.java @@ -0,0 +1,78 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.vclu; + +import java.util.HashMap; +import java.util.Map; + +import org.luaj.vm2.LuaFunction; +import org.luaj.vm2.LuaValue; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class VirtualObject { + private static final Logger LOGGER = LoggerFactory.getLogger(VirtualObject.class); + + protected final String name; + + protected final Map vars = new HashMap<>(); + + protected final Map features = new HashMap<>(); + + protected final Map funcs = new HashMap<>(); + + protected final Map events = new HashMap<>(); + + public VirtualObject(String name) { + this.name = name; + } + + public LuaValue get(int index) { + final LuaValue luaValue = vars.get(index); + if (luaValue != null) { + return luaValue; + } + + final LuaFunction luaFunction = features.get(index); + if (luaFunction != null) { + return luaFunction.call(); + } + + return LuaValue.NIL; + } + + public void set(int index, LuaValue luaValue) { + vars.put(index, luaValue); + } + + public LuaValue execute(int index, LuaValue luaValue) { + final LuaFunction luaFunction = funcs.get(index); + if (luaFunction != null) { + return luaFunction.call(luaValue); + } + + LOGGER.warn("Not implemented: " + name + ":execute(" + index + ")"); + + return LuaValue.NIL; + } + + public void addEvent(int index, LuaFunction luaValue) { + events.put(index, luaValue); + } +} diff --git a/vclu/src/main/java/pl/psobiech/opengr8on/vclu/VirtualRemoteCLU.java b/vclu/src/main/java/pl/psobiech/opengr8on/vclu/VirtualRemoteCLU.java new file mode 100644 index 0000000..37e3b06 --- /dev/null +++ b/vclu/src/main/java/pl/psobiech/opengr8on/vclu/VirtualRemoteCLU.java @@ -0,0 +1,54 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.vclu; + +import java.net.Inet4Address; +import java.util.Optional; + +import org.luaj.vm2.LuaValue; +import org.luaj.vm2.lib.OneArgFunction; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import pl.psobiech.opengr8on.client.CLUClient; +import pl.psobiech.opengr8on.client.CipherKey; +import pl.psobiech.opengr8on.util.IPv4AddressUtil.NetworkInterfaceDto; + +public class VirtualRemoteCLU extends VirtualObject { + private static final Logger LOGGER = LoggerFactory.getLogger(VirtualRemoteCLU.class); + + public VirtualRemoteCLU(String name, Inet4Address address, NetworkInterfaceDto networkInterface, CipherKey cipherKey) { + super(name); + + funcs.put(0, new OneArgFunction() { + @Override + public LuaValue call(LuaValue arg) { + final String script = String.valueOf(arg.checkstring()); + + try (CLUClient client = new CLUClient(networkInterface, address, cipherKey)) { + final Optional execute = client.execute(script); + if (execute.isPresent()) { + return LuaValue.valueOf(execute.get()); + } + } + + return LuaValue.NIL; + } + }); + } +} diff --git a/vclu/src/main/java/pl/psobiech/opengr8on/vclu/VirtualSystem.java b/vclu/src/main/java/pl/psobiech/opengr8on/vclu/VirtualSystem.java new file mode 100644 index 0000000..054e906 --- /dev/null +++ b/vclu/src/main/java/pl/psobiech/opengr8on/vclu/VirtualSystem.java @@ -0,0 +1,185 @@ +/* + * OpenGr8on, open source extensions to systems based on Grenton devices + * Copyright (C) 2023 Piotr Sobiech + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package pl.psobiech.opengr8on.vclu; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import org.luaj.vm2.LuaFunction; +import org.luaj.vm2.LuaValue; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import pl.psobiech.opengr8on.client.CLUClient; +import pl.psobiech.opengr8on.client.CipherKey; +import pl.psobiech.opengr8on.client.device.CLUDevice; +import pl.psobiech.opengr8on.exceptions.UnexpectedException; +import pl.psobiech.opengr8on.util.IPv4AddressUtil; +import pl.psobiech.opengr8on.util.IPv4AddressUtil.NetworkInterfaceDto; +import pl.psobiech.opengr8on.util.ThreadUtil; + +public class VirtualSystem { + private static final Logger LOGGER = LoggerFactory.getLogger(VirtualSystem.class); + + private final ScheduledExecutorService executors = Executors.newSingleThreadScheduledExecutor(ThreadUtil.daemonThreadFactory("LuaServer")); + + private final NetworkInterfaceDto networkInterface; + + private final CLUDevice device; + + private final CipherKey cipherKey; + + private final Map objects = new HashMap<>(); + + private final Map objectsByName = new HashMap<>(); + + private ScheduledFuture clientReport = null; + + private int objectIdGenerator = 0; + + public VirtualSystem(NetworkInterfaceDto networkInterface, CLUDevice device, CipherKey cipherKey) { + this.networkInterface = networkInterface; + this.device = device; + this.cipherKey = cipherKey; + } + + public VirtualObject getObject(int index) { + return objects.get(index); + } + + public VirtualObject getObject(String name) { + return objectsByName.get(name); + } + + public int newObject(int index, String name, int ipAddress) { + final int objectId = objectIdGenerator++; + + final VirtualObject virtualObject = switch (index) { + case 0 -> new VirtualCLU(name, IPv4AddressUtil.parseIPv4(ipAddress)); + case 1 -> new VirtualRemoteCLU(name, IPv4AddressUtil.parseIPv4(ipAddress), networkInterface, cipherKey); + case 44 -> new VirtualObject(name); + default -> new VirtualObject(name); + }; + + objects.put(objectId, virtualObject); + objectsByName.put(name, virtualObject); + + return objectId; + } + + public int newGate(int index, String name) { + final int objectId = objectIdGenerator++; + + final VirtualObject virtualObject = switch (index) { + case 121 -> new VirtualGate(name); + default -> new VirtualObject(name); + }; + + objects.put(objectId, virtualObject); + objectsByName.put(name, virtualObject); + + return objectId; + } + + public void setup() { + for (VirtualObject value : objects.values()) { + final LuaFunction luaFunction = value.events.get(0); + if (luaFunction != null) { + luaFunction.call(); + } + } + } + + public void loop() { + sleep(100); + } + + public void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + + throw new UnexpectedException(e); + } + } + + public String clientRegister(String address, int port, int sessionId, List subscription) { + if (clientReport != null) { + clientReport.cancel(true); + } + System.out.println(address); + clientReport = executors.scheduleAtFixedRate( + () -> { + try { + final String valuesAsString = "clientReport:" + sessionId + ":" + fetchValues(subscription); + + try (CLUClient client = new CLUClient(networkInterface, IPv4AddressUtil.parseIPv4(address), cipherKey, port)) { + client.clientReport(valuesAsString); + } + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + } + }, + 1, 1, TimeUnit.SECONDS + ); + + return "clientReport:" + sessionId + ":" + fetchValues(subscription); + } + + public LuaValue clientDestroy(String ipAddress, int port, int sessionId) { + if (clientReport != null) { + clientReport.cancel(true); + } + + clientReport = null; + + return LuaValue.valueOf(sessionId); + } + + public String fetchValues(List subscription) { + String ret = ""; + for (Subscription entry : subscription) { + final String name = entry.name(); + final Integer index = entry.index(); + + if (ret.length() > 0) { + ret += ","; + } + + final LuaValue luaValue = getObject(name).get(index); + if (luaValue.isnumber()) { + ret += luaValue.checklong(); + } else if (luaValue.isstring()) { + ret += "\"" + luaValue + "\""; + } else { + ret += String.valueOf(luaValue); + } + } + + return "{" + ret + "}"; + } + + public record Subscription(String name, int index) { + } +} diff --git a/vclu/src/main/resources/INIT.LUA b/vclu/src/main/resources/INIT.LUA new file mode 100644 index 0000000..a19c116 --- /dev/null +++ b/vclu/src/main/resources/INIT.LUA @@ -0,0 +1,156 @@ +function collectgarbage() + -- NOP +end + +function logDebug(...) + print(...) + + api.logDebug(...) +end + +function log(...) + print(...) + + api.logInfo(...) +end + +function logInfo(...) + print(...) + + api.logInfo(...) +end + +function logWarning(...) + print(...) + + api.logWarning(...) +end + +function logError(...) + print(...) + + api.logError(...) +end + +-- +-- +-- + +SYSTEM = {} +SYSTEM.__index = SYSTEM + +function SYSTEM:Init() + api.setup() +end + +function SYSTEM:Loop() + api.loop() +end + +function SYSTEM:Wait(milliseconds) + api.sleep(milliseconds) +end + +function SYSTEM:clientRegister(a, b, c, d) + return api.clientRegister(a, b, c, d) +end + +function SYSTEM:clientDestroy(a, b, c) + return api.clientDestroy(a, b, c) +end + +function SYSTEM:fetchValues(d) + return api.fetchValues(d) +end + +function SYSTEM:mqttRegister() + print("SYSTEM", ":mqttRegister") +end + +function SYSTEM:mqttDestroy() + print("SYSTEM", ":mqttDestroy") +end + +-- +-- +-- + +OBJECT = {} +OBJECT.__index = OBJECT + +function OBJECT:new(idx, a, b, c) + local self = {} + setmetatable(self, OBJECT) + + if idx == 0 or idx == 1 then + self['name'] = b + + self['_id'] = api.newObject(idx, b, a) + elseif idx == 44 then + self['name'] = a + self['_id'] = api.newObject(idx, a, 0) + else + self['parent'] = a + self['name'] = c + + self['_id'] = api.newObject(idx, c, 0) + end + + return self +end + +function OBJECT:get(idx) + return api.get(self['_id'], idx) +end + +function OBJECT:set(idx, value) + api.set(self['_id'], idx, value) +end + +function OBJECT:execute(idx, name) + return api.execute(self['_id'], idx, name) +end + +function OBJECT:add_event(idx, fn) + api.addEvent(self['_id'], idx, fn) +end + +-- +-- +-- + +GATE = {} +GATE.__index = GATE + +function GATE:new(idx, a) + local self = {} + setmetatable(self, GATE) + + if idx == 121 then + self['name'] = a + + self['_id'] = api.newGate(idx, a) + else + self['name'] = a + + self['_id'] = api.newGate(idx, a) + end + + return self +end + +function GATE:get(idx) + return api.get(self['_id'], idx) +end + +function GATE:set(idx, value) + api.set(self['_id'], idx, value) +end + +function GATE:execute(idx, name) + return api.execute(self['_id'], idx, name) +end + +function GATE:add_event(idx, fn) + api.addEvent(self['_id'], idx, fn) +end diff --git a/vclu/src/main/resources/logback.xml b/vclu/src/main/resources/logback.xml new file mode 100644 index 0000000..ee23a6d --- /dev/null +++ b/vclu/src/main/resources/logback.xml @@ -0,0 +1,32 @@ + + + + + %date{"yyyy-MM-dd'T'HH:mm:ss,SSSXXX", UTC} [%level] %logger{15} - %message%n%xException{10} + + + + + + + + + + + diff --git a/vclu/src/test/resources/logback-test.xml b/vclu/src/test/resources/logback-test.xml new file mode 100644 index 0000000..3af7c46 --- /dev/null +++ b/vclu/src/test/resources/logback-test.xml @@ -0,0 +1,28 @@ + + + + + %date{"yyyy-MM-dd'T'HH:mm:ss,SSSXXX", UTC} [%level] %logger{15} - %message%n%xException{10} + + + + + + +