commit 721f893540fb8812c47a1fbe212965197572a3c9 Author: Florian Thienel Date: Sun Sep 19 14:19:47 2021 +0200 initial project setup diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..bec8a4f --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +# tetra-pei + +The tetra-pei library allows to communicate with a TETRA radio terminal through its peripheral equipment interface (PEI), with the main focus on simple radio control and the handling of SDS messages. This implementation is solely based on the relevant ETSI specifications: +* ETSI TS 100 392-2 V2.9.2 (2020-06): Terrestrial Trunked Radio (TETRA); Voice plus Data (V+D); Part 2: Air Interface (AI) +* ETSI EN 300 392-5 V2.7.1 (2020-04): Terrestrial Trunked Radio (TETRA); Voice plus Data (V+D) and Direct Mode Operation (DMO); Part 5: Peripheral Equipment Interface (PEI) + +## Restrictions + +* store/forward control information is not handled +* the only supported text encoding scheme is ISO8859-1 + +## License + +This library is published under the [GNU General Public License, Version 3](LICENSE) + +Copyright [Florian Thienel](https://thecodingflow.com) diff --git a/com/com.go b/com/com.go new file mode 100644 index 0000000..04a508c --- /dev/null +++ b/com/com.go @@ -0,0 +1,321 @@ +package com + +import ( + "context" + "fmt" + "io" + "log" + "strings" + "time" +) + +const ( + readBufferSize = 1024 +) + +func New(device io.ReadWriter) *COM { + lines := readLoop(device) + commands := make(chan command) + result := &COM{ + commands: commands, + closed: make(chan struct{}), + indications: make(map[string]indicationConfig), + } + + go func() { + log.Print("entering COM loop") + defer log.Print("exiting COM loop") + defer close(result.closed) + + var commandCancelled <-chan struct{} + var activeCommand *command + var activeIndication *indication + tick := time.NewTicker(100 * time.Millisecond) + defer tick.Stop() + + for { + select { + case line, valid := <-lines: + if !valid { + log.Print("lines channel closed") + return + } + // log.Printf("rx: %s", line) + + switch { + case activeIndication != nil: + activeIndication.AddLine(line) + if activeIndication.Complete() { + activeIndication = nil + } + case activeCommand != nil: + activeIndication = result.newIndication(line) + if activeIndication != nil { + break + } + activeCommand.AddLine(line) + if activeCommand.Complete() { + commandCancelled = nil + activeCommand = nil + } + default: + activeIndication = result.newIndication(line) + } + case <-commandCancelled: + commandCancelled = nil + activeCommand = nil + case <-tick.C: + } + if activeCommand == nil { + select { + case cmd := <-commands: + if len(cmd.request) == 0 { + break + } + + txbytes := make([]byte, 0, len(cmd.request)+2) + txbytes = append(txbytes, []byte(cmd.request)...) + lastbyte := txbytes[len(txbytes)-1] + if (lastbyte != 0x1a) && (lastbyte != 0x1b) { + txbytes = append(txbytes, 0x0d, 0x0a) + } + // log.Printf("tx: %v", txbytes) + device.Write(txbytes) + commandCancelled = cmd.cancelled + activeCommand = &cmd + default: + } + } + } + }() + + return result +} + +type COM struct { + commands chan<- command + closed chan struct{} + + indications map[string]indicationConfig +} + +func readLoop(r io.Reader) <-chan string { + lines := make(chan string, 1) + go func() { + log.Print("entering read loop") + defer log.Print("exiting read loop") + + buf := make([]byte, readBufferSize) + currentLine := make([]byte, 0, readBufferSize) + for { + n, err := r.Read(buf) + if err == io.EOF { + if len(currentLine) > 0 { + lines <- string(currentLine) + } + close(lines) + return + } else if err != nil { + log.Printf("read error: %v", err) + if len(currentLine) > 0 { + lines <- string(currentLine) + } + close(lines) + return + } + + for _, b := range buf[0:n] { + switch { + case b == '\n': + if len(currentLine) == 0 { + continue + } + lines <- string(currentLine) + currentLine = currentLine[:0] + case b < ' ': + continue + default: + currentLine = append(currentLine, b) + } + } + } + }() + return lines +} + +func (c *COM) Closed() bool { + select { + case <-c.closed: + return true + default: + return false + } +} + +func (c *COM) AddIndication(prefix string, trailingLines int, handler func(lines []string)) error { + config := indicationConfig{ + prefix: strings.ToUpper(prefix), + trailingLines: trailingLines, + handler: handler, + } + c.indications[config.prefix] = config + return nil +} + +func (c *COM) newIndication(line string) *indication { + for _, config := range c.indications { + result := config.NewIfMatches(line) + if result != nil { + log.Printf("%s is an indication", config.prefix) + return result + } + } + return nil +} + +func (c *COM) ClearSyntaxErrors(ctx context.Context) error { + for true { + _, err := c.AT(ctx, "AT") + if err == nil { + return nil + } + if err.Error() == "+CME ERROR: 35" { + log.Printf(".") + time.Sleep(200) + } else { + return err + } + } + return nil +} + +func (c *COM) AT(ctx context.Context, request string) ([]string, error) { + cmd := command{ + request: request, + response: make(chan []string, 1), + err: make(chan error, 1), + cancelled: ctx.Done(), + completed: make(chan struct{}), + } + + select { + case c.commands <- cmd: + case <-ctx.Done(): + return nil, ctx.Err() + case <-time.After(500 * time.Millisecond): + return nil, fmt.Errorf("AT sending queue timeout") + } + + select { + case response := <-cmd.response: + return response, nil + case err := <-cmd.err: + return nil, err + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +func (c *COM) ATs(ctx context.Context, requests ...string) error { + for _, request := range requests { + _, err := c.AT(ctx, request) + if err != nil { + return fmt.Errorf("%s failed: %w", request, err) + } + } + return nil +} + +type indicationConfig struct { + prefix string + trailingLines int + handler func(lines []string) +} + +func (c *indicationConfig) NewIfMatches(line string) *indication { + if !strings.HasPrefix(strings.ToUpper(line), c.prefix) { + return nil + } + result := &indication{ + config: *c, + lines: []string{line}, + } + if result.Complete() { + c.handler([]string{line}) + return nil + } + + return result +} + +type indication struct { + config indicationConfig + lines []string +} + +func (ind *indication) AddLine(line string) { + log.Printf("%s add line %s, actual: %d, expected %d", ind.config.prefix, line, len(ind.lines), ind.config.trailingLines) + if ind.Complete() { + return + } + + ind.lines = append(ind.lines, line) + if ind.Complete() { + log.Printf("%s is complete, actual: %d, expected %d\n%v", ind.config.prefix, len(ind.lines), ind.config.trailingLines, strings.Join(ind.lines, "\n")) + go func() { + ind.config.handler(ind.lines) + }() + } +} + +func (ind *indication) Complete() bool { + return len(ind.lines) >= ind.config.trailingLines+1 +} + +type command struct { + lines []string + request string + response chan []string + err chan error + cancelled <-chan struct{} + completed chan struct{} +} + +func (c *command) AddLine(line string) { + select { + case <-c.cancelled: + return + case <-c.completed: + return + default: + } + + saniLine := strings.TrimSpace(strings.ToUpper(line)) + switch { + case saniLine == "OK": + c.response <- c.lines + close(c.completed) + case strings.HasPrefix(saniLine, "ERROR"): + c.err <- fmt.Errorf("%s", line) + close(c.completed) + case strings.HasPrefix(saniLine, "+CME ERROR:"): + c.err <- fmt.Errorf("%s", line) + close(c.completed) + case strings.HasPrefix(saniLine, "+CMS ERROR"): + c.err <- fmt.Errorf("%s", line) + close(c.completed) + default: + c.lines = append(c.lines, line) + } +} + +func (c *command) Complete() bool { + select { + case <-c.cancelled: + return true + case <-c.completed: + return true + default: + return false + } +} diff --git a/com/com_test.go b/com/com_test.go new file mode 100644 index 0000000..a28fcc8 --- /dev/null +++ b/com/com_test.go @@ -0,0 +1,180 @@ +package com + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestReadLoop_CloseDevice(t *testing.T) { + device := NewInMemory() + lines := readLoop(device) + device.Close() + + _, valid := <-lines + + assert.False(t, valid) +} + +func TestReadLoop_ReadLine(t *testing.T) { + device := NewInMemory() + lines := readLoop(device) + + go func() { + time.Sleep(100 * time.Millisecond) + device.PrepareRead([]byte("hello\r\n\nworld")) + }() + + firstLine, valid := <-lines + + assert.True(t, valid) + assert.Equal(t, "hello", firstLine) + + device.Close() + lastLine, valid := <-lines + + assert.True(t, valid) + assert.Equal(t, "world", lastLine) + + _, valid = <-lines + + assert.False(t, valid) +} + +func TestCOM_CloseDevice(t *testing.T) { + device := NewInMemory() + com := New(device) + + device.Close() + + time.Sleep(1 * time.Millisecond) + assert.True(t, com.Closed()) +} + +func TestCOM_ReadAllGarbageOnStartup(t *testing.T) { + device := NewInMemory() + defer device.Close() + device.PrepareRead([]byte("CME ERROR: 35\r\n\n\nCME ERROR: 35\r\n\n")) + + New(device) + + time.Sleep(1 * time.Millisecond) + assert.True(t, device.IsReadEmpty()) +} + +func TestCOM_Indications(t *testing.T) { + device := NewInMemory() + + com := New(device) + actual := make([][]string, 3) + com.AddIndication("Ind0:", 0, func(lines []string) { + actual[0] = lines + }) + com.AddIndication("Ind1:", 1, func(lines []string) { + actual[1] = lines + }) + com.AddIndication("Ind2:", 2, func(lines []string) { + actual[2] = lines + }) + expected := [][]string{ + {"ind0:message"}, + {"Ind1:header", "message"}, + {"IND2:header", "message1", "message2"}, + } + + device.PrepareRead([]byte("ind0:message\r\nInd1:header\r\nmessage\r\nIND2:header\r\nmessage1\r\nmessage2")) + device.CloseWhenEmpty(true) + device.WaitUntilClosed() + time.Sleep(10 * time.Millisecond) + + assert.Equal(t, fmt.Sprintf("%v", expected), fmt.Sprintf("%v", actual)) +} + +func TestCOM_SimpleCommand(t *testing.T) { + device := NewInMemory() + defer device.Close() + com := New(device) + go func() { + device.WaitUntilWritten() + time.Sleep(10 * time.Millisecond) + device.PrepareRead([]byte("OK\r\n")) + }() + response, err := com.AT(context.Background(), "AT") + assert.NoError(t, err) + assert.Empty(t, response) +} + +func TestCOM_CommandWithData(t *testing.T) { + device := NewInMemory() + defer device.Close() + com := New(device) + go func() { + device.WaitUntilWritten() + time.Sleep(10 * time.Millisecond) + device.PrepareRead([]byte("message1\r\n\r\nmessage2\r\nOK\r\n")) + }() + expected := []string{"message1", "message2"} + actual, err := com.AT(context.Background(), "AT") + assert.NoError(t, err) + assert.Equal(t, expected, actual) +} + +func TestCOM_CancelCommand(t *testing.T) { + device := NewInMemory() + defer device.Close() + ctx, cancel := context.WithCancel(context.Background()) + com := New(device) + go func() { + device.WaitUntilWritten() + time.Sleep(10 * time.Millisecond) + cancel() + }() + response, err := com.AT(ctx, "AT") + assert.Error(t, err) + assert.Empty(t, response) +} + +func TestCOM_CommandWithError(t *testing.T) { + device := NewInMemory() + defer device.Close() + com := New(device) + go func() { + device.WaitUntilWritten() + time.Sleep(10 * time.Millisecond) + device.PrepareRead([]byte("first line\r\nError at last\r\n")) + }() + response, err := com.AT(context.Background(), "AT") + assert.Error(t, err) + assert.Empty(t, response) +} + +func TestCOM_CommandWithCMEError(t *testing.T) { + device := NewInMemory() + defer device.Close() + com := New(device) + go func() { + device.WaitUntilWritten() + time.Sleep(10 * time.Millisecond) + device.PrepareRead([]byte("first line\r\n+CME Error: 35\r\n")) + }() + response, err := com.AT(context.Background(), "AT") + assert.Error(t, err) + assert.Empty(t, response) +} + +func TestCOM_CommandWithCMSError(t *testing.T) { + device := NewInMemory() + defer device.Close() + com := New(device) + go func() { + device.WaitUntilWritten() + time.Sleep(10 * time.Millisecond) + device.PrepareRead([]byte("first line\r\n+CMS Error: 35\r\n")) + }() + response, err := com.AT(context.Background(), "AT") + assert.Error(t, err) + assert.Empty(t, response) +} diff --git a/com/in_memory.go b/com/in_memory.go new file mode 100644 index 0000000..3f5ced1 --- /dev/null +++ b/com/in_memory.go @@ -0,0 +1,143 @@ +package com + +import ( + "io" + "sync" + "time" +) + +func NewInMemory() *InMemory { + return &InMemory{ + readBuffer: []byte{}, + writeBuffer: []byte{}, + readLock: new(sync.RWMutex), + writeLock: new(sync.RWMutex), + writeSignal: make(chan bool), + closed: make(chan struct{}), + } +} + +type InMemory struct { + readBuffer []byte + writeBuffer []byte + readLock *sync.RWMutex + writeLock *sync.RWMutex + writeSignal chan bool + closed chan struct{} + closeWhenEmpty bool +} + +func (rw *InMemory) Close() error { + select { + case <-rw.closed: + default: + close(rw.closed) + } + return nil +} + +func (rw *InMemory) WaitUntilClosed() { + <-rw.closed +} + +func (rw *InMemory) Read(p []byte) (int, error) { + for { + rw.readLock.RLock() + if len(rw.readBuffer) > 0 { + rw.readLock.RUnlock() + break + } + rw.readLock.RUnlock() + select { + case <-rw.closed: + return 0, io.EOF + case <-time.After(10 * time.Millisecond): + continue + } + } + + select { + case <-rw.closed: + return 0, io.EOF + default: + } + + rw.readLock.Lock() + defer rw.readLock.Unlock() + n := len(p) + if n > len(rw.readBuffer) { + n = len(rw.readBuffer) + } + copy(p, rw.readBuffer[0:n]) + if n < len(rw.readBuffer) { + rw.readBuffer = rw.readBuffer[n:] + } else { + rw.readBuffer = []byte{} + } + if rw.closeWhenEmpty && len(rw.readBuffer) == 0 { + close(rw.closed) + } + return n, nil +} + +func (rw *InMemory) PrepareRead(p []byte) { + rw.readLock.Lock() + defer rw.readLock.Unlock() + + rw.readBuffer = append(rw.readBuffer, p...) +} + +func (rw *InMemory) ClearRead() { + rw.readLock.Lock() + defer rw.readLock.Unlock() + + rw.readBuffer = []byte{} + + if rw.closeWhenEmpty && len(rw.readBuffer) == 0 { + close(rw.closed) + } +} + +func (rw *InMemory) IsReadEmpty() bool { + rw.readLock.RLock() + defer rw.readLock.RUnlock() + + return len(rw.readBuffer) == 0 +} + +func (rw *InMemory) CloseWhenEmpty(value bool) { + rw.readLock.Lock() + defer rw.readLock.Unlock() + + rw.closeWhenEmpty = value +} + +func (rw *InMemory) Write(p []byte) (int, error) { + rw.writeLock.Lock() + defer rw.writeLock.Unlock() + + rw.writeBuffer = append(rw.writeBuffer, p...) + select { + case rw.writeSignal <- true: + default: + } + return len(p), nil +} + +func (rw *InMemory) Written() []byte { + rw.writeLock.RLock() + defer rw.writeLock.RUnlock() + + return rw.writeBuffer +} + +func (rw *InMemory) ClearWrite() { + rw.writeLock.Lock() + defer rw.writeLock.Unlock() + + rw.writeBuffer = []byte{} +} + +func (rw *InMemory) WaitUntilWritten() { + <-rw.writeSignal +} diff --git a/com/in_memory_test.go b/com/in_memory_test.go new file mode 100644 index 0000000..3cffe09 --- /dev/null +++ b/com/in_memory_test.go @@ -0,0 +1,80 @@ +package com + +import ( + "io" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestInMemory_Read(t *testing.T) { + tt := []struct { + desc string + in string + bufLen int + expected string + }{ + {"short", "hello", 10, "hello"}, + {"exact", "hello", 5, "hello"}, + {"long", "hello", 3, "hel"}, + } + for _, tc := range tt { + t.Run(tc.desc, func(t *testing.T) { + rw := NewInMemory() + rw.PrepareRead([]byte(tc.in)) + buf := make([]byte, tc.bufLen) + + n, err := rw.Read(buf) + + assert.NoError(t, err) + assert.Equal(t, len(tc.expected), n) + assert.Equal(t, tc.expected, string(buf[0:n])) + }) + } +} + +func TestInMemory_ReadClose(t *testing.T) { + rw := NewInMemory() + + go func() { + time.Sleep(100) + rw.Close() + }() + + buf := make([]byte, 10) + n, err := rw.Read(buf) + + assert.Equal(t, io.EOF, err) + assert.Equal(t, 0, n) +} + +func TestInMemory_ReadLater(t *testing.T) { + rw := NewInMemory() + + go func() { + time.Sleep(100) + rw.PrepareRead([]byte("hello")) + }() + + buf := make([]byte, 10) + n, err := rw.Read(buf) + + assert.NoError(t, err) + assert.Equal(t, 5, n) + assert.Equal(t, "hello", string(buf[0:n])) +} + +func TestWrite(t *testing.T) { + rw := NewInMemory() + + n, err := rw.Write([]byte("hello")) + + assert.NoError(t, err) + assert.Equal(t, 5, n) + assert.Equal(t, "hello", string(rw.Written())) + assert.Equal(t, "hello", string(rw.Written())) + + rw.ClearWrite() + assert.Equal(t, "", string(rw.Written())) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..a6bd198 --- /dev/null +++ b/go.mod @@ -0,0 +1,11 @@ +module github.com/ftl/tetra-pei + +go 1.17 + +require github.com/stretchr/testify v1.7.0 + +require ( + github.com/davecgh/go-spew v1.1.0 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..acb88a4 --- /dev/null +++ b/go.sum @@ -0,0 +1,11 @@ +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/sds/command.go b/sds/command.go new file mode 100644 index 0000000..0f0fae9 --- /dev/null +++ b/sds/command.go @@ -0,0 +1,32 @@ +package sds + +import ( + "fmt" + + "github.com/ftl/tetra-pei/tetra" +) + +type Encoder interface { + Encode([]byte, int) ([]byte, int) +} + +type EncoderFunc func() ([]byte, int) + +func (f EncoderFunc) Encode() ([]byte, int) { + return f() +} + +const ( + // SwitchToSDSTL is a short-cut for selecting the SDS-TL AI service according to [PEI] 6.14.6 + SwitchToSDSTL = "AT+CTSDS=12,0,0,0,1" + // SwitchToStatus is a short-cut for selecting the status AI service according to [PEI] 6.14.6 + SwitchToStatus = "AT+CTSDS=13,0" +) + +// SendMessage according to [PEI] 6.13.2 +func SendMessage(destination tetra.Identity, sds Encoder) string { + pdu := make([]byte, 0, 2000) // TODO use the maximum size allowed + pduBits := 0 + pdu, pduBits = sds.Encode(pdu, pduBits) + return fmt.Sprintf("AT+CMGS=%s,%d\x0d\x0a%s\x1a", destination, pduBits, tetra.BinaryToHex(pdu)) +} diff --git a/sds/command_test.go b/sds/command_test.go new file mode 100644 index 0000000..bc13b40 --- /dev/null +++ b/sds/command_test.go @@ -0,0 +1 @@ +package sds diff --git a/sds/doc.go b/sds/doc.go new file mode 100644 index 0000000..9fbb4d7 --- /dev/null +++ b/sds/doc.go @@ -0,0 +1,19 @@ +/* +The package sds implements everything that is necessary for sending and receiving SDS messages through the +Peripheral Equipment Interface (PEI) of a TETRA radio terminal. This implementation is solely based on: + [AI] ETSI TS 100 392-2 V3.9.2 (2020-06) + [PEI] ETSI EN 300 392-5 V2.7.1 (2020-04) + +The most relevant chapters in [AI] are 29 (SDS-TL Protocol) and 14 (CMCE Protocol). + +Abbreviations: +PDU: Protocol Data Unit +SDU: Service Data Unit +UDH: User Data Header + +Restrictions: +Store/forward control information is not supported yet. +Only ISO8859-1 supported as text encoding. + +*/ +package sds diff --git a/sds/sds.go b/sds/sds.go new file mode 100644 index 0000000..56e7bac --- /dev/null +++ b/sds/sds.go @@ -0,0 +1,1015 @@ +package sds + +import ( + "fmt" + "log" + "strconv" + "strings" + "time" + + "github.com/ftl/tetra-pei/tetra" +) + +// ParseIncomingMessage parses an incoming message with the given header and PDU bytes. The message may +// be part of a concatenated text message with user data header, a simple text message, a text message, +// or a status. +func ParseIncomingMessage(headerString string, pduHex string) (IncomingMessage, error) { + header, err := ParseHeader(headerString) + if err != nil { + return IncomingMessage{}, err + } + + pduBytes, err := tetra.HexToBinary(pduHex) + if err != nil { + return IncomingMessage{}, fmt.Errorf("cannot decode hex PDU data: %w", err) + } + if len(pduBytes) != header.PDUBytes() { + log.Printf("got different count of pdu bytes, expected %d, but got %d", len(pduBytes), header.PDUBytes()) + } + if len(pduBytes) > header.PDUBytes() { + pduBytes = pduBytes[0:header.PDUBytes()] + } + + var result IncomingMessage + result.Header = header + switch header.AIService { + case SDSTLService: + result.Payload, err = ParseSDSTLPDU(pduBytes) + case StatusService: + result.Payload, err = ParseStatus(pduBytes) + default: + return IncomingMessage{}, fmt.Errorf("AI service %s is not supported", header.AIService) + } + + if err != nil { + return IncomingMessage{}, err + } + return result, nil +} + +type IncomingMessage struct { + Header Header + Payload interface{} +} + +// ParseHeader from the given string. The string must include the +CTSDSR: token. +func ParseHeader(s string) (Header, error) { + if !strings.HasPrefix(s, "+CTSDSR:") { + return Header{}, fmt.Errorf("invalid header, +CTSDSR expected: %s", s) + } + + var result Header + headerFields := strings.Split(s[8:], ",") + switch len(headerFields) { + case 3, 4: // minimum set + result.AIService = AIService(strings.TrimSpace(headerFields[0])) + result.Destination = tetra.Identity(strings.TrimSpace(headerFields[1])) + case 6, 7: // with source, with end-to-end encryption + result.AIService = AIService(strings.TrimSpace(headerFields[0])) + result.Source = tetra.Identity(strings.TrimSpace(headerFields[1])) + result.Destination = tetra.Identity(strings.TrimSpace(headerFields[3])) + default: + return Header{}, fmt.Errorf("invalid header, wrong field count: %s", s) + } + + pduBitCountField := headerFields[len(headerFields)-1] + var err error + result.PDUBits, err = strconv.Atoi(strings.TrimSpace(pduBitCountField)) + if err != nil { + return Header{}, fmt.Errorf("invalid PDU bit count %s: %v", pduBitCountField, err) + } + + return result, nil +} + +// Header represents the information provided with the AT+CTSDSR unsolicited response indicating an incoming SDS. +// see [PEI] 6.13.3 +type Header struct { + AIService AIService + Source tetra.Identity + Destination tetra.Identity + PDUBits int +} + +// PDUBytes returns the size of the following PDU in bytes. +func (h Header) PDUBytes() int { + result := h.PDUBits / 8 + if (h.PDUBits % 8) != 0 { + result++ + } + return result +} + +// AIService enum according to [PEI] 6.17.3 +type AIService string + +// All AI services relevant for SDS handling, according to [PEI] 6.17.3 +const ( + SDS1Service AIService = "9" + SDS2Service AIService = "10" + SDS3Service AIService = "11" + SDSTLService AIService = "12" + StatusService AIService = "13" +) + +/* General types used in the PDU */ + +// ProtocolIdentifier enum according to [AI] 29.4.3.9 +type ProtocolIdentifier byte + +// Encode this protocol identifier +func (p ProtocolIdentifier) Encode(bytes []byte, bits int) ([]byte, int) { + return append(bytes, byte(p)), bits + 8 +} + +// All protocol identifiers relevant for SDS handling, according to [AI] table 29.21 +const ( + SimpleTextMessaging ProtocolIdentifier = 0x02 + SimpleImmediateTextMessaging ProtocolIdentifier = 0x09 + SimpleConcatenatedSDSMessaging ProtocolIdentifier = 0x0C + TextMessaging ProtocolIdentifier = 0x82 + ImmediateTextMessaging ProtocolIdentifier = 0x89 + UserDataHeaderMessaging ProtocolIdentifier = 0x8A + ConcatenatedSDSMessaging ProtocolIdentifier = 0x8C +) + +/* SDS-TL related types and functions */ + +// ParseSDSTLPDU parses an SDS-TL PDU from the given bytes according to [AI] 29.4.1. +// This function currently supports only a subset of the possible protocol identifiers: +// Simple text messaging (0x02), simple immediate text messaging (0x09), text messaging (0x82), +// immediate text messaging (0x89), message with user data header (0x8A) +func ParseSDSTLPDU(bytes []byte) (interface{}, error) { + if len(bytes) == 0 { + return nil, fmt.Errorf("empty payload") + } + + switch ProtocolIdentifier(bytes[0]) { + case SimpleTextMessaging, SimpleImmediateTextMessaging: + return ParseSimpleTextMessage(bytes) + case TextMessaging, ImmediateTextMessaging, UserDataHeaderMessaging: + return parseSDSTLMessage(bytes) + default: + return nil, fmt.Errorf("protocol 0x%x not supported", bytes[0]) + } +} + +func parseSDSTLMessage(bytes []byte) (interface{}, error) { + if len(bytes) < 2 { + return nil, fmt.Errorf("payload too short: %d", len(bytes)) + } + + messageType := SDSTLMessageType(bytes[1] >> 4) + switch messageType { + case SDSTransferMessage: + return ParseSDSTransfer(bytes) + case SDSReportMessage: + return ParseSDSReport(bytes) + case SDSAcknowledgeMessage: + return ParseSDSAcknowledge(bytes) + default: + return nil, fmt.Errorf("SDS-TL message type 0x%x is not supported", messageType) + } +} + +// SDSTLMessageType enum according to [AI] 29.4.3.8 +type SDSTLMessageType byte + +// All SDS-TL message types according to [AI] table 29.20 +const ( + SDSTransferMessage SDSTLMessageType = 0 + SDSReportMessage SDSTLMessageType = 1 + SDSAcknowledgeMessage SDSTLMessageType = 2 +) + +// ParseSDSAcknowledge parses a SDS-ACK PDU from the given bytes +func ParseSDSAcknowledge(bytes []byte) (SDSAcknowledge, error) { + if len(bytes) < 4 { + return SDSAcknowledge{}, fmt.Errorf("SDS-ACK PDU too short: %d", len(bytes)) + } + + var result SDSAcknowledge + + result.protocol = ProtocolIdentifier(bytes[0]) + result.DeliveryStatus = DeliveryStatus(bytes[2]) + result.MessageReference = MessageReference(bytes[3]) + + return result, nil +} + +// SDSAcknowledge represents the SDS-ACK PDU contents as defined in [AI] 29.4.2.1 +type SDSAcknowledge struct { + protocol ProtocolIdentifier + DeliveryStatus DeliveryStatus + MessageReference MessageReference +} + +// ParseSDSReport parses a SDS-REPORT PDU from the given bytes +func ParseSDSReport(bytes []byte) (SDSReport, error) { + if len(bytes) < 4 { + return SDSReport{}, fmt.Errorf("SDS-REPORT PDU too short: %d", len(bytes)) + } + + var result SDSReport + + result.protocol = ProtocolIdentifier(bytes[0]) + result.AckRequired = ((bytes[1] & 0x08) != 0) + storeForwardControl := (bytes[1] & 0x01) != 0 + result.DeliveryStatus = DeliveryStatus(bytes[2]) + result.MessageReference = MessageReference(bytes[3]) + + userdataStart := 4 + if storeForwardControl { + sfc, err := ParseStoreForwardControl(bytes[4:]) + if err != nil { + return SDSReport{}, err + } + + result.StoreForwardControl = sfc + userdataStart += sfc.Length() + } + + if userdataStart < len(bytes) { + result.UserData = bytes[userdataStart:] + } + + return result, nil +} + +// NewSDSReport creates a new SDS-REPORT PDU based on the given SDS-TRANSFER PDU without store/forward control information. +func NewSDSReport(sdsTransfer SDSTransfer, ackRequired bool, deliveryStatus DeliveryStatus) SDSReport { + return SDSReport{ + protocol: sdsTransfer.protocol, + AckRequired: ackRequired, + DeliveryStatus: deliveryStatus, + MessageReference: sdsTransfer.MessageReference, + } +} + +// SDSReport represents the SDS-REPORT PDU contents as defined in [AI] 29.4.2.2 +type SDSReport struct { + protocol ProtocolIdentifier + AckRequired bool + DeliveryStatus DeliveryStatus + MessageReference MessageReference + StoreForwardControl StoreForwardControl + + // user data + + UserData []byte +} + +// Encode this SDS-REPORT PDU +func (r SDSReport) Encode(bytes []byte, bits int) ([]byte, int) { + + bytes, bits = r.protocol.Encode(bytes, bits) + + var byte1 byte + byte1 = byte(SDSReportMessage) << 4 + if r.AckRequired { + byte1 |= 0x08 + } + bytes = append(bytes, byte1) + bits += 8 + + bytes, bits = r.DeliveryStatus.Encode(bytes, bits) + bytes, bits = r.MessageReference.Encode(bytes, bits) + + return bytes, bits +} + +// ParseSDSShortReport parses a SDS-SHORT-REPORT PDU from the given bytes +func ParseSDSShortReport(bytes []byte) (SDSShortReport, error) { + if len(bytes) != 2 { + return SDSShortReport{}, fmt.Errorf("SDS-SHORT-REPORT PDU invalid length %d", len(bytes)) + } + if (bytes[0] & SDSShortReportPDUIdentifier) != SDSShortReportPDUIdentifier { + return SDSShortReport{}, fmt.Errorf("SDS-SHORT-REPORT PDU invalid PDU identifier 0x%x", bytes[0]&SDSShortReportPDUIdentifier) + } + + var result SDSShortReport + + result.ReportType = ShortReportType(bytes[0] & 0x03) + result.MessageReference = MessageReference(bytes[1]) + + return result, nil +} + +// SDSShortReportPDUIdentifier for SDS-SHORT-REPORT PDUs +const SDSShortReportPDUIdentifier byte = 0x7A + +// SDSShortReport represents the SDS-SHORT-REPORT PDU contents as defined in [AI] 29.4.2.3 +type SDSShortReport struct { + ReportType ShortReportType + MessageReference MessageReference +} + +// ParseSDSTransfer parses a SDS-TRANSFER PDU from the given bytes +func ParseSDSTransfer(bytes []byte) (SDSTransfer, error) { + if len(bytes) < 4 { + return SDSTransfer{}, fmt.Errorf("SDS-TRANSFER PDU too short: %d", len(bytes)) + } + + var result SDSTransfer + + result.protocol = ProtocolIdentifier(bytes[0]) + result.DeliveryReportRequest = DeliveryReportRequest((bytes[1] & 0x0C) >> 2) + result.ServiceSelectionShortFormReport = (bytes[1] & 0x02) == 0 + storeForwardControl := (bytes[1] & 0x01) != 0 + result.MessageReference = MessageReference(bytes[2]) + + userdataStart := 3 + if storeForwardControl { + sfc, err := ParseStoreForwardControl(bytes[3:]) + if err != nil { + return SDSTransfer{}, err + } + + result.StoreForwardControl = sfc + userdataStart += sfc.Length() + } + + var sdu interface{} + var err error + + switch result.protocol { + case TextMessaging, ImmediateTextMessaging: + sdu, err = ParseTextSDU(bytes[userdataStart:]) + case UserDataHeaderMessaging: + sdu, err = ParseConcatenatedTextSDU(bytes[userdataStart:]) + default: + return SDSTransfer{}, fmt.Errorf("protocol 0x%x is not supported as SDS-TRANSFER content", bytes[0]) + } + + if err != nil { + return SDSTransfer{}, err + } + result.UserData = sdu + + return result, nil +} + +// NewTextMessageTransfer returns a new SDS-TRANSFER PDU for text messaging with the given parameters +func NewTextMessageTransfer(messageReference MessageReference, text string) SDSTransfer { + return SDSTransfer{ + protocol: TextMessaging, + MessageReference: messageReference, + UserData: TextSDU{ + TextHeader: TextHeader{ + Encoding: ISO8859_1, + }, + Text: text, + }, + } +} + +// SDSTransfer represents the SDS-TRANSFER PDU contents as defined in [AI] 29.4.2.4 +type SDSTransfer struct { + protocol ProtocolIdentifier + DeliveryReportRequest DeliveryReportRequest + ServiceSelectionShortFormReport bool + MessageReference MessageReference + StoreForwardControl StoreForwardControl + UserData interface{} +} + +// Encode this SDS-TRANSFER PDU +func (m SDSTransfer) Encode(bytes []byte, bits int) ([]byte, int) { + bytes, bits = m.protocol.Encode(bytes, bits) + + var byte1 byte + byte1 = byte(SDSTransferMessage) << 4 + byte1 |= byte(m.DeliveryReportRequest) << 2 + if !m.ServiceSelectionShortFormReport { + byte1 |= 0x02 + } + bytes = append(bytes, byte1) + bits += 8 + + bytes, bits = m.MessageReference.Encode(bytes, bits) + + switch sdu := m.UserData.(type) { + case TextSDU: + bytes, bits = sdu.Encode(bytes, bits) + case ConcatenatedTextSDU: + // bytes, bits = sdu.Encode(bytes, bits) + } + + return bytes, bits +} + +// ReceivedReportRequested indicates if for this SDS-TRANSFER PDU a delivery report is requested for receipt +func (m SDSTransfer) ReceivedReportRequested() bool { + return m.DeliveryReportRequest == MessageReceivedReportRequested || + m.DeliveryReportRequest == MessageReceivedAndConsumedReportRequested +} + +// ConsumedReportRequested indicates if for this SDS-TRANSFER PDU a delivery report is requested for consumation +func (m SDSTransfer) ConsumedReportRequested() bool { + return m.DeliveryReportRequest == MessageConsumedReportRequested || + m.DeliveryReportRequest == MessageReceivedAndConsumedReportRequested +} + +// Immediate indiciates if this message should be displayed/handled immediately by the TE. +func (m SDSTransfer) Immediate() bool { + return m.protocol == ImmediateTextMessaging +} + +// MessageReference according to [AI] 29.4.3.7 +type MessageReference byte + +// Encode this message reference +func (m MessageReference) Encode(bytes []byte, bits int) ([]byte, int) { + return append(bytes, byte(m)), bits + 8 +} + +// DeliveryStatus according to [AI] 29.4.3.2 +type DeliveryStatus byte + +// Encode this delivery status +func (s DeliveryStatus) Encode(bytes []byte, bits int) ([]byte, int) { + return append(bytes, byte(s)), bits + 8 +} + +// Success indicates if this status represents a success (see [AI] table 29.16). +func (s DeliveryStatus) Success() bool { + return (s & 0xE0) == 0x00 +} + +// TemporaryError indicates if this status represents a temporary error (see [AI] table 29.16). +func (s DeliveryStatus) TemporaryError() bool { + return (s & 0xE0) == 0x20 +} + +// DataDeliveryFailed indicates if this status represents a data transfer failure (see [AI] table 29.16). +func (s DeliveryStatus) DataDeliveryFailed() bool { + return (s & 0xE0) == 0x40 +} + +// FlowControl indicates if this status represents flow control information (see [AI] table 29.16). +func (s DeliveryStatus) FlowControl() bool { + return (s & 0xE0) == 0x06 +} + +// EndToEndControl indicates if this status represents end to end control information (see [AI] table 29.16). +func (s DeliveryStatus) EndToEndControl() bool { + return (s & 0xE0) == 0x80 +} + +// All DeliveryStatus values according to [AI] table 29.16 +const ( + // Success + + ReceiptAckByDestination DeliveryStatus = 0x00 + ReceiptReportAck DeliveryStatus = 0x01 + ConsumedByDestination DeliveryStatus = 0x02 + ConsumedReportAck DeliveryStatus = 0x03 + MessageForwardedToExternalNetwork DeliveryStatus = 0x04 + SentToGroupAckPresented DeliveryStatus = 0x05 + ConcatenationPartReceiptAckByDestination DeliveryStatus = 0x06 + + // Temporary Error + + Congestion DeliveryStatus = 0x20 + MessageStored DeliveryStatus = 0x21 + DestinationNotReachableMessageStored DeliveryStatus = 0x22 + + // Data Transfer Failed + + NetworkOverload DeliveryStatus = 0x40 + ServicePermanentlyNotAvailable DeliveryStatus = 0x41 + ServiceTemporaryNotAvailable DeliveryStatus = 0x42 + SourceNotAuthorized DeliveryStatus = 0x43 + DestinationNotAuthorzied DeliveryStatus = 0x44 + UnknownDestGatewayServiceAddress DeliveryStatus = 0x45 + UnknownForwardAddress DeliveryStatus = 0x46 + GroupAddressWithIndividualService DeliveryStatus = 0x47 + ValidityPeriodExpiredNotReceived DeliveryStatus = 0x48 + ValidityPeriodExpiredNotConsumed DeliveryStatus = 0x49 + DeliveryFailed DeliveryStatus = 0x4A + DestinationNotRegistered DeliveryStatus = 0x4B + DestinationQueueFull DeliveryStatus = 0x4C + MessageTooLong DeliveryStatus = 0x4D + DestinationDoesNotSupportSDSTL DeliveryStatus = 0x4E + DestinationHostNotConnected DeliveryStatus = 0x4F + ProtocolNotSupported DeliveryStatus = 0x50 + DataCodingSchemeNotSupported DeliveryStatus = 0x51 + DestinationMemoryFullMessageDiscarded DeliveryStatus = 0x52 + DestinationNotAcceptingSDS DeliveryStatus = 0x53 + ConcatednatedMessageTooLong DeliveryStatus = 0x54 + DestinationAddressProhibited DeliveryStatus = 0x56 + CannotRouteToExternalNetwork DeliveryStatus = 0x57 + UnknownExternalSubscriberNumber DeliveryStatus = 0x58 + NegativeReportAcknowledgement DeliveryStatus = 0x59 + DestinationNotReachable DeliveryStatus = 0x5A + TextDistributionError DeliveryStatus = 0x5B + CorruptInformationElement DeliveryStatus = 0x5C + NotAllConcatenationPartsReceived DeliveryStatus = 0x5D + DestinationEngagedInAnotherServiceBySwMI DeliveryStatus = 0x5E + DestinationEngagedInAnotherServiceByDest DeliveryStatus = 0x5F + + // Flow Control + + DestinationMemoryFull DeliveryStatus = 0x60 + DestinationMemoryAvailable DeliveryStatus = 0x61 + StartPendingMessages DeliveryStatus = 0x62 + NoPendingMessages DeliveryStatus = 0x63 + + // End to End Control + + StopSending DeliveryStatus = 0x80 + StartSending DeliveryStatus = 0x81 +) + +// ShortReportType enum according to [AI] 29.4.3.10 +type ShortReportType byte + +// All short report type values accoring to [AI] table 29.22 +const ( + ProtocolOrEncodingNotSupportedShort ShortReportType = 0x00 + DestinationMemoryFullShort ShortReportType = 0x01 + MessageReceivedShort ShortReportType = 0x02 + MessageConsumedShort ShortReportType = 0x03 +) + +// DeliveryReportRequest enum according to [AI] 29.4.3.3 +type DeliveryReportRequest byte + +// All delivery report requests according to [AI] table 29.17 +const ( + NoReportRequested DeliveryReportRequest = 0x00 + MessageReceivedReportRequested DeliveryReportRequest = 0x01 + MessageConsumedReportRequested DeliveryReportRequest = 0x02 + MessageReceivedAndConsumedReportRequested DeliveryReportRequest = 0x03 +) + +// ParseStoreForwardControl from the given bytes. +func ParseStoreForwardControl(bytes []byte) (StoreForwardControl, error) { + if len(bytes) < 1 { + return StoreForwardControl{}, fmt.Errorf("store forward control too short: %d", len(bytes)) + } + var result StoreForwardControl + + result.Valid = true + result.ValidityPeriod = ParseValidityPeriod(bytes[0] >> 3) + result.ForwardAddressType = ForwardAddressType(bytes[0] & 3) + + switch result.ForwardAddressType { + case ForwardToSNA: + if len(bytes) < 2 { + return StoreForwardControl{}, fmt.Errorf("store forward control with SNA too short: %d", len(bytes)) + } + result.ForwardAddressSNA = ForwardAddressSNA(bytes[1]) + case ForwardToSSI: + if len(bytes) < 4 { + return StoreForwardControl{}, fmt.Errorf("store forward control with SSI too short: %d", len(bytes)) + } + copy(result.ForwardAddressSSI[:], bytes[1:4]) + case ForwardToTSI: + if len(bytes) < 4 { + return StoreForwardControl{}, fmt.Errorf("store forward control with TSI too short: %d", len(bytes)) + } + copy(result.ForwardAddressSSI[:], bytes[1:4]) + case ForwardToExternalSubscriberNumber: + if len(bytes) < 2 { + return StoreForwardControl{}, fmt.Errorf("store forward control with external subscriber number too short: %d", len(bytes)) + } + l := int(bytes[1]) + bl := l / 2 + if l%2 > 0 { + bl++ + } + if len(bytes) < 2+bl { + return StoreForwardControl{}, fmt.Errorf("store forward control with external subscriber number too short: %d", len(bytes)) + } + + result.ExternalSubscriberNumber = make(ExternalSubscriberNumber, 0, l) + d := 0 + for i := 0; i < bl; i++ { + result.ExternalSubscriberNumber[d] = ExternalSubscriberNumberDigit(bytes[i] >> 4) + d++ + if d < l { + result.ExternalSubscriberNumber[d+1] = ExternalSubscriberNumberDigit(bytes[i] & 0x0F) + d++ + } + } + } + + return result, nil +} + +// StoreForwardControl represents the optional store and forward control information contained in the SDS-REPORT and SDS-TRANSFER PDUs. +type StoreForwardControl struct { + // Valid indicates if this StoreForwardControl instance contains valid data. Valid is false if store and forward control is not used with this message. + Valid bool + ValidityPeriod ValidityPeriod + ForwardAddressType ForwardAddressType + ForwardAddressSNA ForwardAddressSNA + ForwardAddressSSI ForwardAddressSSI + ForwardAddressExtension ForwardAddressExtension + ExternalSubscriberNumber ExternalSubscriberNumber +} + +// Length returns the length of this encoded store forward control in bytes. +func (s StoreForwardControl) Length() int { + switch s.ForwardAddressType { + case ForwardToSNA: + return 2 + case ForwardToSSI: + return 4 + case ForwardToTSI: + return 4 + case ForwardToExternalSubscriberNumber: + l := len(s.ExternalSubscriberNumber) / 2 + if len(s.ExternalSubscriberNumber)%2 > 0 { + l++ + } + return 2 + l + case NoForwardAddressPresent: + return 1 + default: + return 1 + } +} + +// ValidityPeriod according to [AI] 29.4.3.14 +type ValidityPeriod time.Duration + +// InfinitelyValid represents the infinite validity period (31). +const InfinitelyValid ValidityPeriod = -1 + +// DecodeValidityPeriod from a 5 bits value according to [AI] table 29.25 +func ParseValidityPeriod(b byte) ValidityPeriod { + switch { + case b == 0: + return 0 + case b <= 6: + return ValidityPeriod(time.Duration(b) * 10 * time.Second) + case b <= 10: + return ValidityPeriod(time.Duration(b-5) * time.Minute) + case b <= 16: + return ValidityPeriod(time.Duration(b-10) * 10 * time.Minute) + case b <= 21: + return ValidityPeriod(time.Duration(b-15) * time.Hour) + case b <= 24: + return ValidityPeriod(time.Duration(b-20) * 6 * time.Hour) + case b <= 30: + return ValidityPeriod(time.Duration(b-24) * 48 * time.Hour) + default: + return InfinitelyValid + } +} + +// Encode the validity period into 5 bits, according to [AI] table 29.25 +func (p ValidityPeriod) Encode() ([]byte, int) { + d := time.Duration(p) + var result byte + incIfRemainder := func(resultDuration time.Duration) { + remainder := d - resultDuration + if remainder > 0 { + result++ + } + } + + switch { + case d == 0: + return []byte{0}, 8 + case d <= time.Minute: + result = byte(int(d.Truncate(time.Second).Seconds() / 10)) + incIfRemainder(time.Duration(result) * 10 * time.Second) + return []byte{result}, 8 + case d <= 5*time.Minute: + result = byte(int(d.Truncate(time.Minute).Minutes())) + incIfRemainder(time.Duration(result) * time.Minute) + return []byte{result + 5}, 8 + case d <= time.Hour: + result = byte(int(d.Truncate(time.Minute).Minutes() / 10)) + incIfRemainder(time.Duration(result) * 10 * time.Minute) + return []byte{result + 10}, 8 + case d <= 6*time.Hour: + result = byte(int(d.Truncate(time.Hour).Hours())) + incIfRemainder(time.Duration(result) * time.Hour) + return []byte{result + 15}, 8 + case d <= 24*time.Hour: + result = byte(int(d.Truncate(time.Hour).Hours() / 6)) + incIfRemainder(time.Duration(result) * 6 * time.Hour) + return []byte{result + 20}, 8 + case d <= 12*24*time.Hour: + result = byte(int(d.Truncate(time.Hour).Hours() / 48)) + incIfRemainder(time.Duration(result) * 48 * time.Hour) + return []byte{result + 24}, 8 + default: + return []byte{31}, 8 // infinite + } +} + +// ForwardAddressType enum according to [AI] 29.4.3.5 +type ForwardAddressType byte + +// All forward address type values according to [AI] table 29.18 +const ( + ForwardToSNA ForwardAddressType = 0x00 + ForwardToSSI ForwardAddressType = 0x01 + ForwardToTSI ForwardAddressType = 0x02 + ForwardToExternalSubscriberNumber ForwardAddressType = 0x03 + NoForwardAddressPresent ForwardAddressType = 0x07 +) + +// ForwardAddressSNA according to [AI] 29.4.3.6 +type ForwardAddressSNA byte + +// ForwardAddressSSI according to [AI] 29.4.3.6 +type ForwardAddressSSI [3]byte + +// ForwardAddressExtendsion according to [AI] 29.4.3.6 +type ForwardAddressExtension [3]byte + +// ExternalSubscriberNumber according to [AI] 29.4.3.6, contains an arbitrary number of digits. +type ExternalSubscriberNumber []ExternalSubscriberNumberDigit + +// ExternalSubscriberNumberDigit represents one digit in the ExternalSubscriberNumber +type ExternalSubscriberNumberDigit byte // its only 4 bits per digit + +/* Simple Text Messaging related types and functions */ + +func ParseSimpleTextMessage(bytes []byte) (SimpleTextMessage, error) { + if len(bytes) < 2 { + return SimpleTextMessage{}, fmt.Errorf("simple text message PDU too short: %d", len(bytes)) + } + + var result SimpleTextMessage + result.protocol = ProtocolIdentifier(bytes[0]) + result.Encoding = TextEncoding(bytes[1] & 0x7F) + + text, err := DecodePayloadText(result.Encoding, bytes[2:]) + if err != nil { + return SimpleTextMessage{}, err + } + result.Text = text + + return result, nil +} + +// SimpleTextMessage represents the data of a simple text messaging PDU, according to [AI] 29.5.2.3 +type SimpleTextMessage struct { + protocol ProtocolIdentifier + Encoding TextEncoding + Text string +} + +// Immediate indiciates if this message should be displayed/handled immediately by the TE. +func (m SimpleTextMessage) Immediate() bool { + return m.protocol == SimpleImmediateTextMessaging +} + +/* Text messaging related types and functions */ + +// ParseTextSDU parses the user data of a text message. +func ParseTextSDU(bytes []byte) (TextSDU, error) { + textHeader, err := ParseTextHeader(bytes) + if err != nil { + return TextSDU{}, err + } + textPayloadStart := textHeader.Length() + text, err := DecodePayloadText(textHeader.Encoding, bytes[textPayloadStart:]) + if err != nil { + return TextSDU{}, err + } + + return TextSDU{ + TextHeader: textHeader, + Text: text, + }, nil +} + +// TextSDU according to [AI] 29.5.3.3 +type TextSDU struct { + TextHeader + Text string +} + +// Encode this text SDU +func (t TextSDU) Encode(bytes []byte, bits int) ([]byte, int) { + bytes, bits = t.TextHeader.Encode(bytes, bits) + bytes, bits = AppendEncodedPayloadText(bytes, bits, t.Text, t.TextHeader.Encoding) + + return bytes, bits +} + +// Length returns the length of this encoded text SDU in bytes. +func (t TextSDU) Length() int { + return t.TextHeader.Length() + TextBytes(t.Encoding, len(t.Text)) +} + +/* Concatenated text messageing related types and functions */ + +// ParseConcatenatedTextSDU parses the user data of a message with user data header. +func ParseConcatenatedTextSDU(bytes []byte) (ConcatenatedTextSDU, error) { + /* + Example PDU with User Data Header: 8A00C98D045A8F050003C90201 + + 8A: Protocol Identifier[8] + 00: Message Type[4], Delivery Report Request[2], Service Selection/Short form report[1], Store/forward control[1] + C9: Message Reference[8] (0xC9) <-- This one is incremented for each part of the concatenated message + + 8D: Timestamp Used[1] (yes), Text Encoding Scheme[7] (ISO8859-15/Latin 0 ???) + 04 5A 8F: Timestamp[24] + 05: User Data Header length[8] (5) + 00: UDH Information Element ID[8] (0) + 03: UDH Information Element Length[8] (3) + C9: Message Reference[8] (0xC9) <-- This is always the message reference of the first part + 02: Total number of parts[8] (2) + 01: Sequence number of current part[8] (1) <-- 1-based, first part == 1 + + and then comes the text data + */ + + textHeader, err := ParseTextHeader(bytes) + if err != nil { + return ConcatenatedTextSDU{}, err + } + + udhStart := textHeader.Length() + udh, err := ParseConcatenatedTextUDH(bytes[udhStart:]) + if err != nil { + return ConcatenatedTextSDU{}, err + } + + textPayloadStart := udhStart + udh.Length() + text, err := DecodePayloadText(textHeader.Encoding, bytes[textPayloadStart:]) + if err != nil { + return ConcatenatedTextSDU{}, err + } + + return ConcatenatedTextSDU{ + TextSDU: TextSDU{ + TextHeader: textHeader, + Text: text, + }, + UserDataHeader: udh, + }, nil +} + +// ConcatenatedTextSDU according to [AI] 29.5.10.3 +type ConcatenatedTextSDU struct { + TextSDU + UserDataHeader ConcatenatedTextUDH +} + +// Length returns the length of this encoded concatenated text SDU in bytes. +func (t ConcatenatedTextSDU) Length() int { + return t.TextSDU.Length() + t.UserDataHeader.Length() +} + +// ParseConcatenatedTextUDH according to [AI] table 29.48 +func ParseConcatenatedTextUDH(bytes []byte) (ConcatenatedTextUDH, error) { + if len(bytes) < 6 { + return ConcatenatedTextUDH{}, fmt.Errorf("concatenated text UDH too short: %d", len(bytes)) + } + + var result ConcatenatedTextUDH + + result.HeaderLength = bytes[0] + result.ElementID = UDHInformationElementID(bytes[1]) + result.ElementLength = bytes[2] + numbersStart := 4 + if result.ElementID == ConcatenatedTextMessageWithShortReference { + if result.ElementLength != 3 { + return ConcatenatedTextUDH{}, fmt.Errorf("UDH information element length invalid, got %d but expected 3", result.ElementLength) + } + result.MessageReference = uint16(bytes[3]) + } else { + if result.ElementLength != 4 { + return ConcatenatedTextUDH{}, fmt.Errorf("UDH information element length invalid, got %d but expected 4", result.ElementLength) + } + if len(bytes) < 7 { + return ConcatenatedTextUDH{}, fmt.Errorf("concatenated text UDH with long reference too short: %d", len(bytes)) + } + numbersStart = 5 + result.MessageReference = (uint16(bytes[4]) << 8) | uint16(bytes[3]) + } + result.TotalNumber = bytes[numbersStart] + result.SequenceNumber = bytes[numbersStart+1] + + return result, nil +} + +// ConcatenatedTextUDH contents according to [AI] 29.5.10.3 +type ConcatenatedTextUDH struct { + HeaderLength byte + ElementID UDHInformationElementID + ElementLength byte + MessageReference uint16 + TotalNumber byte + SequenceNumber byte +} + +// Length returns the length of this header in bytes. +func (h ConcatenatedTextUDH) Length() int { + return int(h.HeaderLength) + 1 // the HeaderLength byte itself +} + +// UDHInformationElementID enum according to [AI] 29.5.9.4.1 +type UDHInformationElementID byte + +// The relevant UDHInformationElementID values for concatenated text according to [AI] table 29.47. +const ( + ConcatenatedTextMessageWithShortReference UDHInformationElementID = 0x00 + ConcatenatedTextMessageWithLongReference UDHInformationElementID = 0x08 +) + +/* Status related types and functions */ + +// ParseStatus from the given bytes. +func ParseStatus(bytes []byte) (interface{}, error) { + if len(bytes) < 2 { + return 0, fmt.Errorf("status value too short: %v", bytes) + } + + if (bytes[0] & SDSShortReportPDUIdentifier) == SDSShortReportPDUIdentifier { + return ParseSDSShortReport(bytes) + } + + var result Status + result = (Status(bytes[0]) << 8) | Status(bytes[1]) + + return result, nil +} + +// Status represents a pre-coded status according to [AI] 14.8.34 +type Status uint16 + +// Bytes returns this status as byte slice. +func (s Status) Bytes() []byte { + return []byte{ + byte(s >> 8), + byte(s), + } +} + +// Length returns the length of this encoded status in bytes. +func (s Status) Length() int { + return 2 +} + +// Some relevant status values +const ( + // requests + + Status0 Status = 0x8002 + Status1 Status = 0x8003 + Status2 Status = 0x8004 + Status3 Status = 0x8005 + Status4 Status = 0x8006 + Status5 Status = 0x8007 + Status6 Status = 0x8008 + Status7 Status = 0x8009 + Status8 Status = 0x800A + Status9 Status = 0x800B + + // responses + StatusA Status = 0x80F2 + StatusE Status = 0x80F3 + StatusC Status = 0x80F4 + StatusF Status = 0x80F5 + StatusH Status = 0x80F6 + StatusJ Status = 0x80F7 + StatusL Status = 0x80F8 + StatusP Status = 0x80F9 + Statusd Status = 0x80FC + Statush Status = 0x80FD + Statuso Status = 0x80FE + Statusu Status = 0x80FF +) + +// DecodeTimestamp according to [AI] 29.5.4.4 +func DecodeTimestamp(bytes []byte) (time.Time, error) { + if len(bytes) != 3 { + return time.Now(), fmt.Errorf("a timestamp must be 3 bytes long") + } + + locations := []*time.Location{time.Local, time.UTC, time.Local, time.Local} + location := locations[(bytes[0]&0xC0)>>6] + year := time.Now().Year() + month := bytes[0] & 0x0F + day := int((bytes[1] & 0xF8) >> 3) + hour := int(((bytes[1] & 0x07) << 2) | ((bytes[2] & 0xC0) >> 6)) + minute := int(bytes[2] & 0x3F) + + return time.Date(year, time.Month(month), day, hour, minute, 0, 0, location), nil +} + +// EncodeTimestampUTC according to [AI] 29.5.4.4, always using timeframe type UTC +func EncodeTimestampUTC(timestamp time.Time) []byte { + result := make([]byte, 3) + utc := timestamp.UTC() + + result[0] = 0x40 // always use timeframe type UTC + result[0] |= byte(utc.Month()) & 0x0F + result[1] = (byte(utc.Day()) << 3) & 0xF8 + result[1] |= (byte(utc.Hour()) >> 2) & 0x07 + result[2] = (byte(utc.Hour()) << 6) & 0xC0 + result[2] |= byte(utc.Minute()) & 0x3F + + return result +} diff --git a/sds/sds_test.go b/sds/sds_test.go new file mode 100644 index 0000000..9581ab5 --- /dev/null +++ b/sds/sds_test.go @@ -0,0 +1,508 @@ +package sds + +import ( + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestParseMessage(t *testing.T) { + tt := []struct { + desc string + header string + pdu string + expected IncomingMessage + immediate bool + invalid bool + }{ + { + desc: "empty string", + invalid: true, + }, + { + desc: "status", + header: "+CTSDSR: 13,1234567,0,2345678,0,16", + pdu: "8004", + expected: IncomingMessage{ + Header: Header{AIService: StatusService, Source: "1234567", Destination: "2345678", PDUBits: 16}, + Payload: Status2, + }, + }, + { + desc: "simple text message", + header: "+CTSDSR: 12,1234567,0,2345678,0,224", + pdu: "0201746573746D657373616765", + expected: IncomingMessage{ + Header: Header{AIService: SDSTLService, Source: "1234567", Destination: "2345678", PDUBits: 224}, + Payload: SimpleTextMessage{ + protocol: SimpleTextMessaging, + Encoding: ISO8859_1, + Text: "testmessage", + }, + }, + }, + { + desc: "simple text message without text", + header: "+CTSDSR: 12,1234567,0,2345678,0,16", + pdu: "0201", + expected: IncomingMessage{ + Header: Header{AIService: SDSTLService, Source: "1234567", Destination: "2345678", PDUBits: 16}, + Payload: SimpleTextMessage{ + protocol: SimpleTextMessaging, + Encoding: ISO8859_1, + Text: "", + }, + }, + }, + { + desc: "immediate simple text message", + header: "+CTSDSR: 12,1234567,0,2345678,0,104", + pdu: "0901746573746D657373616765", + expected: IncomingMessage{ + Header: Header{AIService: SDSTLService, Source: "1234567", Destination: "2345678", PDUBits: 104}, + Payload: SimpleTextMessage{ + protocol: SimpleImmediateTextMessaging, + Encoding: ISO8859_1, + Text: "testmessage", + }, + }, + immediate: true, + }, + { + desc: "text message, no report, no store/forward, no timestamp", + header: "+CTSDSR: 12,1234567,0,2345678,0,120", + pdu: "82029C01746573746D657373616765", + expected: IncomingMessage{ + Header: Header{AIService: SDSTLService, Source: "1234567", Destination: "2345678", PDUBits: 120}, + Payload: SDSTransfer{ + protocol: TextMessaging, + MessageReference: 0x9C, + UserData: TextSDU{ + TextHeader: TextHeader{ + Encoding: ISO8859_1, + }, + Text: "testmessage", + }, + }, + }, + }, + { + desc: "immediate text message, no report, no store/forward, no timestamp", + header: "+CTSDSR: 12,1234567,0,2345678,0,120", + pdu: "89029C01746573746D657373616765", + expected: IncomingMessage{ + Header: Header{AIService: SDSTLService, Source: "1234567", Destination: "2345678", PDUBits: 120}, + Payload: SDSTransfer{ + protocol: ImmediateTextMessaging, + MessageReference: 0x9C, + UserData: TextSDU{ + TextHeader: TextHeader{ + Encoding: ISO8859_1, + }, + Text: "testmessage", + }, + }, + }, + immediate: true, + }, + { + desc: "text message, no report, store/forward to SSI, no timestamp", + header: "+CTSDSR: 12,1234567,0,2345678,0,152", + pdu: "82039C5101020301746573746D657373616765", + expected: IncomingMessage{ + Header: Header{AIService: SDSTLService, Source: "1234567", Destination: "2345678", PDUBits: 152}, + Payload: SDSTransfer{ + protocol: TextMessaging, + MessageReference: 0x9C, + StoreForwardControl: StoreForwardControl{ + Valid: true, + ValidityPeriod: ValidityPeriod(5 * time.Minute), + ForwardAddressType: ForwardToSSI, + ForwardAddressSSI: ForwardAddressSSI{1, 2, 3}, + }, + UserData: TextSDU{ + TextHeader: TextHeader{ + Encoding: ISO8859_1, + }, + Text: "testmessage", + }, + }, + }, + }, + { + desc: "text message, no report, no store/forward, with timestamp", + header: "+CTSDSR: 12,1234567,0,2345678,0,144", + pdu: "82029C81045A8F746573746D657373616765", + expected: IncomingMessage{ + Header: Header{AIService: SDSTLService, Source: "1234567", Destination: "2345678", PDUBits: 144}, + Payload: SDSTransfer{ + protocol: TextMessaging, + MessageReference: 0x9C, + UserData: TextSDU{ + TextHeader: TextHeader{ + Encoding: ISO8859_1, + Timestamp: time.Date(2021, time.April, 11, 10, 15, 0, 0, time.Local), + }, + Text: "testmessage", + }, + }, + }, + }, + { + desc: "concatenated text message part 1 of 2, no report, no store/forward, with timestamp", + header: "+CTSDSR: 12,1234567,0,2345678,0,192", + pdu: "8A02C981045A8F050003C90201746573746D657373616765", + expected: IncomingMessage{ + Header: Header{AIService: SDSTLService, Source: "1234567", Destination: "2345678", PDUBits: 192}, + Payload: SDSTransfer{ + protocol: UserDataHeaderMessaging, + MessageReference: 0xC9, + UserData: ConcatenatedTextSDU{ + TextSDU: TextSDU{ + TextHeader: TextHeader{ + Encoding: ISO8859_1, + Timestamp: time.Date(2021, time.April, 11, 10, 15, 0, 0, time.Local), + }, + Text: "testmessage", + }, + UserDataHeader: ConcatenatedTextUDH{ + HeaderLength: 5, + ElementID: 0, + ElementLength: 3, + MessageReference: 0xC9, + TotalNumber: 2, + SequenceNumber: 1, + }, + }, + }, + }, + }, + { + desc: "concatenated text message part 2 of 2, no report, no store/forward, with timestamp", + header: "+CTSDSR: 12,1234567,0,2345678,0,192", + pdu: "8A02CA81045A8F050003C90202746573746D657373616765", + expected: IncomingMessage{ + Header: Header{AIService: SDSTLService, Source: "1234567", Destination: "2345678", PDUBits: 192}, + Payload: SDSTransfer{ + protocol: UserDataHeaderMessaging, + MessageReference: 0xCA, + UserData: ConcatenatedTextSDU{ + TextSDU: TextSDU{ + TextHeader: TextHeader{ + Encoding: ISO8859_1, + Timestamp: time.Date(2021, time.April, 11, 10, 15, 0, 0, time.Local), + }, + Text: "testmessage", + }, + UserDataHeader: ConcatenatedTextUDH{ + HeaderLength: 5, + ElementID: 0, + ElementLength: 3, + MessageReference: 0xC9, + TotalNumber: 2, + SequenceNumber: 2, + }, + }, + }, + }, + }, + { + desc: "SDS-REPORT success, no ack, no store/forward", + header: "+CTSDSR: 12,1234567,0,2345678,0,32", + pdu: "821000C9", + expected: IncomingMessage{ + Header: Header{AIService: SDSTLService, Source: "1234567", Destination: "2345678", PDUBits: 32}, + Payload: SDSReport{ + protocol: TextMessaging, + DeliveryStatus: ReceiptAckByDestination, + MessageReference: 0xC9, + }, + }, + }, + { + desc: "SDS-REPORT success, ack required, no store/forward", + header: "+CTSDSR: 12,1234567,0,2345678,0,32", + pdu: "821800CA", + expected: IncomingMessage{ + Header: Header{AIService: SDSTLService, Source: "1234567", Destination: "2345678", PDUBits: 32}, + Payload: SDSReport{ + protocol: TextMessaging, + AckRequired: true, + DeliveryStatus: ReceiptAckByDestination, + MessageReference: 0xCA, + }, + }, + }, + { + desc: "SDS-ACK success", + header: "+CTSDSR: 12,1234567,0,2345678,0,32", + pdu: "822001C9", + expected: IncomingMessage{ + Header: Header{AIService: SDSTLService, Source: "1234567", Destination: "2345678", PDUBits: 32}, + Payload: SDSAcknowledge{ + protocol: TextMessaging, + DeliveryStatus: ReceiptReportAck, + MessageReference: 0xC9, + }, + }, + }, + { + desc: "SDS-SHORT-REPORT success", + header: "+CTSDSR: 13,1234567,0,2345678,0,16", + pdu: "7ACA", + expected: IncomingMessage{ + Header: Header{AIService: StatusService, Source: "1234567", Destination: "2345678", PDUBits: 16}, + Payload: SDSShortReport{ + ReportType: MessageReceivedShort, + MessageReference: 0xCA, + }, + }, + }, + } + type immediater interface { + Immediate() bool + } + for _, tc := range tt { + t.Run(tc.desc, func(t *testing.T) { + actual, err := ParseIncomingMessage(tc.header, tc.pdu) + if tc.invalid { + assert.Error(t, err) + } else { + assert.NoError(t, err) + assert.Equal(t, tc.expected, actual) + + if tc.immediate { + i, ok := tc.expected.Payload.(immediater) + assert.True(t, ok) + assert.True(t, i.Immediate()) + } + } + }) + } +} + +func TestTimestampRoundtrip(t *testing.T) { + now := time.Now() + expected := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), 0, 0, time.Local).UTC() + + actual, err := DecodeTimestamp(EncodeTimestampUTC(now)) + + assert.NoError(t, err) + assert.Equal(t, expected, actual) +} + +func TestValidityPeriod_Decode(t *testing.T) { + tt := []struct { + value byte + expected time.Duration + }{ + {0, 0}, + {1, 10 * time.Second}, + {2, 20 * time.Second}, + {6, 1 * time.Minute}, + {7, 2 * time.Minute}, + {10, 5 * time.Minute}, + {11, 10 * time.Minute}, + {12, 20 * time.Minute}, + {16, 1 * time.Hour}, + {17, 2 * time.Hour}, + {22, 12 * time.Hour}, + {23, 18 * time.Hour}, + {25, 2 * 24 * time.Hour}, + {26, 4 * 24 * time.Hour}, + {30, 12 * 24 * time.Hour}, + {31, time.Duration(InfinitelyValid)}, + } + for _, tc := range tt { + t.Run(fmt.Sprintf("%d", tc.value), func(t *testing.T) { + actual := ParseValidityPeriod(tc.value) + assert.Equal(t, ValidityPeriod(tc.expected), actual) + }) + } +} + +func TestValidityPeriod_Encode(t *testing.T) { + tt := []struct { + value time.Duration + expected byte + }{ + {0, 0}, + {1 * time.Millisecond, 1}, + {1 * time.Second, 1}, + {1*time.Second + 1*time.Millisecond, 1}, + {10 * time.Second, 1}, + {10*time.Second + 1*time.Millisecond, 2}, + {20 * time.Second, 2}, + {1 * time.Minute, 6}, + {1*time.Minute + 1*time.Millisecond, 7}, + {2 * time.Minute, 7}, + {2*time.Minute + 1*time.Millisecond, 8}, + {5 * time.Minute, 10}, + {5*time.Minute + 1*time.Millisecond, 11}, + {10 * time.Minute, 11}, + {10*time.Minute + 1*time.Millisecond, 12}, + {1 * time.Hour, 16}, + {1*time.Hour + 1*time.Millisecond, 17}, + {2 * time.Hour, 17}, + {2*time.Hour + 1*time.Millisecond, 18}, + {6 * time.Hour, 21}, + {6*time.Hour + 1*time.Millisecond, 22}, + {7 * time.Hour, 22}, + {12 * time.Hour, 22}, + {12*time.Hour + 1*time.Millisecond, 23}, + {24 * time.Hour, 24}, + {24*time.Hour + 1*time.Millisecond, 25}, + {2 * 24 * time.Hour, 25}, + {2*24*time.Hour + 1*time.Millisecond, 26}, + {3 * 24 * time.Hour, 26}, + {4 * 24 * time.Hour, 26}, + {4*24*time.Hour + 1*time.Millisecond, 27}, + {5 * 24 * time.Hour, 27}, + {6 * 24 * time.Hour, 27}, + {7 * 24 * time.Hour, 28}, + {8 * 24 * time.Hour, 28}, + {9 * 24 * time.Hour, 29}, + {10 * 24 * time.Hour, 29}, + {11 * 24 * time.Hour, 30}, + {12 * 24 * time.Hour, 30}, + {12*24*time.Hour + 1*time.Millisecond, 31}, + } + for _, tc := range tt { + t.Run(fmt.Sprintf("%v", tc.value), func(t *testing.T) { + actual, _ := ValidityPeriod(tc.value).Encode() + assert.Equal(t, tc.expected, actual[0]) + }) + } +} + +func TestStatusBytes(t *testing.T) { + assert.Equal(t, []byte{0x80, 0x04}, Status2.Bytes()) +} + +func TestParseHeader(t *testing.T) { + tt := []struct { + desc string + value string + expected Header + invalid bool + }{ + { + desc: "empty string", + value: "", + invalid: true, + }, + { + desc: "valid minimum set", + value: "+CTSDSR: 12,1234567,16", + expected: Header{ + AIService: SDSTLService, + Destination: "1234567", + PDUBits: 16, + }, + }, + { + desc: "valid minimum set with identity type", + value: "+CTSDSR: 12,1234567,0,16", + expected: Header{ + AIService: SDSTLService, + Destination: "1234567", + PDUBits: 16, + }, + }, + { + desc: "valid with source identity", + value: "+CTSDSR: 12,1234567,0,2345678,0,16", + expected: Header{ + AIService: SDSTLService, + Source: "1234567", + Destination: "2345678", + PDUBits: 16, + }, + }, + { + desc: "valid with source identity and end-to-end encryption", + value: "+CTSDSR: 12,1234567,0,2345678,0,1,16", + expected: Header{ + AIService: SDSTLService, + Source: "1234567", + Destination: "2345678", + PDUBits: 16, + }, + }, + } + for _, tc := range tt { + t.Run(tc.desc, func(t *testing.T) { + actual, err := ParseHeader(tc.value) + if tc.invalid { + assert.Error(t, err) + } else { + assert.NoError(t, err) + assert.Equal(t, tc.expected, actual) + } + }) + } +} + +func TestEncode(t *testing.T) { + tt := []struct { + desc string + values []Encoder + expectedBytes []byte + expectedBits int + }{ + { + desc: "single entities", + values: []Encoder{ + SimpleTextMessaging, + ConsumedReportAck, + }, + expectedBytes: []byte{0x02, 0x03}, + expectedBits: 16, + }, + { + desc: "SDS-REPORT", + values: []Encoder{ + SDSReport{ + protocol: TextMessaging, + AckRequired: true, + DeliveryStatus: ReceiptAckByDestination, + MessageReference: 0xCA, + }, + }, + expectedBytes: []byte{0x82, 0x18, 0x00, 0xCA}, + expectedBits: 32, + }, + { + desc: "SDS-TRANSFER text message, delivery report requested", + values: []Encoder{ + SDSTransfer{ + protocol: TextMessaging, + DeliveryReportRequest: MessageReceivedReportRequested, + MessageReference: 0xC9, + UserData: TextSDU{ + TextHeader: TextHeader{ + Encoding: ISO8859_1, + Timestamp: time.Date(2021, time.April, 11, 10, 15, 0, 0, time.UTC), + }, + Text: "testmessage", + }, + }, + }, + expectedBytes: []byte{0x82, 0x06, 0xC9, 0x81, 0x44, 0x5A, 0x8F, 0x74, 0x65, 0x73, 0x74, 0x6D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65}, + expectedBits: 144, + }, + } + for _, tc := range tt { + t.Run(tc.desc, func(t *testing.T) { + actualBytes := make([]byte, 0) + actualBits := 0 + for _, value := range tc.values { + actualBytes, actualBits = value.Encode(actualBytes, actualBits) + } + assert.Equal(t, tc.expectedBytes, actualBytes) + assert.Equal(t, tc.expectedBits, actualBits) + }) + } +} diff --git a/sds/stack.go b/sds/stack.go new file mode 100644 index 0000000..4b30caf --- /dev/null +++ b/sds/stack.go @@ -0,0 +1,204 @@ +package sds + +import ( + "fmt" + "log" + "time" + + "github.com/ftl/tetra-pei/tetra" +) + +type Message struct { + ID int + Source tetra.Identity + Destination tetra.Identity + Timestamp time.Time + parts []part +} + +func NewMessage(id int, source tetra.Identity, destination tetra.Identity, timestamp time.Time, parts int) Message { + return Message{ + ID: id, + Source: source, + Destination: destination, + Timestamp: timestamp, + parts: make([]part, parts), + } +} + +func (m Message) Complete() bool { + for _, part := range m.parts { + if !part.Valid { + return false + } + } + return true +} + +func (m Message) Text() string { + var result string + for _, part := range m.parts { + if part.Valid { + result += part.Text + } else if result != "" { + result += "..." + } + } + return result +} + +func (m Message) String() string { + return fmt.Sprintf("Message 0x%x from %s to %s at %s:\n%s", + m.ID, m.Source, m.Destination, m.Timestamp.Format(time.RFC3339), m.Text()) +} + +func (m *Message) SetPart(i int, text string) { + i -= 1 + if i < 0 || i >= len(m.parts) { + return + } + + m.parts[i].Text = text + m.parts[i].Valid = true +} + +type part struct { + Valid bool + Text string +} + +type MessageCallback func(Message) + +type StatusMessage struct { + Source tetra.Identity + Destination tetra.Identity + Value Status +} + +func (s StatusMessage) String() string { + return fmt.Sprintf("Status 0x%x from %s to %s", s.Value, s.Source, s.Destination) +} + +type StatusCallback func(StatusMessage) + +type ResponseCallback func([]string) error + +type Stack struct { + messageCallback MessageCallback + statusCallback StatusCallback + responseCallback ResponseCallback + pendingMessages map[int]Message +} + +func NewStack() *Stack { + return &Stack{ + pendingMessages: make(map[int]Message), + } +} + +func (s *Stack) WithMessageCallback(callback MessageCallback) *Stack { + s.messageCallback = callback + return s +} + +func (s *Stack) WithStatusCallback(callback StatusCallback) *Stack { + s.statusCallback = callback + return s +} + +func (s *Stack) WithResponseCallback(callback ResponseCallback) *Stack { + s.responseCallback = callback + return s +} + +func (s *Stack) Put(part IncomingMessage) error { + switch payload := part.Payload.(type) { + case Status: + log.Print("incoming status") + if s.statusCallback == nil { + return nil + } + s.statusCallback(StatusMessage{ + Source: part.Header.Source, + Destination: part.Header.Destination, + Value: payload, + }) + case SimpleTextMessage: + log.Print("incoming simple text message") + if s.messageCallback == nil { + return nil + } + message := NewMessage( + 0, + part.Header.Source, + part.Header.Destination, + time.Time{}, + 1) + message.SetPart(1, payload.Text) + s.messageCallback(message) + case SDSTransfer: + log.Print("incoming SDS-TRANSFER") + return s.putSDSTransfer(part.Header, payload) + default: + return fmt.Errorf("unexpected message type %T", payload) + } + + return nil +} + +func (s *Stack) putSDSTransfer(header Header, sdsTransfer SDSTransfer) error { + var messageID int + var message Message + var ok bool + + switch sdu := sdsTransfer.UserData.(type) { + case TextSDU: + messageID = int(sdsTransfer.MessageReference) + message = NewMessage( + messageID, + header.Source, + header.Destination, + sdu.Timestamp, + 1, + ) + message.SetPart(1, sdu.Text) + + if s.responseCallback != nil && sdsTransfer.ReceivedReportRequested() { + ackRequired := false // TODO should be configurable or a parameter + sdsReport := NewSDSReport(sdsTransfer, ackRequired, ReceiptAckByDestination) + + s.responseCallback([]string{ + SwitchToSDSTL, + SendMessage(header.Source, sdsReport), + }) + } + case ConcatenatedTextSDU: + messageID = int(sdu.UserDataHeader.MessageReference) + message, ok = s.pendingMessages[messageID] + if !ok { + message = NewMessage( + messageID, + header.Source, + header.Destination, + sdu.Timestamp, + int(sdu.UserDataHeader.TotalNumber), + ) + } else if message.Source != header.Source || + message.Destination != header.Destination || + len(message.parts) != int(sdu.UserDataHeader.TotalNumber) { + return fmt.Errorf("part does not match message 0x%x: %s != %s | %s != %s | %d != %d", message.ID, message.Source, header.Source, message.Destination, header.Destination, len(message.parts), int(sdu.UserDataHeader.TotalNumber)) + } + message.SetPart(int(sdu.UserDataHeader.SequenceNumber), sdu.Text) + default: + return fmt.Errorf("unexpected SDS-TRANSFER SDU: %T", sdu) + } + + if message.Complete() && s.messageCallback != nil { + s.messageCallback(message) + delete(s.pendingMessages, message.ID) + } else { + s.pendingMessages[message.ID] = message + } + + return nil +} diff --git a/sds/stack_test.go b/sds/stack_test.go new file mode 100644 index 0000000..386b0a8 --- /dev/null +++ b/sds/stack_test.go @@ -0,0 +1,264 @@ +package sds + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestStack_Put_Status(t *testing.T) { + value := IncomingMessage{ + Header: Header{AIService: StatusService, Source: "1234567", Destination: "2345678", PDUBits: 16}, + Payload: Status4, + } + expected := StatusMessage{ + Source: "1234567", + Destination: "2345678", + Value: Status4, + } + + var status StatusMessage + statusReceived := false + stack := NewStack().WithStatusCallback(func(s StatusMessage) { + status = s + statusReceived = true + }) + + err := stack.Put(value) + + require.NoError(t, err) + assert.True(t, statusReceived) + assert.Equal(t, expected, status) +} + +func TestStack_Put_SimpleTextMessage(t *testing.T) { + value := IncomingMessage{ + Header: Header{AIService: SDSTLService, Source: "1234567", Destination: "2345678", PDUBits: 224}, + Payload: SimpleTextMessage{ + protocol: SimpleTextMessaging, + Encoding: ISO8859_1, + Text: "testmessage", + }, + } + expected := Message{ + Source: "1234567", + Destination: "2345678", + parts: []part{ + {Valid: true, Text: "testmessage"}, + }, + } + + var message Message + messageReceived := false + stack := NewStack().WithMessageCallback(func(m Message) { + message = m + messageReceived = true + }) + + err := stack.Put(value) + + require.NoError(t, err) + assert.True(t, messageReceived) + assert.Equal(t, expected, message) +} + +func TestStack_Put_TextMessage(t *testing.T) { + value := IncomingMessage{ + Header: Header{AIService: SDSTLService, Source: "1234567", Destination: "2345678", PDUBits: 120}, + Payload: SDSTransfer{ + protocol: TextMessaging, + MessageReference: 0xC9, + UserData: TextSDU{ + TextHeader: TextHeader{ + Encoding: ISO8859_1, + Timestamp: time.Date(2021, time.April, 11, 10, 15, 0, 0, time.Local), + }, + Text: "testmessage", + }, + }, + } + expected := Message{ + ID: 0xC9, + Source: "1234567", + Destination: "2345678", + Timestamp: time.Date(2021, time.April, 11, 10, 15, 0, 0, time.Local), + parts: []part{ + {Valid: true, Text: "testmessage"}, + }, + } + + var message Message + messageReceived := false + stack := NewStack().WithMessageCallback(func(m Message) { + message = m + messageReceived = true + }) + + err := stack.Put(value) + + require.NoError(t, err) + assert.True(t, messageReceived) + assert.Equal(t, expected, message) +} + +func TestStack_Put_SinglePartConcatenatedMessage(t *testing.T) { + value := IncomingMessage{ + Header: Header{AIService: SDSTLService, Source: "1234567", Destination: "2345678", PDUBits: 192}, + Payload: SDSTransfer{ + protocol: UserDataHeaderMessaging, + MessageReference: 0xC9, + UserData: ConcatenatedTextSDU{ + TextSDU: TextSDU{ + TextHeader: TextHeader{ + Encoding: ISO8859_1, + Timestamp: time.Date(2021, time.April, 11, 10, 15, 0, 0, time.Local), + }, + Text: "testmessage", + }, + UserDataHeader: ConcatenatedTextUDH{ + HeaderLength: 5, + ElementID: 0, + ElementLength: 3, + MessageReference: 0xC9, + TotalNumber: 1, + SequenceNumber: 1, + }, + }, + }, + } + expected := Message{ + ID: 0xC9, + Source: "1234567", + Destination: "2345678", + Timestamp: time.Date(2021, time.April, 11, 10, 15, 0, 0, time.Local), + parts: []part{ + {Valid: true, Text: "testmessage"}, + }, + } + + var message Message + messageReceived := false + stack := NewStack().WithMessageCallback(func(m Message) { + message = m + messageReceived = true + }) + + err := stack.Put(value) + + require.NoError(t, err) + assert.True(t, messageReceived) + assert.Equal(t, expected, message) +} + +func TestStack_Put_MultiPartConcatenatedMessage(t *testing.T) { + values := []IncomingMessage{ + { + Header: Header{AIService: SDSTLService, Source: "1234567", Destination: "2345678", PDUBits: 200}, + Payload: SDSTransfer{ + protocol: UserDataHeaderMessaging, + MessageReference: 0xC9, + UserData: ConcatenatedTextSDU{ + TextSDU: TextSDU{ + TextHeader: TextHeader{ + Encoding: ISO8859_1, + Timestamp: time.Date(2021, time.April, 11, 10, 15, 0, 0, time.Local), + }, + Text: "testmessage1", + }, + UserDataHeader: ConcatenatedTextUDH{ + HeaderLength: 5, + ElementID: 0, + ElementLength: 3, + MessageReference: 0xC9, + TotalNumber: 2, + SequenceNumber: 1, + }, + }, + }, + }, + { + Header: Header{AIService: SDSTLService, Source: "1234567", Destination: "2345678", PDUBits: 208}, + Payload: SDSTransfer{ + protocol: UserDataHeaderMessaging, + MessageReference: 0xCA, + UserData: ConcatenatedTextSDU{ + TextSDU: TextSDU{ + TextHeader: TextHeader{ + Encoding: ISO8859_1, + Timestamp: time.Date(2021, time.April, 11, 10, 15, 0, 0, time.Local), + }, + Text: "\ntestmessage2", + }, + UserDataHeader: ConcatenatedTextUDH{ + HeaderLength: 5, + ElementID: 0, + ElementLength: 3, + MessageReference: 0xC9, + TotalNumber: 2, + SequenceNumber: 2, + }, + }, + }, + }, + } + expected := Message{ + ID: 0xC9, + Source: "1234567", + Destination: "2345678", + Timestamp: time.Date(2021, time.April, 11, 10, 15, 0, 0, time.Local), + parts: []part{ + {Valid: true, Text: "testmessage1"}, + {Valid: true, Text: "\ntestmessage2"}, + }, + } + + var message Message + messageReceived := false + stack := NewStack().WithMessageCallback(func(m Message) { + message = m + messageReceived = true + }) + + for i, value := range values { + err := stack.Put(value) + require.NoErrorf(t, err, "part %d", i) + } + + assert.True(t, messageReceived) + assert.Equal(t, expected, message) +} + +func TestStack_Put_TextMessage_ReceiptReportRequested(t *testing.T) { + value := IncomingMessage{ + Header: Header{AIService: SDSTLService, Source: "1234567", Destination: "2345678", PDUBits: 120}, + Payload: SDSTransfer{ + protocol: TextMessaging, + MessageReference: 0xC9, + DeliveryReportRequest: MessageReceivedReportRequested, + UserData: TextSDU{ + TextHeader: TextHeader{ + Encoding: ISO8859_1, + Timestamp: time.Date(2021, time.April, 11, 10, 15, 0, 0, time.Local), + }, + Text: "testmessage", + }, + }, + } + expected := []string{"AT+CTSDS=12,0,0,0,1", "AT+CMGS=1234567,32\r\n821000C9\x1a"} + + responses := make([]string, 0) + responseReceived := false + stack := NewStack().WithResponseCallback(func(s []string) error { + responses = s + responseReceived = true + return nil + }) + + err := stack.Put(value) + + require.NoError(t, err) + assert.True(t, responseReceived) + assert.Equal(t, expected, responses) +} diff --git a/sds/text.go b/sds/text.go new file mode 100644 index 0000000..4930b69 --- /dev/null +++ b/sds/text.go @@ -0,0 +1,133 @@ +package sds + +import ( + "fmt" + "log" + "time" +) + +/* Text related types and functions */ + +// TextEncoding enum according to [AI] 29.5.4.1 +type TextEncoding byte + +// All supported text encoding schemes, according to [AI] table 29.29 +const ( + Packed7Bit TextEncoding = 0 + ISO8859_1 TextEncoding = 1 +) + +// TextBytes returns the length in bytes of an encoded text with +// the given number of characters and the given encoding +func TextBytes(encoding TextEncoding, length int) int { + bits := TextBytesToBits(encoding, length) + bytes := bits / 8 + if bits%8 > 0 { + bytes++ + } + return bytes +} + +// TextBytesToBits returns the length in bits of an encoded text with +// the given number of characters and the given encoding +func TextBytesToBits(encoding TextEncoding, length int) int { + switch encoding { + case Packed7Bit: + return length*8 - length + default: + return length * 8 + } +} + +// ParseTextHeader in text messages and concatenated text messages. +func ParseTextHeader(bytes []byte) (TextHeader, error) { + if len(bytes) < 1 { + return TextHeader{}, fmt.Errorf("text header too short: %d", len(bytes)) + } + + var result TextHeader + + timestampUsed := (bytes[0] & 0x80) == 0x80 + if timestampUsed && len(bytes) < 7 { + return TextHeader{}, fmt.Errorf("text header with timestamp too short: %d", len(bytes)) + } + result.Encoding = TextEncoding(bytes[0] & 0x7F) + + var timestamp time.Time + var err error + if timestampUsed { + timestamp, err = DecodeTimestamp(bytes[1:4]) + if err != nil { + return TextHeader{}, err + } + } + result.Timestamp = timestamp + + return result, nil +} + +// TextHeader represents the meta information for text used in text messages according to [AI] 29.5.3.3 +// and concatenated text messages according to [AI] 29.5.10.3 +type TextHeader struct { + Encoding TextEncoding + Timestamp time.Time +} + +// Encode this text header +func (h TextHeader) Encode(bytes []byte, bits int) ([]byte, int) { + bytes = append(bytes, byte(h.Encoding)) + bits += 8 + if !h.Timestamp.IsZero() { + bytes[len(bytes)-1] |= 0x80 + bytes = append(bytes, EncodeTimestampUTC(h.Timestamp)...) + bits += 24 + } + + return bytes, bits +} + +// Length returns the length of this text header in bytes. +func (h TextHeader) Length() int { + if h.Timestamp.IsZero() { + return 1 + } + return 4 +} + +// DecodePayloadText decodes the actual text content using the given encoding scheme according to [AI] 29.5.4 +func DecodePayloadText(encoding TextEncoding, bytes []byte) (string, error) { + switch encoding { + case ISO8859_1: // only ISO8859-1 at the moment + return decodeISO8859_1(bytes) + default: // be lenient and use ISO8859-1 as fallback + log.Printf("encoding 0x%x is currently not supported, using ISO8859-1 as fallback", encoding) + return decodeISO8859_1(bytes) + } +} + +func decodeISO8859_1(bytes []byte) (string, error) { + utf8Buf := make([]rune, len(bytes)) + for i, b := range bytes { + utf8Buf[i] = rune(b) + } + return string(utf8Buf), nil +} + +func AppendEncodedPayloadText(bytes []byte, bits int, text string, encoding TextEncoding) ([]byte, int) { + var encodedBytes []byte + var encodedBits int + switch encoding { + case ISO8859_1: // only ISO8859-1 at the moment + encodedBytes, encodedBits = encodeISO8859_1(text) + default: // be lenient and use ISO8859-1 as fallback + encodedBytes, encodedBits = encodeISO8859_1(text) + } + + bytes = append(bytes, encodedBytes...) + bits += encodedBits + return bytes, bits +} + +func encodeISO8859_1(text string) ([]byte, int) { + return []byte(text), len(text) * 8 +} diff --git a/tetra/tetra.go b/tetra/tetra.go new file mode 100644 index 0000000..8efcab1 --- /dev/null +++ b/tetra/tetra.go @@ -0,0 +1,42 @@ +package tetra + +import ( + "encoding/hex" + "regexp" + "strings" +) + +// Identity represents an identity of a party in a TETRA communication +type Identity string + +// IdentityType enum according to [PEI] 6.17.11 and 6.17.12 +type IdentityType byte + +// All defined IdentityType values +const ( + SSI IdentityType = iota + TSI + SNA + PABX + PSTN + ExtendedTSI +) + +// TypedIdentity combines an identity with its type in one struct +type TypedIdentity struct { + Identity Identity + Type IdentityType +} + +var hexSanitizer = regexp.MustCompile(`\s+`) + +// HexToBinary converts the hex representation used along the PEI for binary data into a slice of bytes +func HexToBinary(s string) ([]byte, error) { + sanitized := hexSanitizer.ReplaceAllString(s, "") + return hex.DecodeString(sanitized) +} + +// BinaryToHex converts a slice of bytes into the hex representation used along the PEI for binary data +func BinaryToHex(pdu []byte) string { + return strings.ToUpper(hex.EncodeToString(pdu)) +} diff --git a/tetra/tetra_test.go b/tetra/tetra_test.go new file mode 100644 index 0000000..3b88efc --- /dev/null +++ b/tetra/tetra_test.go @@ -0,0 +1,17 @@ +package tetra + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestHexBinaryRoundtrip(t *testing.T) { + hex := "82000201546573746E6163687269636874" + + pdu, err := HexToBinary(hex) + assert.NoError(t, err) + + actual := BinaryToHex(pdu) + assert.Equal(t, hex, actual) +}