From fe65b592fa86d72dc2229239a41971ac942bac07 Mon Sep 17 00:00:00 2001 From: Daniel Kondlatsch Date: Sat, 28 Jan 2023 07:53:51 -0300 Subject: [PATCH] First upload First upload, copy from original project v0.3.6 --- LICENSE | 674 ++++++++++++++++++++++++++++++++ M17-ref-packet-description.ods | Bin 0 -> 18810 bytes Makefile | 82 ++++ README.md | 137 +++++++ base.cpp | 66 ++++ base.h | 28 ++ bwset.cpp | 202 ++++++++++ bwset.h | 61 +++ callsign.cpp | 155 ++++++++ callsign.h | 46 +++ client.cpp | 108 ++++++ client.h | 91 +++++ clients.cpp | 165 ++++++++ clients.h | 74 ++++ config/mrefd.blacklist | 14 + config/mrefd.interlink | 20 + config/mrefd.whitelist | 14 + configure.h | 5 + configure.mk | 2 + crc.cpp | 76 ++++ crc.h | 48 +++ gatekeeper.cpp | 185 +++++++++ gatekeeper.h | 74 ++++ ip.cpp | 296 ++++++++++++++ ip.h | 72 ++++ m17client.cpp | 47 +++ m17client.h | 50 +++ m17peer.cpp | 68 ++++ m17peer.h | 51 +++ m17protocol.cpp | 685 +++++++++++++++++++++++++++++++++ m17protocol.h | 85 ++++ main.cpp | 96 +++++ main.h | 105 +++++ mrefd.blacklist | 14 + mrefd.interlink | 22 ++ mrefd.whitelist | 14 + notification.cpp | 46 +++ notification.h | 59 +++ notificationqueue.h | 64 +++ packet.cpp | 86 +++++ packet.h | 82 ++++ packetqueue.h | 62 +++ packetstream.cpp | 92 +++++ packetstream.h | 67 ++++ peer.cpp | 130 +++++++ peer.h | 95 +++++ peermap.cpp | 244 ++++++++++++ peermap.h | 73 ++++ peermapitem.cpp | 142 +++++++ peermapitem.h | 65 ++++ peers.cpp | 175 +++++++++ peers.h | 74 ++++ protocol.cpp | 328 ++++++++++++++++ protocol.h | 113 ++++++ rconfig | 234 +++++++++++ reflector.cfg | 4 + reflector.cpp | 462 ++++++++++++++++++++++ reflector.h | 123 ++++++ systemd/mrefd.service | 12 + test-all.cpp | 57 +++ timepoint.cpp | 53 +++ timepoint.h | 48 +++ udpsocket.cpp | 171 ++++++++ udpsocket.h | 75 ++++ user.cpp | 84 ++++ user.h | 55 +++ users.cpp | 71 ++++ users.h | 53 +++ version.cpp | 79 ++++ version.h | 60 +++ 70 files changed, 7570 insertions(+) create mode 100644 LICENSE create mode 100644 M17-ref-packet-description.ods create mode 100644 Makefile create mode 100644 README.md create mode 100644 base.cpp create mode 100644 base.h create mode 100644 bwset.cpp create mode 100644 bwset.h create mode 100644 callsign.cpp create mode 100644 callsign.h create mode 100644 client.cpp create mode 100644 client.h create mode 100644 clients.cpp create mode 100644 clients.h create mode 100644 config/mrefd.blacklist create mode 100644 config/mrefd.interlink create mode 100644 config/mrefd.whitelist create mode 100644 configure.h create mode 100644 configure.mk create mode 100644 crc.cpp create mode 100644 crc.h create mode 100644 gatekeeper.cpp create mode 100644 gatekeeper.h create mode 100644 ip.cpp create mode 100644 ip.h create mode 100644 m17client.cpp create mode 100644 m17client.h create mode 100644 m17peer.cpp create mode 100644 m17peer.h create mode 100644 m17protocol.cpp create mode 100644 m17protocol.h create mode 100644 main.cpp create mode 100644 main.h create mode 100644 mrefd.blacklist create mode 100644 mrefd.interlink create mode 100644 mrefd.whitelist create mode 100644 notification.cpp create mode 100644 notification.h create mode 100644 notificationqueue.h create mode 100644 packet.cpp create mode 100644 packet.h create mode 100644 packetqueue.h create mode 100644 packetstream.cpp create mode 100644 packetstream.h create mode 100644 peer.cpp create mode 100644 peer.h create mode 100644 peermap.cpp create mode 100644 peermap.h create mode 100644 peermapitem.cpp create mode 100644 peermapitem.h create mode 100644 peers.cpp create mode 100644 peers.h create mode 100644 protocol.cpp create mode 100644 protocol.h create mode 100644 rconfig create mode 100644 reflector.cfg create mode 100644 reflector.cpp create mode 100644 reflector.h create mode 100644 systemd/mrefd.service create mode 100644 test-all.cpp create mode 100644 timepoint.cpp create mode 100644 timepoint.h create mode 100644 udpsocket.cpp create mode 100644 udpsocket.h create mode 100644 user.cpp create mode 100644 user.h create mode 100644 users.cpp create mode 100644 users.h create mode 100644 version.cpp create mode 100644 version.h 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/M17-ref-packet-description.ods b/M17-ref-packet-description.ods new file mode 100644 index 0000000000000000000000000000000000000000..66d70c24b0b20e18a2a16f6239ea9fa9a65e419d GIT binary patch literal 18810 zcmb5V1#De0vo0EDYM7as+AuRSCr!i5oHW^CW@ct+n3Q>ba&)w{ zGBI+saM>WFmkbSVRmpdvp01xakDeCcV%{QbT%_Gb+I%vb5;KT@chT-{}kMR zEingsb1Mrs=l|m7!p`FA;9zTP7;4< zAXc>C8~zZpnN?vHXlQ5JiFWI}zVD&h&@A_v=-WN9Nt!CfmFIa&2Y)0vc4C{du8auB zq8iHk)j3V*s3xQ>o6i_{JDJ-{Hh9-pTNp?(iSDd}O7iGCJnZRt3{yjxxR7jT8w+VY zGavYsy2$(gayv;QjWor=!4t=bT0I^9#^;&Yhd0+!alOco_j(}}h}z<<$ZtR}YEkVD zYavYt5RQSDp9pphBJ5C<8|FxTP~qt>xY{56)x8*0$p7n>A$E3kI~=L>=;v;C-L-zu z&hHdU?`sopx5eSR9g5^%+3eR!=be0Bpc5e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?iah*9YF&^g zc&13*{;5y&|AP_{En=2)mk1c1W}TX_SabUHuA*H_y641Sp4uubdL?M8Rh8-Yd(Qhz z&$Ik5J9(?`)a_sP6+9nSd-WNAkT`9ntG|B6`g;rdgO6?XmEJG7hHuST#tegxYUTI6^51rQo!MTeY=wz) z*g`GaUz+7c^l9w%GV=_vRq0V#@s%JBS(a$?sZSzE#qDl)vYcXPE%`bupe25cOd<@p4?qFM4+6lB zLqXStPytyQh~S3+nYa%;LA4v93*D41ET$k1Kq1zY16WK!9EgJ36wm=B2=EQaME4Q$ z0V%l60UeQo0D8a}KsN{Vz!cmjp}Hsoi%G}_sNgmS)kO=in1gzt3T~57U33eJNyrDR z;5G+z#0mlkF=2)g#(^sk!(eBIAfF}z+S`Bt{y@XvWe4y87FZ&N=|n!M0(9C40`vh_ zt^&^i0-rsCt_yj~FKEdt0^|T!(IU>YK-Y)7I|H;K7y%-I&Q3;b4@TFByg(P#gU`fJ zw{pOA;#$Cquu?`A_i|pCDX?HdE. + +# locations for the executibles and other files are set here +# NOTE: IF YOU CHANGE THESE, YOU WILL NEED TO UPDATE THE service.* FILES AND +# if you change these locations, make sure the sgs.service file is updated! +# you will also break hard coded paths in the dashboard file, index.php. + +include configure.mk + +# if you make changed in these two variable, you'll need to change things +# in the main.h file as well as the systemd service file. +BINDIR = /usr/local/bin +CFGDIR = /usr/local/etc +DATADIR = /var/lib/m17ref + +CFLAGS += -c -W -std=c++11 -MMD -MD -c + +ifeq ($(debug), true) +CFLAGS += -ggdb3 +endif + +ifeq ("$(OS)","Windows_NT") +CFLAGS += -D_GNU_SOURCE +endif + +LDFLAGS=-pthread + +SRCS = base.cpp bwset.cpp callsign.cpp client.cpp clients.cpp crc.cpp gatekeeper.cpp ip.cpp m17client.cpp m17peer.cpp m17protocol.cpp notification.cpp packet.cpp packetstream.cpp peer.cpp peermap.cpp peermapitem.cpp peers.cpp protocol.cpp reflector.cpp timepoint.cpp udpsocket.cpp user.cpp users.cpp version.cpp main.cpp + +OBJS = $(SRCS:.cpp=.o) +DEPS = $(SRCS:.cpp=.d) + +EXE=mrefd + +all : $(EXE) test-all + +test-all : test-all.o crc.o callsign.o + $(CXX) $^ -o $@ + +$(EXE) : $(OBJS) + $(CXX) $^ -o $@ $(LDFLAGS) + +%.o : %.cpp + $(CXX) $(CFLAGS) $< -o $@ + +clean : + $(RM) *.o *.d $(EXE) test-all + +-include $(DEPS) + +install : $(EXE).blacklist $(EXE).whitelist $(EXE).interlink + ln -s $(shell pwd)/$(EXE).blacklist $(CFGDIR)/$(EXE).blacklist + ln -s $(shell pwd)/$(EXE).whitelist $(CFGDIR)/$(EXE).whitelist + ln -s $(shell pwd)/$(EXE).interlink $(CFGDIR)/$(EXE).interlink + cp -f systemd/$(EXE).service /etc/systemd/system/ + cp -f $(EXE) $(BINDIR) + mkdir -p $(DATADIR) + systemctl enable $(EXE).service + systemctl daemon-reload + systemctl start $(EXE) + +uninstall : + rm -f $(CFGDIR)/$(EXE).blacklist + rm -f $(CFGDIR)/$(EXE).whitelist + rm -f $(CFGDIR)/$(EXE).interlink + systemctl stop $(EXE).service + systemctl disable $(EXE).service + rm -f /etc/systemd/system/$(EXE).service + systemctl daemon-reload diff --git a/README.md b/README.md new file mode 100644 index 0000000..4465b06 --- /dev/null +++ b/README.md @@ -0,0 +1,137 @@ +# MREFD + +MREFD is a new M17 open source Reflector. Most of the code is originally based on groundbreaking development of XLXD and the copyrights of all relevent source files reflect this. The sources are published under GPL Licenses. + +## Introduction + +This is prototype software. Currently, this totally ignores, and in fact assumes, that no client is using M17 encrytion. Incoming M17 voice streams are readdressed to each client by rewriting the destination callsign and then recalculating the CRC for each packet. + +Only systemd-based operating systems are supported. Debian or Ubuntu is recommended. If you want to install this on a non-systemd based OS, you are on your own. Also, by default, mrefd is built without gdb support. Finally, this repository is designed so that you don't have to modify any file in the repository when you build your system. Any file you need to modify to properly configure your reflector will be a file you copy from you locally cloned repo. This makes it easier to update the source code when this repository is updated. Follow the instructions below to build your M17 reflector. + +## Usage + +The packages which are described in this document are designed to install server software which is used for the digital voice network infrastructure. It requires a 24/7 internet connection which can support 20 voice streams or more to connect repeaters and hot-spots and other digitial voice clients! + +- The server can build a reflector that support IPv4, IPv6 or both (dual stack). +- The public IP addresses should have a DNS record which must be published in the common host files. + +## Installation + +Below are instructions for building an mrefd reflector. + +### After a clean installation of a Debian-based OS make sure to run update and upgrade + +```bash +sudo apt update +sudo apt upgrade +``` + +### Required packages (some of these may already be installed) + +```bash +sudo apt install git +sudo apt install apache2 php5 +sudo apt install build-essential +sudo apt install g++ +``` + +### Download the repository and enter the directory + +```bash +git clone https://github.com/n7tae/mrefd.git +cd mrefd +``` + +### Create and edit your blacklist, whitelist and linking files + +```bash +cp config/mrefd.blacklist . +cp config/mrefd.whitelist . +cp config/mrefd.interlink . +``` + +Use your favorite editor to modify each of these files. If you want a totally open network, the blacklist and whitelist files are ready to go. The blacklist determine which callsigns can't use the reflector. The whitelist determines which callsigns can use the reflector. The mrefd reflector will monitor these file and dynamically update itself whenever anything changes. There is no need to stop and restart the reflector. + +The mrefd.interlink file sets up the M17<--->M17 peer group linking. Please read the comments in this file. An M17 interlink now has to be configured on both sides of the link. Linked reflectors can share multiple modules, but cross module linking, for example, linking M17-000 module A to M17-001 module B is not supported. Also group linking demands all reflector in a group are linked to all other reflectors in the group. This will result in the shortest possible latency between a client and any other client on the group. This XLX-like mode of linking is enforced by implementing a *one hop* policy where a voice stream is marked by a reflector when it is passed to another reflector. The receiving reflector will then know not to pass the voice stream on to any other reflector. + +Group adminstration will require coordination among the admins of all involved reflectors. If a group memeber drops out or if a new member wants to join a group, all other group members will need to remove or add a line to their mrefd.interlink file. + +Finally, if both ends of a link in a group support IPv6, that part of the group can use IPv6 while the rest of the group can use IPv4. + +### Configuring your reflector + +Configuring, compiling and maintaining your reflector build is easy! Start the configuration script in the base directory of you cloned repo: + +```bash +./rconfig +``` + +There are only a few things that need to be specified. Most important are, the reflector callsign and the IP addresses for the IPv4 and IPv6 listen ports. The reflector callsign must be exactly 7 characters beginning with "M17-". The remaining 3 characters can be an combination of numbers or letters. Input will automatically be capitolized by rconfig. + +Dual-stack operation is enabled by specifying both an IPv4 and IPv6 address. IPv4-only single stack can be specified by leaving the IPv6 address set to `none`. It's even possible to operate in an IPv6-only configuration by leaving the IPv4 address to the default `none`. + +Be sure to write out the configuration files and look at the three different configration files that are created. The first file, reflector.cfg is the memory file for rconfig so that if you start that script again, it will remember how you left things. There is one `.h` file and one `.mk` file for the reflector. You should **not** modify these files by hand unless you really know exactly how they work. + +### Compling and installing your system + +After you have written your configutation files, you can build and install your system: + +```bash +make && sudo make install +``` + +Use this command to compile and install your system. Use `sudo make uninstall` to uninstall mrefd. + +### Stoping and starting the service manually + +To stop the execution of mrefd: + +```bash +sudo systemctl stop mrefd +``` + +You can start mrefd by replacing `stop` with `start`, or you can restart it by using `restart`. + +To view the mrefd log: + +```bash +sudo journalctl -u mrefd -f +``` + +The blacklist, whitelist and interlink files can be modified in real time while xrfd is executing and the reflector will update itself within a few seconds. Edit the files in build directory. While mrefd accesses the configuration files in /usr/local/etc, these files are symbolically linked back to your build directory. + +### Copy dashboard to /var/www + +The official M17 dashboard is in another repo. + +```bash +git clone https://github.com/M17-project/ref-dash /var/www/html # or where ever you system www root is located +``` + +Follow the instructions on that repo for configuring your dashboard. + +## Updating mrefd + +Here is the safest way to update your reflector: + +```bash +sudo make uninstall +make clean +git pull +make +sudo make install +``` + +If, after doing the `git pull`, you see that it's downloaded a new rconfig script, it would probably be a good idea to run it before doing a `make`. There may be new build options of which you might want to take advantage. + +## Firewall settings + +MREFD requires the following port to be open to inbound network traffic: + +- UDP port 17000 for M17 +- TCP port 80 for HTTP +- TCP port 443 for HTTPS + +## Copyright + +- Copyright © 2020 Thomas A. Early N7TAE diff --git a/base.cpp b/base.cpp new file mode 100644 index 0000000..fc9a78f --- /dev/null +++ b/base.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2020 by Thomas Early N7TAE + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include + +#include "base.h" + +void CBase::Dump(const char *title, const void *pointer, int length) +{ + const unsigned char *data = (const unsigned char *)pointer; + + std::cout << title << std::endl; + + unsigned int offset = 0U; + + while (length > 0) { + + unsigned int bytes = (length > 16) ? 16U : length; + + for (unsigned i = 0U; i < bytes; i++) { + if (i) + std::cout << " "; + std::cout << std::hex << std::setw(2) << std::right << std::setfill('0') << int(data[offset + i]); + } + + for (unsigned int i = bytes; i < 16U; i++) + std::cout << " "; + + std::cout << " *"; + + for (unsigned i = 0U; i < bytes; i++) { + unsigned char c = data[offset + i]; + + if (::isprint(c)) + std::cout << c; + else + std::cout << '.'; + } + + std::cout << '*' << std::endl; + + offset += 16U; + + if (length >= 16) + length -= 16; + else + length = 0; + } +} diff --git a/base.h b/base.h new file mode 100644 index 0000000..98b079c --- /dev/null +++ b/base.h @@ -0,0 +1,28 @@ +#pragma once +/* + * Copyright (C) 2020 by Thomas Early N7TAE + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +class CBase +{ +public: + CBase() {} + virtual ~CBase() {} + +protected: + void Dump(const char *title, const void *pointer, int length); +}; diff --git a/bwset.cpp b/bwset.cpp new file mode 100644 index 0000000..a26c0d2 --- /dev/null +++ b/bwset.cpp @@ -0,0 +1,202 @@ +// +// ccallsignlist.cpp +// m17ref +// +// Created by Jean-Luc Deltombe (LX3JL) on 30/12/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include +#include +#include + +#include "main.h" +#include "bwset.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CBWSet::CBWSet() +{ + m_Filename = nullptr; + ::memset(&m_LastModTime, 0, sizeof(time_t)); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// file io + +bool CBWSet::LoadFromFile(const char *filename) +{ + bool ok = false; + char sz[256]; + char szStar[2] = "*"; + + // and load + std::ifstream file (filename); + if ( file.is_open() ) + { + Lock(); + + // empty list + m_Callsigns.clear(); + // fill with file content + while ( file.getline(sz, sizeof(sz)).good() ) + { + // remove leading & trailing spaces + char *szt = TrimWhiteSpaces(sz); + + // crack it + if ( (strlen(szt) > 0) && (szt[0] != '#') ) + { + // 1st token is callsign + if ( (szt = strtok(szt, " ,\t")) != nullptr ) + { + std::string cs(ToUpper(szt)); + if (m_Callsigns.end() == m_Callsigns.find(cs)) + { + m_Callsigns.insert(cs); + } + else + { + std::cerr << "Duplicate ," << cs << " in " << filename << " will be ignored." << std::endl; + } + } + } + } + // close file + file.close(); + + // keep file path + m_Filename = filename; + + // update time + GetLastModTime(&m_LastModTime); + + // and done + Unlock(); + ok = true; + std::cout << "Gatekeeper loaded " << m_Callsigns.size() << " lines from " << filename << std::endl; + } + else + { + std::cout << "Gatekeeper cannot find " << filename << std::endl; + } + + return ok; +} + +bool CBWSet::ReloadFromFile(void) +{ + bool ok = false; + + if ( m_Filename != nullptr ) + { + ok = LoadFromFile(m_Filename); + } + return ok; +} + +bool CBWSet::NeedReload(void) +{ + bool needReload = false; + + time_t time; + if ( GetLastModTime(&time) ) + { + needReload = time != m_LastModTime; + } + return needReload; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// compare + +bool CBWSet::IsMatched(const std::string &cs) const +{ + for ( const auto &item : m_Callsigns ) + { + auto pos = item.find('*'); + switch (pos) + { + case 0: + return true; + case std::string::npos: + if (0 == item.compare(cs)) + return true; + break; + default: + if (0 == item.compare(0, pos, cs, 0, pos)) + return true; + break; + } + } + return false; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// helpers + +char *CBWSet::TrimWhiteSpaces(char *str) +{ + char *end; + + // Trim leading space & tabs + while((*str == ' ') || (*str == '\t')) str++; + + // All spaces? + if(*str == 0) + return str; + + // Trim trailing space, tab or lf + end = str + ::strlen(str) - 1; + while((end > str) && ((*end == ' ') || (*end == '\t') || (*end == '\r'))) end--; + + // Write new null terminator + *(end+1) = 0; + + return str; +} + +bool CBWSet::GetLastModTime(time_t *time) +{ + bool ok = false; + + if ( m_Filename != nullptr ) + { + struct stat fileStat; + if( ::stat(m_Filename, &fileStat) != -1 ) + { + *time = fileStat.st_mtime; + ok = true; + } + } + return ok; +} + +char *CBWSet::ToUpper(char *str) +{ + constexpr auto diff = 'a' - 'A'; + for (char *p=str; *p; p++) + { + if (*p >= 'a' && *p <= 'z') + *p -= diff; + } + return str; +} diff --git a/bwset.h b/bwset.h new file mode 100644 index 0000000..3c10f7c --- /dev/null +++ b/bwset.h @@ -0,0 +1,61 @@ +// +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + +#include + +#include "main.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CBWSet +{ +public: + // constructor + CBWSet(); + + // locks + void Lock(void) const { m_Mutex.lock(); } + void Unlock(void) const { m_Mutex.unlock(); } + + // file io + bool LoadFromFile(const char *); + bool ReloadFromFile(void); + bool NeedReload(void); + + // pass-thru + bool empty() const { return m_Callsigns.empty(); } + + // compare + bool IsMatched(const std::string &) const; + +protected: + bool GetLastModTime(time_t *); + char *TrimWhiteSpaces(char *); + char *ToUpper(char *str); + + // data + mutable std::mutex m_Mutex; + const char *m_Filename; + time_t m_LastModTime; + std::unordered_set m_Callsigns; +}; diff --git a/callsign.cpp b/callsign.cpp new file mode 100644 index 0000000..4734cff --- /dev/null +++ b/callsign.cpp @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2020 by Thomas A. Early N7TAE + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include + +#include "callsign.h" + +#define M17CHARACTERS " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-/." + +CCallsign::CCallsign() +{ + memset(cs, 0, sizeof(cs)); + coded = 0; +} + +CCallsign::CCallsign(const std::string &callsign) +{ + CSIn(callsign); +} + +CCallsign::CCallsign(const uint8_t *in) +{ + CodeIn(in); +} + +void CCallsign::CSIn(const std::string &callsign) +{ + const std::string m17_alphabet(M17CHARACTERS); + memset(cs, 0, sizeof(cs)); + memcpy(cs, callsign.c_str(), (callsign.size()<10) ? callsign.size() : 9); // no more than 9 chars + coded = 0; + for( int i=int(callsign.size()-1); i>=0; i-- ) { + auto pos = m17_alphabet.find(cs[i]); + if (pos == std::string::npos) { + pos = 0; + } + cs[i] = m17_alphabet[pos]; // replace with valid character + coded *= 40; + coded += pos; + } + + // strip trailing spaces (just to be nice!) + auto len = strlen(cs); + while (len && (' ' == cs[len-1])) + cs[--len] = 0; + +} + +const std::string CCallsign::GetCS(unsigned len) const +{ + if (len > 9) + len = 9; + std::string rval(cs); + if (len) + rval.resize(len, ' '); + return rval; +} + +void CCallsign::CodeIn(const uint8_t *in) +{ + const std::string m17_alphabet(M17CHARACTERS); + memset(cs, 0, 10); + coded = in[0]; + for (int i=1; i<6; i++) + coded = (coded << 8) | in[i]; + if (coded > 0xee6b27ffffffu) { + std::cerr << "Callsign code is too large, 0x" << std::hex << coded << std::dec << std::endl; + return; + } + auto c = coded; + int i = 0; + while (c) { + cs[i++] = m17_alphabet[c % 40]; + c /= 40; + } +} + +void CCallsign::CodeOut(uint8_t *out) const +{ + memset(out, 0, 6); + auto c = coded; + auto pout = out+5; + while (c) + { + *pout-- = c % 0x100u; + c /= 0x100u; + } +} + +char CCallsign::GetModule() const +{ + if (cs[8]) + return cs[8]; + else + return ' '; +} + +bool CCallsign::HasSameCallsign(const CCallsign &call) const +{ + return (this->GetCS(8) == call.GetCS(8)); +} + +bool CCallsign::operator==(const CCallsign &rhs) const +{ + return coded == rhs.coded; +} + +bool CCallsign::operator!=(const CCallsign &rhs) const +{ + return coded != rhs.coded; +} + +bool CCallsign::HasSameCallsignWithWildcard(const CCallsign &callsign) const +{ + bool same = true; + bool done = false; + + for ( unsigned i = 0; (i < sizeof(cs)) && same && !done; i++ ) + { + if ( !(done = ((cs[i] == '*') || (callsign.cs[i] == '*'))) ) + { + same &= (cs[i] == callsign.cs[i]); + } + } + return same; +} + +void CCallsign::SetModule(char m) +{ + std::string call(cs); + call.resize(8, ' '); + call.append(1, m); + CSIn(call); +} + +std::ostream &operator<<(std::ostream &stream, const CCallsign &call) +{ + stream << call.cs; + return stream; +} diff --git a/callsign.h b/callsign.h new file mode 100644 index 0000000..27640fd --- /dev/null +++ b/callsign.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2020 by Thomas A. Early N7TAE + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#pragma once + +#include +#include +#include + +class CCallsign +{ +public: + CCallsign(); + CCallsign(const std::string &cs); + CCallsign(const uint8_t *code); + void CSIn(const std::string &cs); + void CodeIn(const uint8_t *code); + const std::string GetCS(unsigned len = 0) const; + void CodeOut(uint8_t *out) const; + size_t Hash() const { return coded; } + bool operator==(const CCallsign &rhs) const; + bool operator!=(const CCallsign &rhs) const; + char GetModule(void) const; + bool HasSameCallsignWithWildcard(const CCallsign &callsign) const; + void SetModule(char m); + friend std::ostream &operator<<(std::ostream &stream, const CCallsign &call); + bool HasSameCallsign(const CCallsign &call) const; +private: + uint64_t coded; + char cs[10]; +}; diff --git a/client.cpp b/client.cpp new file mode 100644 index 0000000..b5d4e03 --- /dev/null +++ b/client.cpp @@ -0,0 +1,108 @@ +// +// cclient.cpp +// m17ref +// +// Created by Jean-Luc Deltombe (LX3JL) on 31/10/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include + +#include "client.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructors + +CClient::CClient() +{ + m_ReflectorModule = ' '; + m_ModuleMastered = ' '; + m_LastKeepaliveTime.Now(); + m_ConnectTime = std::time(nullptr); + m_LastHeardTime = std::time(nullptr); +} + +CClient::CClient(const CCallsign &callsign, const CIp &ip, char reflectorModule) +{ + m_ReflectorModule = reflectorModule; + m_Callsign = callsign; + m_Ip = ip; + m_ModuleMastered = ' '; + m_LastKeepaliveTime.Now(); + m_ConnectTime = std::time(nullptr); + m_LastHeardTime = std::time(nullptr); +} + +CClient::CClient(const CClient &client) +{ + m_Callsign = client.m_Callsign; + m_Ip = client.m_Ip; + m_ReflectorModule = client.m_ReflectorModule; + m_ModuleMastered = client.m_ModuleMastered; + m_LastKeepaliveTime = client.m_LastKeepaliveTime; + m_ConnectTime = client.m_ConnectTime; + m_LastHeardTime = client.m_LastHeardTime; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// status + +void CClient::Alive(void) +{ + m_LastKeepaliveTime.Now(); +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// operators + +bool CClient::operator ==(const CClient &client) const +{ + return ((client.m_Callsign == m_Callsign) && + (client.m_Ip == m_Ip) && +#ifdef MCLIENTS + (client.m_Ip.GetPort() == m_Ip.GetPort()) && +#endif + (client.m_ReflectorModule == m_ReflectorModule)); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// reporting + +void CClient::WriteXml(std::ofstream &xmlFile) +{ + xmlFile << "" << std::endl; + xmlFile << "\t" << m_Callsign << "" << std::endl; + xmlFile << "\t" << m_Ip.GetAddress() << "" << std::endl; + xmlFile << "\t" << m_ReflectorModule << "" << std::endl; + xmlFile << "\t" << GetProtocolName() << "" << std::endl; + char mbstr[100]; + if (std::strftime(mbstr, sizeof(mbstr), "%A %c", std::localtime(&m_ConnectTime))) + { + xmlFile << "\t" << mbstr << "" << std::endl; + } + if (std::strftime(mbstr, sizeof(mbstr), "%A %c", std::localtime(&m_LastHeardTime))) + { + xmlFile << "\t" << mbstr << "" << std::endl; + } + xmlFile << "" << std::endl; +} diff --git a/client.h b/client.h new file mode 100644 index 0000000..094bd52 --- /dev/null +++ b/client.h @@ -0,0 +1,91 @@ +// +// Created by Jean-Luc Deltombe (LX3JL) on 31/10/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + +#include "timepoint.h" +#include "ip.h" +#include "callsign.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CClient +{ +public: + // constructors + CClient(); + CClient(const CCallsign &, const CIp &, char); + CClient(const CClient &); + + // destructor + virtual ~CClient() {}; + + // operators + bool operator ==(const CClient &) const; + + // get + const CCallsign &GetCallsign(void) const { return m_Callsign; } + const CIp &GetIp(void) const { return m_Ip; } + char GetModule(void) const { return m_Callsign.GetModule(); } + bool HasReflectorModule(void) const { return m_ReflectorModule != ' '; } + char GetReflectorModule(void) const { return m_ReflectorModule; } + + // set + void SetModule(char c) { m_Callsign.SetModule(c); } + void SetReflectorModule(char c) { m_ReflectorModule = c; } + + // identity + virtual const char *GetProtocolName(void) const { return "none"; } + virtual bool IsNode(void) const { return false; } + virtual bool IsPeer(void) const { return false; } + virtual bool IsDextraDongle(void) const { return false; } + virtual void SetDextraDongle(void) { } + + // status + virtual void Alive(void); + virtual bool IsAlive(void) const { return false; } + virtual bool IsAMaster(void) const { return (m_ModuleMastered != ' '); } + virtual void SetMasterOfModule(char c) { m_ModuleMastered = c; } + virtual void NotAMaster(void) { m_ModuleMastered = ' '; } + virtual void Heard(void) { m_LastHeardTime = std::time(nullptr); } + + // reporting + virtual void WriteXml(std::ofstream &); + +protected: + // data + CCallsign m_Callsign; + CIp m_Ip; + + // linked to + char m_ReflectorModule; + + // status + char m_ModuleMastered; + CTimePoint m_LastKeepaliveTime; + std::time_t m_ConnectTime; + std::time_t m_LastHeardTime; +}; diff --git a/clients.cpp b/clients.cpp new file mode 100644 index 0000000..d7edfc0 --- /dev/null +++ b/clients.cpp @@ -0,0 +1,165 @@ +// +// cclients.cpp +// m17ref +// +// Created by Jean-Luc Deltombe (LX3JL) on 31/10/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "reflector.h" +#include "clients.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + + +CClients::CClients() +{ +} + +//////////////////////////////////////////////////////////////////////////////////////// +// destructors + +CClients::~CClients() +{ + m_Mutex.lock(); + m_Clients.clear(); + m_Mutex.unlock(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// manage Clients + +void CClients::AddClient(std::shared_ptr client) +{ + // first check if client already exists + for ( auto it=begin(); it!=end(); it++ ) + { + if (*client == *(*it)) + // if found, just do nothing + // so *client keep pointing on a valid object + // on function return + { + // delete new one + return; + } + } + + // and append + m_Clients.push_back(client); + std::cout << "New client " << client->GetCallsign() << " at " << client->GetIp() << " added with protocol " << client->GetProtocolName(); + if ( client->GetReflectorModule() != ' ' ) + { + std::cout << " on module " << client->GetReflectorModule(); + } + std::cout << std::endl; + // notify + g_Reflector.OnClientsChanged(); +} + +void CClients::RemoveClient(std::shared_ptr client) +{ + // look for the client + bool found = false; + for ( auto it=begin(); it!=end(); it++ ) + { + // compare objetc pointers + if ( *it == client ) + { + // found it ! + if ( !(*it)->IsAMaster() ) + { + // remove it + std::cout << "Client " << (*it)->GetCallsign() << " at " << (*it)->GetIp() << " removed with protocol " << (*it)->GetProtocolName(); + if ( (*it)->GetReflectorModule() != ' ' ) + { + std::cout << " on module " << (*it)->GetReflectorModule(); + } + std::cout << std::endl; + m_Clients.erase(it); + // notify + g_Reflector.OnClientsChanged(); + break; + } + } + } +} + +bool CClients::IsClient(std::shared_ptr client) const +{ + for ( auto it=cbegin(); it!=cend(); it++ ) + { + if (*it == client) + return true; + } + return false; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// find Clients + +std::shared_ptr CClients::FindClient(const CIp &Ip) +{ + // find client + for ( auto it=begin(); it!=end(); it++ ) + { +#ifdef MCLIENTS + if ( ((*it)->GetIp() == Ip) && ((*it)->GetIp().GetPort() == Ip.GetPort()) ) +#else + if ((*it)->GetIp() == Ip) +#endif + { + return *it; + } + } + + // done + return nullptr; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// iterate on clients + +std::shared_ptr CClients::FindNextClient(std::list>::iterator &it) +{ + if ( it != end() ) + return *it++; + + return nullptr; +} + +std::shared_ptr CClients::FindNextClient(const CCallsign &Callsign, const CIp &Ip, std::list>::iterator &it) +{ + while ( it != end() ) + { +#ifdef MCLIENTS + if ( ((*it)->GetIp() == Ip) && ((*it)->GetIp().GetPort() == Ip.GetPort()) && (*it)->GetCallsign().HasSameCallsign(Callsign) ) +#else + if ( ((*it)->GetIp() == Ip) && (*it)->GetCallsign().HasSameCallsign(Callsign) ) +#endif + { + return *it++; + } + it++; + } + return nullptr; +} diff --git a/clients.h b/clients.h new file mode 100644 index 0000000..a3c7731 --- /dev/null +++ b/clients.h @@ -0,0 +1,74 @@ +// +// Created by Jean-Luc Deltombe (LX3JL) on 31/10/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + +#include +#include + +#include "client.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// define + + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CClients +{ +public: + // constructors + CClients(); + + // destructors + virtual ~CClients(); + + // locks + void Lock(void) { m_Mutex.lock(); } + void Unlock(void) { m_Mutex.unlock(); } + + // manage Clients + int GetSize(void) const { return (int)m_Clients.size(); } + void AddClient(std::shared_ptr); + void RemoveClient(std::shared_ptr); + bool IsClient(std::shared_ptr) const; + + // pass-thru + std::list>::iterator begin() { return m_Clients.begin(); } + std::list>::iterator end() { return m_Clients.end(); } + std::list>::const_iterator cbegin() const { return m_Clients.cbegin(); } + std::list>::const_iterator cend() const { return m_Clients.cend(); } + + // find clients + std::shared_ptr FindClient(const CIp &); + + // iterate on clients + std::shared_ptr FindNextClient(std::list>::iterator &); + std::shared_ptr FindNextClient(const CCallsign &, const CIp &, std::list>::iterator &); + +protected: + // data + std::mutex m_Mutex; + std::list> m_Clients; +}; diff --git a/config/mrefd.blacklist b/config/mrefd.blacklist new file mode 100644 index 0000000..8c2c8b9 --- /dev/null +++ b/config/mrefd.blacklist @@ -0,0 +1,14 @@ +############################################################################## +# MREFD blacklist file +# +# one line per entry +# each entry is explicitely denied access (blacklisted) +# you can use * as last wildcard character +# example: +# * -> deny access to eveybody (that would be stupid!) +# LX* -> deny access to all callsign starting with LX +# everything after the * is ignored +# LX3JL -> deny access to LX3JL exactly +# but you would generally want to use LX3JL* instead +# +############################################################################# diff --git a/config/mrefd.interlink b/config/mrefd.interlink new file mode 100644 index 0000000..ee4e39a --- /dev/null +++ b/config/mrefd.interlink @@ -0,0 +1,20 @@ +############################################################################ +# M17 interlink file +# +# One line per entry, but any reflector can only have one line. +# Each entry specifies a remote M17 Reflector to peer with format: +# +# example: +# M17-ABC 44.123.213.112 ACD +# M17-XYZ 2600:400:bc03::100 ACD +# +# In the above example, this reflector would link modules A, C and D +# with both M17-ABC and M17-XYZ. This example implies both this +# reflector and M17-XYZ support IPv6. +# +# These remote reflectors must list this reflector and modules +# exactly in their interlink file for the link to be established. +# +# Every reflector in an interlink group must link to every other +# reflector in the group or clients in a group may not hear everybody. +############################################################################# diff --git a/config/mrefd.whitelist b/config/mrefd.whitelist new file mode 100644 index 0000000..405d12e --- /dev/null +++ b/config/mrefd.whitelist @@ -0,0 +1,14 @@ +############################################################################## +# MREFD whitelist file +# +# one line per entry +# each entry is explicitely authorised (whitelisted) +# you can use * as last wildcard character +# example: +# LX* -> authorize all callsign starting with LX'= +# anthing after the * will be ignored +# LX3JL -> authorize LX3JL exactly +# +# no whitelist entry means everyone is allowed +# +############################################################################# diff --git a/configure.h b/configure.h new file mode 100644 index 0000000..6562411 --- /dev/null +++ b/configure.h @@ -0,0 +1,5 @@ +// Created on Tue 24 Jan 2023 07:18:41 AM -03 +#define CALLSIGN "M17-YSF" +#define NB_OF_MODULES 26 +#define LISTEN_IPV4 "0.0.0.0" +#define MCLIENTS diff --git a/configure.mk b/configure.mk new file mode 100644 index 0000000..c17f878 --- /dev/null +++ b/configure.mk @@ -0,0 +1,2 @@ +# Created on Tue 24 Jan 2023 07:18:41 AM -03 +debug = false diff --git a/crc.cpp b/crc.cpp new file mode 100644 index 0000000..c9f7645 --- /dev/null +++ b/crc.cpp @@ -0,0 +1,76 @@ +/* + * Library: libcrc + * Git: https://github.com/lammertb/libcrc + * Author: Lammert Bies + * + * This file is licensed under the MIT License as stated below + * + * Copyright (c) 1999-2016 Lammert Bies + * Copyright (c) 2020 Thomas A. Early, N7TAE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * Description + * ----------- + * The source file contains routines which calculate the CCITT CRC + * values for an incomming byte string. + */ + +#include +#include +#include +#include + +#include "crc.h" + +#define CRC_POLY_16 0x5935u +#define CRC_START_16 0xFFFFu + +CCRC::CCRC() +{ + for (uint16_t i=0; i<256; i++) + { + uint16_t crc = 0; + uint16_t c = i << 8; + + for (uint16_t j=0; j<8; j++) + { + if ( (crc ^ c) & 0x8000 ) + crc = ( crc << 1 ) ^ CRC_POLY_16; + else + crc = crc << 1; + + c = c << 1; + } + crc_tab16[i] = crc; + } +} + +uint16_t CCRC::CalcCRC( const uint8_t *input_str, size_t num_bytes ) const +{ + uint16_t crc = CRC_START_16; + + if ( input_str ) + for (size_t a=0; a> 8) ^ uint16_t(input_str[a])) & 0x00FF ]; + } + + return crc; +} diff --git a/crc.h b/crc.h new file mode 100644 index 0000000..f9cb321 --- /dev/null +++ b/crc.h @@ -0,0 +1,48 @@ +/* + * Library: libcrc + * Git: https://github.com/lammertb/libcrc + * Author: Lammert Bies + * + * This file is licensed under the MIT License as stated below + * + * Copyright (c) 1999-2016 Lammert Bies + * Copyright (c) 2020 Thomas A. Early, N7TAE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * Description + * ----------- + * The source file contains routines which calculate the CCITT CRC + * values for an incomming byte string. + */ + +#pragma once + +#include +#include + +class CCRC +{ +public: + CCRC(); + uint16_t CalcCRC(const uint8_t *buf, size_t len) const; + +private: + uint16_t crc_tab16[256]; +}; diff --git a/gatekeeper.cpp b/gatekeeper.cpp new file mode 100644 index 0000000..8bebc13 --- /dev/null +++ b/gatekeeper.cpp @@ -0,0 +1,185 @@ +// +// cgatekeeper.cpp +// M17Refd +// +// Created by Jean-Luc Deltombe (LX3JL) on 07/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of M17Refd. +// +// M17Refd 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. +// +// M17Refd 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "timepoint.h" +#include "reflector.h" +#include "gatekeeper.h" + +//////////////////////////////////////////////////////////////////////////////////////// + +CGateKeeper g_GateKeeper; + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CGateKeeper::CGateKeeper() +{ + keep_running = true; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// destructor + +CGateKeeper::~CGateKeeper() +{ + Close(); +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// init & clode + +bool CGateKeeper::Init(void) +{ + + // load lists from files + m_NodeWhiteSet.LoadFromFile(WHITELIST_PATH); + m_NodeBlackSet.LoadFromFile(BLACKLIST_PATH); + m_PeerMap.LoadFromFile(INTERLINKLIST_PATH); + + // reset run flag + keep_running = true; + + // start thread; + m_Future = std::async(std::launch::async, &CGateKeeper::Thread, this); + + return true; +} + +void CGateKeeper::Close(void) +{ + // kill threads + keep_running = false; + if ( m_Future.valid() ) + { + m_Future.get(); + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// authorizations + +bool CGateKeeper::MayLink(const CCallsign &callsign, const CIp &ip, char *modules) const +{ + bool ok = false; + if (callsign.GetCS(4).compare("M17-")) + { + auto clients = g_Reflector.GetClients(); + if (clients->FindClient(ip)) + ok = false; + else + ok = IsNodeListedOk(callsign); + g_Reflector.ReleaseClients(); + } + else + { + ok = IsPeerListedOk(callsign, ip, modules); + } + + if ( !ok ) + { + std::cout << "Gatekeeper blocking linking of " << callsign << " @ " << ip << std::endl; + } + + // done + return ok; +} + +bool CGateKeeper::MayTransmit(const CCallsign &callsign, const CIp &ip) const +{ + return IsNodeListedOk(callsign); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// thread + +void CGateKeeper::Thread() +{ + while (keep_running) + { + // Wait 30 seconds + for (int i=0; i<15 && keep_running; i++) + CTimePoint::TaskSleepFor(2000); + + // have lists files changed ? + if ( m_NodeWhiteSet.NeedReload() ) + { + m_NodeWhiteSet.ReloadFromFile(); + } + if ( m_NodeBlackSet.NeedReload() ) + { + m_NodeBlackSet.ReloadFromFile(); + } + if ( m_PeerMap.NeedReload() ) + { + m_PeerMap.ReloadFromFile(); + } + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// operation helpers + +bool CGateKeeper::IsNodeListedOk(const CCallsign &callsign) const +{ + bool ok = true; + + // next, check callsign + // first check if callsign is in white list + // note if white list is empty, everybody is authorized + m_NodeWhiteSet.Lock(); + if ( ! m_NodeWhiteSet.empty() ) + { + ok = m_NodeWhiteSet.IsMatched(callsign.GetCS()); + } + m_NodeWhiteSet.Unlock(); + + // then check if not blacklisted + m_NodeBlackSet.Lock(); + ok = ok && !m_NodeBlackSet.IsMatched(callsign.GetCS()); + m_NodeBlackSet.Unlock(); + + // done + return ok; + +} + +bool CGateKeeper::IsPeerListedOk(const CCallsign &callsign, const CIp &ip, const char *modules) const +{ + bool ok = false; + + // look for an exact match in the list + m_PeerMap.Lock(); + if ( ! m_PeerMap.empty() ) + { + // find an exact match + ok = m_PeerMap.IsCallsignListed(callsign, ip, modules); + } + m_PeerMap.Unlock(); + + // done + return ok; +} diff --git a/gatekeeper.h b/gatekeeper.h new file mode 100644 index 0000000..883c539 --- /dev/null +++ b/gatekeeper.h @@ -0,0 +1,74 @@ +// +// cgatekeeper.h +// M17Refd +// +// Created by Jean-Luc Deltombe (LX3JL) on 07/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of M17Refd. +// +// M17Refd 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. +// +// M17Refd 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + +#include "main.h" +#include "callsign.h" +#include "ip.h" +#include "bwset.h" +#include "peermap.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CGateKeeper +{ +public: + // constructor + CGateKeeper(); + + // destructor + ~CGateKeeper(); + + // init & clode + bool Init(void); + void Close(void); + + // authorizations + bool MayLink(const CCallsign &, const CIp &, char * = nullptr) const; + bool MayTransmit(const CCallsign &, const CIp &) const; + + // peer list handeling + CPeerMap *GetPeerMap(void) { m_PeerMap.Lock(); return &m_PeerMap; } + void ReleasePeerMap(void) { m_PeerMap.Unlock(); } + +protected: + // thread + void Thread(); + + // operation helpers + bool IsNodeListedOk(const CCallsign &) const; + bool IsPeerListedOk(const CCallsign &, const CIp &, const char *) const; + +protected: + // data + CBWSet m_NodeWhiteSet; + CBWSet m_NodeBlackSet; + CPeerMap m_PeerMap; + + // thread + std::atomic keep_running; + std::future m_Future; +}; diff --git a/ip.cpp b/ip.cpp new file mode 100644 index 0000000..c930c79 --- /dev/null +++ b/ip.cpp @@ -0,0 +1,296 @@ +/* +* Copyright (C) 2020 by Thomas Early N7TAE +* +* 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 2 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, write to the Free Software +* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +*/ + +#include +#include +#include +#include + +#include "ip.h" + +CIp::CIp() : is_set(false) +{ + Clear(); +} + +CIp::CIp(const char *address, int family, int type, uint16_t port) : is_set(true) +{ + Clear(); + if (0 == strncasecmp(address, "none", 4)) + { + is_set = false; + return; + } + struct addrinfo hints, *result; + bzero(&hints, sizeof(struct addrinfo)); + hints.ai_family = family; + hints.ai_socktype = type; + if (0 == getaddrinfo(address, (port ? std::to_string(port).c_str() : nullptr), &hints, &result)) + { + memcpy(&addr, result->ai_addr, result->ai_addrlen); + addr.ss_family = result->ai_family; + freeaddrinfo(result); + } + SetPort(port); +} +CIp::CIp(const int family, const uint16_t port, const char *address) : is_set(true) +{ + Initialize(family, port, address); +} + +void CIp::Initialize(const int family, const uint16_t port, const char *address) +{ + Clear(); + if (0 == strncasecmp(address, "none", 4)) + { + is_set = false; + return; + } + is_set = true; + addr.ss_family = family; + if (AF_INET == family) + { + auto addr4 = (struct sockaddr_in *)&addr; + addr4->sin_port = htons(port); + if (address) + { + if (0 == strncasecmp(address, "loc", 3)) + inet_pton(AF_INET, "127.0.0.1", &(addr4->sin_addr)); + else if (0 == strncasecmp(address, "any", 3)) + inet_pton(AF_INET, "0.0.0.0", &(addr4->sin_addr)); + else + { + if (1 > inet_pton(AF_INET, address, &(addr4->sin_addr))) + { + std::cerr << "Address Initialization Error: '" << address << "' is not a valdid IPV4 address!" << std::endl; + is_set = false; + } + } + } + } + else if (AF_INET6 == family) + { + auto addr6 = (struct sockaddr_in6 *)&addr; + addr6->sin6_port = htons(port); + if (address) + { + if (0 == strncasecmp(address, "loc", 3)) + inet_pton(AF_INET6, "::1", &(addr6->sin6_addr)); + else if (0 == strncasecmp(address, "any", 3)) + inet_pton(AF_INET6, "::", &(addr6->sin6_addr)); + else + { + if (1 > inet_pton(AF_INET6, address, &(addr6->sin6_addr))) + { + std::cerr << "Address Initialization Error: '" << address << "' is not a valid IPV6 address!" << std::endl; + is_set = false; + } + } + } + } + else + { + std::cerr << "Error: Wrong address family type:" << family << " for [" << (address ? address : "NULL") << "]:" << port << std::endl; + is_set = false; + } +} + +bool CIp::operator==(const CIp &rhs) const // doesn't compare ports, only addresses and families +{ + if (addr.ss_family != rhs.addr.ss_family) + return false; + if (AF_INET == addr.ss_family) + { + auto l = (struct sockaddr_in *)&addr; + auto r = (struct sockaddr_in *)&rhs.addr; + return (l->sin_addr.s_addr == r->sin_addr.s_addr); + } + else if (AF_INET6 == addr.ss_family) + { + auto l = (struct sockaddr_in6 *)&addr; + auto r = (struct sockaddr_in6 *)&rhs.addr; + return (0 == memcmp(&(l->sin6_addr), &(r->sin6_addr), sizeof(struct in6_addr))); + } + return false; +} + +bool CIp::operator!=(const CIp &rhs) const // doesn't compare ports, only addresses and families +{ + if (addr.ss_family != rhs.addr.ss_family) + return true; + if (AF_INET == addr.ss_family) + { + auto l = (struct sockaddr_in *)&addr; + auto r = (struct sockaddr_in *)&rhs.addr; + return (l->sin_addr.s_addr != r->sin_addr.s_addr); + } + else if (AF_INET6 == addr.ss_family) + { + auto l = (struct sockaddr_in6 *)&addr; + auto r = (struct sockaddr_in6 *)&rhs.addr; + return (0 != memcmp(&(l->sin6_addr), &(r->sin6_addr), sizeof(struct in6_addr))); + } + return true; +} + +bool CIp::AddressIsZero() const +{ + if (AF_INET == addr.ss_family) + { + auto addr4 = (struct sockaddr_in *)&addr; + return (addr4->sin_addr.s_addr == 0U); + } + else + { + auto addr6 = (struct sockaddr_in6 *)&addr; + for (unsigned int i=0; i<16; i++) + { + if (addr6->sin6_addr.s6_addr[i]) + return false; + } + return true; + } +} + +void CIp::ClearAddress() +{ + if (AF_INET == addr.ss_family) + { + auto addr4 = (struct sockaddr_in *)&addr; + addr4->sin_addr.s_addr = 0U; + strcpy(straddr, "0.0.0.0"); + } + else + { + auto addr6 = (struct sockaddr_in6 *)&addr; + memset(&(addr6->sin6_addr.s6_addr), 0, 16); + strcpy(straddr, "::"); + } +} + +const char *CIp::GetAddress() const +{ + if (straddr[0]) + return straddr; + + if (AF_INET == addr.ss_family) + { + auto addr4 = (struct sockaddr_in *)&addr; + inet_ntop(AF_INET, &(addr4->sin_addr), straddr, INET6_ADDRSTRLEN); + } + else if (AF_INET6 == addr.ss_family) + { + auto addr6 = (struct sockaddr_in6 *)&addr; + inet_ntop(AF_INET6, &(addr6->sin6_addr), straddr, INET6_ADDRSTRLEN); + } + else + { + std::cerr << "CIp::GetAddress: unknown socket family=" << addr.ss_family << std::endl; + } + return straddr; +} + +std::ostream &operator<<(std::ostream &stream, const CIp &Ip) +{ + const char *sz = Ip; + if (AF_INET6 == Ip.GetFamily()) + stream << "[" << sz << "]"; + else + stream << sz; + const uint16_t port = Ip.GetPort(); + if (port) + stream << ":" << port; + return stream; +} + +uint32_t CIp::GetAddr() const +{ + if (AF_INET6 == addr.ss_family) + { + auto addr6 = (struct sockaddr_in6 *)&addr; + // hash the results + auto *a = (const uint32_t *)&(addr6->sin6_addr.s6_addr); + return a[0] ^ a[1] ^ a[2] ^ a[3]; + } + else + { + auto addr4 = (struct sockaddr_in *)&addr; + return addr4->sin_addr.s_addr; + } +} + +int CIp::GetFamily() const +{ + return addr.ss_family; +} + +uint16_t CIp::GetPort() const +{ + if (AF_INET == addr.ss_family) + { + auto addr4 = (struct sockaddr_in *)&addr; + return ntohs(addr4->sin_port); + } + else if (AF_INET6 == addr.ss_family) + { + auto addr6 = (struct sockaddr_in6 *)&addr; + return ntohs(addr6->sin6_port); + } + else + return 0; +} + +void CIp::SetPort(const uint16_t newport) +{ + if (AF_INET == addr.ss_family) + { + auto addr4 = (struct sockaddr_in *)&addr; + addr4->sin_port = htons(newport); + } + else if (AF_INET6 == addr.ss_family) + { + auto addr6 = (struct sockaddr_in6 *)&addr; + addr6->sin6_port = htons(newport); + } +} + +struct sockaddr *CIp::GetPointer() +{ + memset(straddr, 0, INET6_ADDRSTRLEN); // things might change + return (struct sockaddr *)&addr; +} + +const struct sockaddr *CIp::GetCPointer() const +{ + return (const struct sockaddr *)&addr; +} + +size_t CIp::GetSize() const +{ + if (AF_INET == addr.ss_family) + return sizeof(struct sockaddr_in); + else + return sizeof(struct sockaddr_in6); +} + +void CIp::Clear() +{ + memset(&addr, 0, sizeof(struct sockaddr_storage)); + memset(straddr, 0, INET6_ADDRSTRLEN); + is_set = false; +} diff --git a/ip.h b/ip.h new file mode 100644 index 0000000..ab21ec3 --- /dev/null +++ b/ip.h @@ -0,0 +1,72 @@ +#pragma once + +/* + * Copyright (C) 2020 by Thomas Early N7TAE + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +class CIp +{ +public: + // constructors + CIp(); + CIp(const char *address, int family = AF_UNSPEC, int type = SOCK_DGRAM, uint16_t port = 0U); + CIp(const int family, const uint16_t port = 0U, const char *address = nullptr); + + // initializer for empty constructor + void Initialize(const int family, const uint16_t port = 0U, const char *address = nullptr); + + // comparison operators + bool operator==(const CIp &rhs) const; + bool operator!=(const CIp &rhs) const; + + // state methods + bool IsSet() const { return is_set; } + bool AddressIsZero() const; + void ClearAddress(); + const char *GetAddress() const; + operator const char *() const { return GetAddress(); } + friend std::ostream &operator<<(std::ostream &stream, const CIp &Ip); + int GetFamily() const; + uint16_t GetPort() const; + size_t GetSize() const; + uint32_t GetAddr() const; + + // modifiers + void SetPort(const uint16_t newport); + + // for i/o + struct sockaddr *GetPointer(); + const struct sockaddr *GetCPointer() const; + + void Clear(); + +private: + struct sockaddr_storage addr; + mutable char straddr[INET6_ADDRSTRLEN]; + bool is_set; +}; diff --git a/m17client.cpp b/m17client.cpp new file mode 100644 index 0000000..307ae5e --- /dev/null +++ b/m17client.cpp @@ -0,0 +1,47 @@ +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "m17client.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructors + +CM17Client::CM17Client() +{ +} + +CM17Client::CM17Client(const CCallsign &callsign, const CIp &ip, char reflectorModule) + : CClient(callsign, ip, reflectorModule) +{ +} + +CM17Client::CM17Client(const CM17Client &client) + : CClient(client) +{ +} + +//////////////////////////////////////////////////////////////////////////////////////// +// status + +bool CM17Client::IsAlive(void) const +{ + return (m_LastKeepaliveTime.DurationSinceNow() < M17_KEEPALIVE_TIMEOUT); +} diff --git a/m17client.h b/m17client.h new file mode 100644 index 0000000..7921895 --- /dev/null +++ b/m17client.h @@ -0,0 +1,50 @@ +#pragma once + +// Copyright © 2015 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include "client.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// define + + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CM17Client : public CClient +{ +public: + // constructors + CM17Client(); + CM17Client(const CCallsign &, const CIp &, char); + CM17Client(const CM17Client &); + + // destructor + virtual ~CM17Client() {}; + + // identity + const char *GetProtocolName(void) const { return "M17"; } + bool IsNode(void) const { return true; } + + // status + bool IsAlive(void) const; +}; + +//////////////////////////////////////////////////////////////////////////////////////// diff --git a/m17peer.cpp b/m17peer.cpp new file mode 100644 index 0000000..cb22614 --- /dev/null +++ b/m17peer.cpp @@ -0,0 +1,68 @@ +// +// Created by Antony Chazapis (SV9OAN) on 25/2/2018. +// Copyright © 2016 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of mrefd. +// +// mrefd 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. +// +// mrefd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include +#include "reflector.h" +#include "m17peer.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + + +CM17Peer::CM17Peer() +{ +} + +CM17Peer::CM17Peer(const CCallsign &cs, const CIp &ip, const char *modules) : CPeer(cs, ip, modules) +{ + std::cout << "Adding M17 peer " << cs << " module(s) " << modules << std::endl; + + // and construct the M17 clients + for (auto p=modules; *p; p++) + { + // create and append to vector + m_Clients.push_back(std::make_shared(cs, ip, *p)); + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// status + +bool CM17Peer::IsAlive(void) const +{ + for ( auto it=cbegin(); it!=cend(); it++ ) + { + if (! (*it)->IsAlive()) + return false; + } + return true; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// revision helper + +int CM17Peer::GetProtocolRevision(const CVersion &version) +{ + return version.GetMajor(); +} diff --git a/m17peer.h b/m17peer.h new file mode 100644 index 0000000..9dbbd91 --- /dev/null +++ b/m17peer.h @@ -0,0 +1,51 @@ +// +// Created by Antony Chazapis (SV9OAN) on 25/2/2018. +// Copyright © 2016 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of mrefd. +// +// mrefd 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. +// +// mrefd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + +#include "peer.h" +#include "m17client.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// define + + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CM17Peer : public CPeer +{ +public: + // constructors + CM17Peer(); + CM17Peer(const CCallsign &, const CIp &, const char *); + CM17Peer(const CM17Peer &) = delete; + + // status + bool IsAlive(void) const; + + // identity + const char *GetProtocolName(void) const { return "M17"; } + + // revision helper + static int GetProtocolRevision(const CVersion &); +}; diff --git a/m17protocol.cpp b/m17protocol.cpp new file mode 100644 index 0000000..3ddd046 --- /dev/null +++ b/m17protocol.cpp @@ -0,0 +1,685 @@ +// +// Created by Jean-Luc Deltombe (LX3JL) on 01/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of mrefd. +// +// mrefd 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. +// +// mrefd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include + +#include "main.h" +#include "m17peer.h" +#include "m17client.h" +#include "m17protocol.h" +#include "reflector.h" +#include "gatekeeper.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CM17Protocol::CM17Protocol() +{ + peerRegEx = std::regex("^M17-([A-Z0-9]){3,3}(($)|( [A-Z]$))", std::regex::extended); + clientRegEx = std::regex("^[0-9]?[A-Z]{1,2}[0-9]{1,2}[A-Z]{1,4}(($)|([ ]*[A-Z]?$)|([-/\\.][A-Z0-9]+$))", std::regex::extended); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// operation + +bool CM17Protocol::Initialize(const uint16_t port, const bool has_ipv4, const bool has_ipv6) +{ + // base class + if (! CProtocol::Initialize(port, has_ipv4, has_ipv6)) + return false; + + // update time + m_LastKeepaliveTime.Now(); + m_LastPeersLinkTime.Now(); + + // done + return true; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// task + +void CM17Protocol::Task(void) +{ + uint8_t buf[UDP_BUFFER_LENMAX]; + CIp ip; + CCallsign cs; + char mod; + char mods[27]; + std::unique_ptr pack; + + // any incoming packet ? +#ifdef LISTEN_IPV6 +#ifdef LISTEN_IPV4 + auto len = ReceiveDS(buf, ip, 20); +#else + auto len = Receive6(buf, ip, 20); +#endif +#else + auto len = Receive4(buf, ip, 20); +#endif + //if (len > 0) std::cout << "Received " << len << " bytes from " << ip << std::endl; + switch (len) { + case sizeof(SM17Frame): // a packet from a client + case sizeof(SRefM17Frame): // a packet from a peer + // check that the source and dest c/s is correct, including dest module + if ( IsValidPacket(buf, (sizeof(SM17Frame) == len) ? false : true, pack) ) + { + if (g_GateKeeper.MayTransmit(pack->GetSourceCallsign(), ip)) + { + OnFirstPacketIn(pack, ip); // might open a new stream, if it's the first packet + if (pack) // the packet might have been erased + { // if it needed to open a new stream, but couldn't + OnPacketIn(pack, ip); + } + } + else if (pack->IsLastPacket()) + { + std::cout << "Blocked voice stream from " << pack->GetSourceCallsign() << " at " << ip << std::endl; + } + } + break; + case sizeof(SInterConnect): + if (IsValidInterlinkConnect(buf, cs, mods)) + { + //std::cout << "CONN packet from " << cs << " at " << ip << " to module(s) " << mods << std::endl; + + // callsign authorized? + if ( g_GateKeeper.MayLink(cs, ip, mods) ) + { + SInterConnect ackn; + // acknowledge the request + EncodeInterlinkAckPacket(ackn, mods); + Send(ackn.magic, sizeof(SInterConnect), ip); + } + else + { + // deny the request + EncodeInterlinkNackPacket(buf); + Send(buf, 10, ip); + } + + } + else if (IsVaildInterlinkAcknowledge(buf, cs, mods)) + { + //std::cout << "ACQN packet from " << cs << " at " << ip << " on module(s) " << mods << std::endl; + + // callsign authorized? + if ( g_GateKeeper.MayLink(cs, ip, mods) ) + { + // already connected ? + CPeers *peers = g_Reflector.GetPeers(); + if ( nullptr == peers->FindPeer(cs, ip) ) + { + // create the new peer + // this also create one client per module + std::shared_ptr peer = std::make_shared(cs, ip, mods); + + // append the peer to reflector peer list + // this also add all new clients to reflector client list + peers->AddPeer(peer); + } + g_Reflector.ReleasePeers(); + } + } + break; + case 11: + if ( IsValidConnect(buf, cs, &mod) ) + { + std::cout << "Connect packet for module " << mod << " from " << cs << " at " << ip << std::endl; + + // callsign authorized? + if ( g_GateKeeper.MayLink(cs, ip) ) + { + // valid module ? + if ( g_Reflector.IsValidModule(mod) ) + { + // acknowledge a normal request from a repeater/hot-spot/mvoice + EncodeConnectAckPacket(buf); + Send(buf, 4, ip); + + // create the client and append + g_Reflector.GetClients()->AddClient(std::make_shared(cs, ip, mod)); + g_Reflector.ReleaseClients(); + } + else + { + std::cout << "Node " << cs << " connect attempt on non-existing module '" << mod << "'" << std::endl; + + // deny the request + EncodeConnectNackPacket(buf); + Send(buf, 4, ip); + } + } + else + { + // deny the request + EncodeConnectNackPacket(buf); + Send(buf, 4, ip); + } + } + break; + case 10: + if ( IsValidKeepAlive(buf, cs) ) + { + if (cs.GetCS(4).compare("M17-")) { + // find all clients with that callsign & ip and keep them alive + CClients *clients = g_Reflector.GetClients(); + auto it = clients->begin(); + std::shared_ptrclient = nullptr; + while (nullptr != (client = clients->FindNextClient(cs, ip, it))) + { + client->Alive(); + } + g_Reflector.ReleaseClients(); + } + else + { + // find peer + CPeers *peers = g_Reflector.GetPeers(); + std::shared_ptrpeer = peers->FindPeer(ip); + if ( peer ) + { + // keep it alive + peer->Alive(); + } + g_Reflector.ReleasePeers(); + } + } + else if ( IsValidDisconnect(buf, cs) ) + { + std::cout << "Disconnect packet from " << cs << " at " << ip << std::endl; + if (cs.GetCS(4).compare("M17-")) { + // find the regular client & remove it + CClients *clients = g_Reflector.GetClients(); + std::shared_ptrclient = clients->FindClient(ip); + if ( client != nullptr ) + { + // ack disconnect packet + EncodeDisconnectedPacket(buf); + Send(buf, 4, ip); + // and remove it + clients->RemoveClient(client); + } + g_Reflector.ReleaseClients(); + } + else + { + // find the peer and remove it + CPeers *peers = g_Reflector.GetPeers(); + std::shared_ptrpeer = peers->FindPeer(ip); + if ( peer ) + { + // remove it from reflector peer list + // this also remove all peer's clients from reflector client list + // and delete them + peers->RemovePeer(peer); + } + g_Reflector.ReleasePeers(); + } + } + else if ( IsValidNAcknowledge(buf, cs)) + { + std::cout << "NACK packet received from " << cs << " at " << ip << std::endl; + } + break; + default: + break; + } + + // handle end of streaming timeout + CheckStreamsTimeout(); + + // handle queue from reflector + HandleQueue(); + + // keep alive + if ( m_LastKeepaliveTime.DurationSinceNow() > M17_KEEPALIVE_PERIOD ) + { + // handle keep alives + HandleKeepalives(); + + // update time + m_LastKeepaliveTime.Now(); + } + + // peer connections + if ( m_LastPeersLinkTime.DurationSinceNow() > M17_RECONNECT_PERIOD ) + { + // handle remote peers connections + HandlePeerLinks(); + + // update time + m_LastPeersLinkTime.Now(); + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// queue helper + +void CM17Protocol::HandleQueue(void) +{ + m_Queue.Lock(); + while ( !m_Queue.empty() ) + { + // get the packet + auto packet = m_Queue.front(); + m_Queue.pop(); + + // push it to all our clients linked to the module and who is not streaming in + CClients *clients = g_Reflector.GetClients(); + auto it = clients->begin(); + std::shared_ptrclient = nullptr; + while (nullptr != (client = clients->FindNextClient(it))) + { + // is this client busy ? + if ( !client->IsAMaster() && (client->GetReflectorModule() == packet->GetDestModule()) ) + { + auto cs = client->GetCallsign(); + + if (cs.GetCS(4).compare("M17-")) + { + // the client is not a reflector + cs.CodeOut(packet->GetFrame().frame.lich.addr_dst); + packet->SetCRC(crc.CalcCRC(packet->GetFrame().frame.magic, sizeof(SM17Frame) - 2)); + Send(packet->GetFrame().frame.magic, sizeof(SM17Frame), client->GetIp()); + } + else if (! packet->GetRelay()) + { + // the client is a reflector and the packet hasn't yet been relayed + cs.SetModule(client->GetReflectorModule()); + cs.CodeOut(packet->GetFrame().frame.lich.addr_dst); // set the destination + packet->SetCRC(crc.CalcCRC(packet->GetFrame().frame.magic, sizeof(SM17Frame) - 2)); // recalculate the crc + packet->SetRelay(true); // make sure the destination reflector doesn't send it to other reflectors + Send(packet->GetFrame().frame.magic, sizeof(SRefM17Frame), client->GetIp()); + packet->SetRelay(false); // reset for the next client; + } + } + } + g_Reflector.ReleaseClients(); + } + m_Queue.Unlock(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// keepalive helpers + +void CM17Protocol::HandleKeepalives(void) +{ + uint8_t keepalive[10]; + EncodeKeepAlivePacket(keepalive); + + // iterate on clients + CClients *clients = g_Reflector.GetClients(); + auto it = clients->begin(); + std::shared_ptr client; + while ( nullptr != (client = clients->FindNextClient(it)) ) + { + // don't ping reflector modules, we'll do each interlinked refectors after this while loop + if (0 == client->GetCallsign().GetCS(4).compare("M17-")) + continue; + + // send keepalive + Send(keepalive, 10, client->GetIp()); + + // client busy ? + if ( client->IsAMaster() ) + { + // yes, just tickle it + client->Alive(); + } + // otherwise check if still with us + else if ( !client->IsAlive() ) + { + CPeers *peers = g_Reflector.GetPeers(); + auto peer = peers->FindPeer(client->GetCallsign(), client->GetIp()); + if ( peer && (peer->GetReflectorModules()[0] == client->GetReflectorModule()) ) + { + // no, but this is a peer client, so it will be handled below + } + else + { + // no, disconnect + uint8_t disconnect[10]; + EncodeDisconnectPacket(disconnect, client->GetReflectorModule()); + Send(disconnect, 10, client->GetIp()); + + // remove it + std::cout << "Client " << client->GetCallsign() << " keepalive timeout" << std::endl; + clients->RemoveClient(client); + } + g_Reflector.ReleasePeers(); + } + + } + g_Reflector.ReleaseClients(); + + // iterate on peers + CPeers *peers = g_Reflector.GetPeers(); + auto pit = peers->begin(); + std::shared_ptr peer; + while ( nullptr != (peer = peers->FindNextPeer(pit)) ) + { + // send keepalive + Send(keepalive, 10, peer->GetIp()); + + // client busy ? + if ( peer->IsAMaster() ) + { + // yes, just tickle it + peer->Alive(); + } + // otherwise check if still with us + else if ( !peer->IsAlive() ) + { + // no, disconnect + uint8_t disconnect[10]; + EncodeDisconnectPacket(disconnect, 0); + Send(disconnect, 10, peer->GetIp()); + + // remove it + std::cout << "Peer " << peer->GetCallsign() << " keepalive timeout" << std::endl; + peers->RemovePeer(peer); + } + } + g_Reflector.ReleasePeers(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// Peers helpers + +void CM17Protocol::HandlePeerLinks(void) +{ + uint8_t buf[10]; + // get the list of peers + CPeerMap *peermap = g_GateKeeper.GetPeerMap(); + CPeers *peers = g_Reflector.GetPeers(); + + // check if all our connected peers are still listed by gatekeeper + // if not, disconnect + auto pit = peers->begin(); + std::shared_ptrpeer = nullptr; + while ( (peer = peers->FindNextPeer(pit)) != nullptr ) + { + if ( nullptr == peermap->FindMapItem(peer->GetCallsign().GetCS()) ) + { + // send disconnect packet + EncodeDisconnectPacket(buf, 0); + Send(buf, 10, peer->GetIp()); + std::cout << "Sending disconnect packet to M17 peer " << peer->GetCallsign() << " at " << peer->GetIp() << std::endl; + // remove client + peers->RemovePeer(peer); + } + } + + // check if all ours peers listed by gatekeeper are connected + // if not, connect or reconnect + SInterConnect connect; + for ( auto it=peermap->begin(); it!=peermap->end(); it++ ) + { + if ( nullptr == peers->FindPeer((*it).second.GetCallsign()) ) + { + // send connect packet to re-initiate peer link + EncodeInterlinkConnectPacket(connect, (*it).second.GetModules()); + Send(connect.magic, sizeof(SInterConnect), (*it).second.GetIp()); + std::cout << "Sent connect packet to M17 peer " << (*it).second.GetCallsign() << " @ " << (*it).second.GetIp() << " for module(s) " << (*it).second.GetModules() << std::endl; + } + } + + g_Reflector.ReleasePeers(); + g_GateKeeper.ReleasePeerMap(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// streams helpers + +void CM17Protocol::OnFirstPacketIn(std::unique_ptr &packet, const CIp &ip) +{ + // find the stream + CPacketStream *stream = GetStream(packet->GetStreamId(), ip); + if ( stream ) + { + // stream already open + // skip packet, but tickle the stream + stream->Tickle(); + } + else + { + // find this client + std::shared_ptr client = g_Reflector.GetClients()->FindClient(ip); + if ( client ) + { + // save the source and destination module for Hearing(). + // We're going to lose packet after the OpenStream() call. + auto s = packet->GetSourceCallsign(); + auto d = packet->GetDestCallsign().GetModule(); + // try to open the stream + stream = g_Reflector.OpenStream(packet, client); + if ( nullptr == stream ) + { + packet.release(); // couldn't open the stream, so destroy the packet + } + else + { + // keep the handle + m_Streams.push_back(stream); + + // update last heard + auto from = client->GetCallsign(); + if (0 == from.GetCS(4).compare("M17-")) + from.SetModule(d); + auto ref = GetReflectorCallsign(); + ref.SetModule(d); + g_Reflector.GetUsers()->Hearing(s, from, ref); + g_Reflector.ReleaseUsers(); + } + + } + // release + g_Reflector.ReleaseClients(); + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// packet decoding helpers + +bool CM17Protocol::IsValidConnect(const uint8_t *buf, CCallsign &cs, char *mod) +{ + if (0 == memcmp(buf, "CONN", 4)) + { + cs.CodeIn(buf + 4); + if (std::regex_match(cs.GetCS(), clientRegEx)) + { + *mod = buf[10]; + if (IsLetter(*mod)) + return true; + } + } + return false; +} + +bool CM17Protocol::IsValidDisconnect(const uint8_t *buf, CCallsign &cs) +{ + if (0 == memcmp(buf, "DISC", 4)) + { + cs.CodeIn(buf + 4); + auto call = cs.GetCS(); + if (std::regex_match(call, clientRegEx) || std::regex_match(call, peerRegEx)) + { + return true; + } + } + return false; +} + +bool CM17Protocol::IsValidKeepAlive(const uint8_t *buf, CCallsign &cs) +{ + if ('P' == buf[0] && ('I' == buf[1] || 'O' == buf[1]) && 'N' == buf[2] && 'G' == buf[3]) + { + cs.CodeIn(buf + 4); + auto call = cs.GetCS(); + if (std::regex_match(call, clientRegEx) || std::regex_match(call, peerRegEx)) + { + return true; + } + } + return false; +} + +bool CM17Protocol::HasValidModule(const CCallsign &cs) const +{ + auto i = cs.GetModule() - 'A'; + if (i >= 0) + { + if (i < NB_OF_MODULES) + return true; + } + return false; +} + +bool CM17Protocol::IsValidPacket(const uint8_t *buf, bool is_internal, std::unique_ptr &packet) +{ + if (0 == memcmp(buf, "M17 ", 4)) // we tested the size before we got here + { + // create packet + packet = std::unique_ptr(new CPacket(buf, is_internal)); + // check validity of packet + auto dest = packet->GetDestCallsign(); + if (HasValidModule(dest) && dest.HasSameCallsign(GetReflectorCallsign())) + { + if (std::regex_match(packet->GetSourceCallsign().GetCS(), clientRegEx)) + { // looks like a valid source + return true; + } + else + { + std::cout << packet->GetSourceCallsign().GetCS() << " Source C/S FAILED RegEx test" << std::endl; + } + } + else + { + std::cout << "Destination " << dest << " is invalid" << std::endl; + } + } + return false; +} + +bool CM17Protocol::IsValidInterlinkConnect(const uint8_t *buf, CCallsign &cs, char *mods) +{ + if (memcmp(buf, "CONN", 4)) + return false; + + cs.CodeIn(buf + 4); + if (cs.GetCS(4).compare("M17-")) + { + std::cout << "Link request from '" << cs << "' denied" << std::endl; + return false; + } + memcpy(mods, buf+10, 27); + for (unsigned i=0; imagic, "ACKN", 4)) + { + cs.CodeIn(p->fromcs); + memcpy(mods, p->mods, 27); + return (0 == mods[26]); + } + return false; +} + +bool CM17Protocol::IsValidNAcknowledge(const uint8_t *buf, CCallsign &cs) +{ + if (0 == memcmp(buf, "NACK", 4)) + { + cs.CodeIn(buf + 4); + return true; + } + return false; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// packet encoding helpers + +void CM17Protocol::EncodeKeepAlivePacket(uint8_t *buf) +{ + memcpy(buf, "PING", 4); + GetReflectorCallsign().CodeOut(buf + 4); +} + +void CM17Protocol::EncodeInterlinkConnectPacket(SInterConnect &conn, const std::string &mods) +{ + memset(conn.magic, 0, sizeof(SInterConnect)); + memcpy(conn.magic, "CONN", 4); + GetReflectorCallsign().CodeOut(conn.fromcs); + memcpy(conn.mods, mods.c_str(), mods.size()); +} + +void CM17Protocol::EncodeConnectAckPacket(uint8_t *buf) +{ + memcpy(buf, "ACKN", 4); +} + +void CM17Protocol::EncodeInterlinkAckPacket(SInterConnect &ackn, const char *mods) +{ + memset(ackn.magic, 0, sizeof(SInterConnect)); + memcpy(ackn.magic, "ACKN", 4); + GetReflectorCallsign().CodeOut(ackn.fromcs); + memcpy(ackn.mods, mods, strlen(mods)); +} + +void CM17Protocol::EncodeInterlinkNackPacket(uint8_t *buf) +{ + memcpy(buf, "NACK", 4); + GetReflectorCallsign().CodeOut(buf+4); +} + +void CM17Protocol::EncodeConnectNackPacket(uint8_t *buf) +{ + memcpy(buf, "NACK", 4); +} + +void CM17Protocol::EncodeDisconnectPacket(uint8_t *buf, char mod) +{ + memcpy(buf, "DISC", 4); + CCallsign cs(GetReflectorCallsign()); + if (mod) + cs.SetModule(mod); + cs.CodeOut(buf + 4); +} + +void CM17Protocol::EncodeDisconnectedPacket(uint8_t *buf) +{ + memcpy(buf, "DISC", 4); +} diff --git a/m17protocol.h b/m17protocol.h new file mode 100644 index 0000000..b1c0682 --- /dev/null +++ b/m17protocol.h @@ -0,0 +1,85 @@ +// +// Created by Jean-Luc Deltombe (LX3JL) on 01/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of mrefd. +// +// mrefd 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. +// +// mrefd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + +#include + +#include "timepoint.h" +#include "protocol.h" +#include "packet.h" +#include "crc.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CM17Protocol : public CProtocol +{ +public: + CM17Protocol(); + // initialization + bool Initialize(const uint16_t port, const bool has_ipv4, const bool has_ipv6); + + // task + void Task(void); + +protected: + // queue helper + void HandleQueue(void); + + // keepalive helpers + void HandlePeerLinks(void); + void HandleKeepalives(void); + + // stream helpers + void OnFirstPacketIn(std::unique_ptr &, const CIp &); + + // packet decoding helpers + bool IsValidConnect(const uint8_t *, CCallsign &, char *); + bool IsValidDisconnect(const uint8_t *, CCallsign &); + bool IsValidKeepAlive(const uint8_t *, CCallsign &); + bool IsValidPacket(const uint8_t *, bool is_internal, std::unique_ptr &); + bool IsValidNAcknowledge(const uint8_t *, CCallsign &); + bool IsValidInterlinkConnect(const uint8_t *, CCallsign &, char *); + bool IsVaildInterlinkAcknowledge(const uint8_t *, CCallsign &, char *); + + bool HasValidModule(const CCallsign &cs) const; + + // packet encoding helpers + void EncodeKeepAlivePacket(uint8_t *); + void EncodeConnectAckPacket(uint8_t *); + void EncodeConnectNackPacket(uint8_t *); + void EncodeDisconnectPacket(uint8_t *, char); + void EncodeDisconnectedPacket(uint8_t *); + void EncodeInterlinkConnectPacket(SInterConnect &, const std::string &); + void EncodeInterlinkAckPacket(SInterConnect &, const char *); + void EncodeInterlinkNackPacket(uint8_t *); + +protected: + // time + CTimePoint m_LastKeepaliveTime; + CTimePoint m_LastPeersLinkTime; + +private: + std::regex clientRegEx, peerRegEx; + CCRC crc; +}; diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..a47618f --- /dev/null +++ b/main.cpp @@ -0,0 +1,96 @@ +// +// main.cpp +// m17ref +// +// Created by Jean-Luc Deltombe (LX3JL) on 31/10/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include +#include + +#include "main.h" +#include "reflector.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// global objects + +CReflector g_Reflector; + +#ifndef CALLSIGN +#define CALLSIGN "CHANGME" +#endif +#ifndef LISTEN_IPV4 +#define LISTEN_IPV4 "none" +#endif +#ifndef LISTEN_IPV6 +#define LISTEN_IPV6 "none" +#endif + +int main() +{ + auto IPv4RegEx = std::regex("^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3,3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9]){1,1}$", std::regex::extended); + auto IPv6RegEx = std::regex("^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}(:[0-9a-fA-F]{1,4}){1,1}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|([0-9a-fA-F]{1,4}:){1,1}(:[0-9a-fA-F]{1,4}){1,6}|:((:[0-9a-fA-F]{1,4}){1,7}|:))$", std::regex::extended); + auto RefRegEx = std::regex("^M17-([A-Z0-9]){3,3}$", std::regex::extended); + + if (! std::regex_match(CALLSIGN, RefRegEx)) + { + std::cerr << "Malformed reflector callsign: '" << CALLSIGN << "', aborting!" << std::endl; + return EXIT_FAILURE; + } + + if (! std::regex_match(LISTEN_IPV4, IPv4RegEx) && ! std::regex_match(LISTEN_IPV6, IPv6RegEx)) + { + std::cerr << "No valid IP bind address was specifed:" << std::endl; + std::cerr << "IPv4='" << LISTEN_IPV4 << "' IPV6='" << LISTEN_IPV6 << "'" << std::endl; + return EXIT_FAILURE; + } + const std::string cs(CALLSIGN); + + // remove pidfile + remove(PIDFILE_PATH); + + // splash + std::cout << "Starting " << cs << " " << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_REVISION << std::endl; + + // initialize reflector + g_Reflector.SetCallsign(CCallsign(cs)); + + + // and let it run + if ( !g_Reflector.Start() ) + { + std::cout << "Error starting reflector" << std::endl; + return EXIT_FAILURE; + } + std::cout << "Reflector " << g_Reflector.GetCallsign() << " started and listening" << std::endl; + + // write new pid file + std::ofstream ofs(PIDFILE_PATH, std::ofstream::out); + ofs << getpid() << std::endl; + ofs.close(); + + pause(); // wait for any signal + + g_Reflector.Stop(); + std::cout << "Reflector stopped" << std::endl; + + // done + return EXIT_SUCCESS; +} diff --git a/main.h b/main.h new file mode 100644 index 0000000..931f5a0 --- /dev/null +++ b/main.h @@ -0,0 +1,105 @@ +// +// Created by Jean-Luc Deltombe (LX3JL) on 31/10/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Eary, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "configure.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// defines + +// version ----------------------------------------------------- + +#define VERSION_MAJOR 0 +#define VERSION_MINOR 3 +#define VERSION_REVISION 6 + +// debug ------------------------------------------------------- + +//#define DEBUG_NO_ERROR_ON_XML_OPEN_FAIL +//#define DEBUG_DUMPFILE + +// protocols --------------------------------------------------- + +// M17 +#define M17_PORT 17000 +#define M17_KEEPALIVE_PERIOD 3 +#define M17_KEEPALIVE_TIMEOUT (M17_KEEPALIVE_PERIOD*10) +#define M17_RECONNECT_PERIOD 5 + +// xml & json reporting ----------------------------------------- + +#define LASTHEARD_USERS_MAX_SIZE 100 +#define XML_UPDATE_PERIOD 10 // in seconds + +// system paths ------------------------------------------------- +#define XML_PATH "/var/log/mrefd.xml" +#define WHITELIST_PATH "/usr/local/etc/mrefd.whitelist" +#define BLACKLIST_PATH "/usr/local/etc/mrefd.blacklist" +#define INTERLINKLIST_PATH "/usr/local/etc/mrefd.interlink" +#define PIDFILE_PATH "/var/run/mrefd.pid" + +//////////////////////////////////////////////////////////////////////////////////////// +// typedefs + + +//////////////////////////////////////////////////////////////////////////////////////// +// macros + +#define MIN(a,b) (int(a) < int(b))?(a):(b) +#define MAX(a,b) (int(a) > int(b))?(a):(b) +#define MAKEWORD(low, high) ((uint16_t)(((uint8_t)(low)) | (((uint16_t)((uint8_t)(high))) << 8))) +#define MAKEDWORD(low, high) ((uint32_t)(((uint16_t)(low)) | (((uint32_t)((uint16_t)(high))) << 16))) +#define LOBYTE(w) ((uint8_t)(uint16_t)(w & 0x00FF)) +#define HIBYTE(w) ((uint8_t)((((uint16_t)(w)) >> 8) & 0xFF)) +#define LOWORD(dw) ((uint16_t)(uint32_t)(dw & 0x0000FFFF)) +#define HIWORD(dw) ((uint16_t)((((uint32_t)(dw)) >> 16) & 0xFFFF)) + +//////////////////////////////////////////////////////////////////////////////////////// +// global objects + +class CReflector; +extern CReflector g_Reflector; + +class CGateKeeper; +extern CGateKeeper g_GateKeeper; diff --git a/mrefd.blacklist b/mrefd.blacklist new file mode 100644 index 0000000..8c2c8b9 --- /dev/null +++ b/mrefd.blacklist @@ -0,0 +1,14 @@ +############################################################################## +# MREFD blacklist file +# +# one line per entry +# each entry is explicitely denied access (blacklisted) +# you can use * as last wildcard character +# example: +# * -> deny access to eveybody (that would be stupid!) +# LX* -> deny access to all callsign starting with LX +# everything after the * is ignored +# LX3JL -> deny access to LX3JL exactly +# but you would generally want to use LX3JL* instead +# +############################################################################# diff --git a/mrefd.interlink b/mrefd.interlink new file mode 100644 index 0000000..4691610 --- /dev/null +++ b/mrefd.interlink @@ -0,0 +1,22 @@ +############################################################################ +# M17 interlink file +# +# One line per entry, but any reflector can only have one line. +# Each entry specifies a remote M17 Reflector to peer with format: +# +# example: +# M17-ABC 44.123.213.112 ACD +# M17-XYZ 2600:400:bc03::100 ACD +# +# In the above example, this reflector would link modules A, C and D +# with both M17-ABC and M17-XYZ. This example implies both this +# reflector and M17-XYZ support IPv6. +# +# These remote reflectors must list this reflector and modules +# exactly in their interlink file for the link to be established. +# +# Every reflector in an interlink group must link to every other +# reflector in the group or clients in a group may not hear everybody. +############################################################################# + +#M17-724 177.131.119.153 DEF diff --git a/mrefd.whitelist b/mrefd.whitelist new file mode 100644 index 0000000..405d12e --- /dev/null +++ b/mrefd.whitelist @@ -0,0 +1,14 @@ +############################################################################## +# MREFD whitelist file +# +# one line per entry +# each entry is explicitely authorised (whitelisted) +# you can use * as last wildcard character +# example: +# LX* -> authorize all callsign starting with LX'= +# anthing after the * will be ignored +# LX3JL -> authorize LX3JL exactly +# +# no whitelist entry means everyone is allowed +# +############################################################################# diff --git a/notification.cpp b/notification.cpp new file mode 100644 index 0000000..39fe25c --- /dev/null +++ b/notification.cpp @@ -0,0 +1,46 @@ +// +// cnotification.cpp +// M17Refd +// +// Created by Jean-Luc on 05/12/2015. +// Copyright © 2015 Jean-Luc. All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of M17Refd. +// +// M17Refd 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. +// +// M17Refd 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "notification.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CNotification::CNotification() +{ + // init variables + m_iId = NOTIFICATION_NONE; +} + +CNotification::CNotification(int iId) +{ + m_iId = iId; +} + +CNotification::CNotification(int iId, const CCallsign &Callsign) +{ + m_iId = iId; + m_Callsign = Callsign; +} diff --git a/notification.h b/notification.h new file mode 100644 index 0000000..a110e61 --- /dev/null +++ b/notification.h @@ -0,0 +1,59 @@ +// +// cnotification.h +// M17Refd +// +// Created by Jean-Luc on 05/12/2015. +// Copyright © 2015 Jean-Luc. All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of M17Refd. +// +// M17Refd 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. +// +// M17Refd 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + + +#pragma once + +#include "callsign.h" + +//////////////////////////////////////////////////////////////////////////////////////// + +// Id +#define NOTIFICATION_NONE 0 +#define NOTIFICATION_CLIENTS 1 +#define NOTIFICATION_USERS 2 +#define NOTIFICATION_STREAM_OPEN 3 +#define NOTIFICATION_STREAM_CLOSE 4 +#define NOTIFICATION_PEERS 5 + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CNotification +{ +public: + // constructor + CNotification(); + CNotification(int); + CNotification(int, const CCallsign &); + + // get + int GetId(void) const { return m_iId; } + const CCallsign &GetCallsign(void) const { return m_Callsign; } + +protected: + // data + int m_iId; + CCallsign m_Callsign; +}; diff --git a/notificationqueue.h b/notificationqueue.h new file mode 100644 index 0000000..a2bc793 --- /dev/null +++ b/notificationqueue.h @@ -0,0 +1,64 @@ +// +// cnotificationqueue.h +// M17Refd +// +// Created by Jean-Luc on 05/12/2015. +// Copyright © 2015 Jean-Luc. All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of M17Refd. +// +// M17Refd 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. +// +// M17Refd 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + + + +#pragma once + +#include +#include + +#include "notification.h" + + +//////////////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CNotificationQueue +{ +public: + // constructor + CNotificationQueue() {} + + // destructor + ~CNotificationQueue() {} + + // lock + void Lock() { m_Mutex.lock(); } + void Unlock() { m_Mutex.unlock(); } + + // pass thru + CNotification front() { return queue.front(); } + void pop() { queue.pop(); } + void push(CNotification note) { queue.push(note); } + bool empty() const { return queue.empty(); } + +protected: + // data + std::mutex m_Mutex; + std::queue queue; +}; diff --git a/packet.cpp b/packet.cpp new file mode 100644 index 0000000..9608d61 --- /dev/null +++ b/packet.cpp @@ -0,0 +1,86 @@ +// +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include + +#include "packet.h" + +CPacket::CPacket(const uint8_t *buf, bool is_internal) +{ + memcpy(m17.frame.magic, buf, is_internal ? sizeof(SRefM17Frame) : sizeof(SM17Frame)); + if (! is_internal) + m17.relayed = false; + destination.CodeIn(m17.frame.lich.addr_dst); + source.CodeIn(m17.frame.lich.addr_src); +} + +const CCallsign &CPacket::GetDestCallsign() const +{ + return destination; +} + +char CPacket::GetDestModule() const +{ + return destination.GetModule(); +} + +const CCallsign &CPacket::GetSourceCallsign() const +{ + return source; +} + +uint16_t CPacket::GetStreamId() const +{ + return ntohs(m17.frame.streamid); +} + +uint16_t CPacket::GetCRC() const +{ + return ntohs(m17.frame.crc); +} + +void CPacket::SetCRC(uint16_t crc) +{ + m17.frame.crc = htons(crc); +} + +void CPacket::SetRelay(bool state) +{ + m17.relayed = state; +} + +bool CPacket::GetRelay() const +{ + return m17.relayed; +} + +std::unique_ptr CPacket::Duplicate(void) const +{ + return std::unique_ptr(new CPacket(*this)); +} + +bool CPacket::IsLastPacket() const +{ + return ((0x8000u & ntohs(m17.frame.framenumber)) == 0x8000u); +} + +SRefM17Frame &CPacket::GetFrame() +{ + return m17; +} diff --git a/packet.h b/packet.h new file mode 100644 index 0000000..9bc9303 --- /dev/null +++ b/packet.h @@ -0,0 +1,82 @@ +// +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + +#include +#include +#include + +#include "callsign.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// aliases + +// M17 Packets +//all structures must be big endian on the wire, so you'll want htonl (man byteorder 3) and such. +using SM17Lich = struct __attribute__((__packed__)) lich_tag { + uint8_t addr_dst[6]; + uint8_t addr_src[6]; + uint16_t frametype; //frametype flag field per the M17 spec + uint8_t nonce[14]; //bytes for the nonce +}; // 6 + 6 + 2 + 14 = 28 bytes + +//without SYNC or other parts +using SM17Frame = struct __attribute__((__packed__)) m17_tag { + uint8_t magic[4]; + uint16_t streamid; + SM17Lich lich; + uint16_t framenumber; + uint8_t payload[16]; + uint16_t crc; //16 bit CRC +}; // 4 + 2 + 28 + 2 + 16 + 2 = 54 bytes + +// includes extra bool (1 byte) for enforcing one-hop policy +using SRefM17Frame = struct __attribute__((__packed__)) peer_tag { + SM17Frame frame; + bool relayed; +}; // 4 + 2 + 28 + 2 + 16 + 2 + 1 = 55 bytes + +using SInterConnect = struct __attribute__((__packed__)) interconnect_tag { + uint8_t magic[4]; + uint8_t fromcs[6]; + uint8_t mods[27]; +}; // 37 bytes + +class CPacket +{ +public: + CPacket() {} + CPacket(const uint8_t *buf, bool is_internal); + const CCallsign &GetDestCallsign() const; + char GetDestModule() const; + const CCallsign &GetSourceCallsign() const; + uint16_t GetStreamId() const; + uint16_t GetCRC() const; + void SetCRC(uint16_t crc); + void SetRelay(bool state); + bool GetRelay() const; + std::unique_ptr Duplicate(void) const; + bool IsLastPacket() const; + SRefM17Frame &GetFrame(); + +private: + CCallsign destination, source; + SRefM17Frame m17; +}; diff --git a/packetqueue.h b/packetqueue.h new file mode 100644 index 0000000..3c4b5e5 --- /dev/null +++ b/packetqueue.h @@ -0,0 +1,62 @@ +// +// Created by Jean-Luc Deltombe (LX3JL) on 02/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of M17Refd. +// +// M17Refd 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. +// +// M17Refd 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + +#include + +#include "packet.h" +#include "client.h" + +//////////////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////////////// +// CPacketQueue + +class CClient; + +class CPacketQueue +{ +public: + // destructor + virtual ~CPacketQueue() {} + + // lock + void Lock() { m_Mutex.lock(); } + void Unlock() { m_Mutex.unlock(); } + + // pass thru + void pop() { queue.pop(); } + bool empty() const { return queue.empty(); } + std::unique_ptr front() { return std::move(queue.front()); } + void push(std::unique_ptr &packet) { queue.push(std::move(packet)); } + +protected: + // status + bool m_bOpen; + uint16_t m_uiStreamId; + std::mutex m_Mutex; + + // owner + CClient *m_Client; + std::queue> queue; +}; diff --git a/packetstream.cpp b/packetstream.cpp new file mode 100644 index 0000000..deb394e --- /dev/null +++ b/packetstream.cpp @@ -0,0 +1,92 @@ +// +// cpacketstream.cpp +// M17Refd +// +// Created by Jean-Luc Deltombe (LX3JL) on 06/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of M17Refd. +// +// M17Refd 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. +// +// M17Refd 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "packetstream.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CPacketStream::CPacketStream() +{ + m_bOpen = false; + m_uiStreamId = 0; + m_OwnerClient = nullptr; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// open / close + +bool CPacketStream::OpenPacketStream(const CPacket &Header, std::shared_ptrclient) +{ + bool ok = false; + + // not already open? + if ( !m_bOpen ) + { + // update status + m_bOpen = true; + m_uiStreamId = Header.GetStreamId(); + m_Header = Header; + m_OwnerClient = client; + m_LastPacketTime.Now(); + ok = true; + } + return ok; +} + +void CPacketStream::ClosePacketStream(void) +{ + // update status + m_bOpen = false; + m_uiStreamId = 0; + m_OwnerClient = nullptr; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// push & pop + +void CPacketStream::Push(std::unique_ptr Packet) +{ + // update stream dependent packet data + m_LastPacketTime.Now(); + push(Packet); +} + +bool CPacketStream::IsEmpty(void) const +{ + return empty(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// get + +const CIp *CPacketStream::GetOwnerIp(void) +{ + if ( m_OwnerClient != nullptr ) + { + return &(m_OwnerClient->GetIp()); + } + return nullptr; +} diff --git a/packetstream.h b/packetstream.h new file mode 100644 index 0000000..5552ab7 --- /dev/null +++ b/packetstream.h @@ -0,0 +1,67 @@ +// +// Created by Jean-Luc Deltombe (LX3JL) on 06/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of M17Refd. +// +// M17Refd 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. +// +// M17Refd 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + +#include "packetqueue.h" +#include "timepoint.h" +#include "packet.h" + +//////////////////////////////////////////////////////////////////////////////////////// + +//#define STREAM_TIMEOUT (0.600) +#define STREAM_TIMEOUT (1.600) + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CPacketStream : public CPacketQueue +{ +public: + // constructor + CPacketStream(); + + // open / close + bool OpenPacketStream(const CPacket &, std::shared_ptr); + void ClosePacketStream(void); + + // push & pop + void Push(std::unique_ptr packet); + void Tickle(void) { m_LastPacketTime.Now(); } + bool IsEmpty(void) const; + + // get + std::shared_ptr GetOwnerClient(void) { return m_OwnerClient; } + const CIp *GetOwnerIp(void); + bool IsExpired(void) const { return (m_LastPacketTime.DurationSinceNow() > STREAM_TIMEOUT); } + bool IsOpen(void) const { return m_bOpen; } + uint16_t GetPacketStreamId(void) const { return m_uiStreamId; } + const CCallsign &GetUserCallsign(void) const { return m_Header.GetDestCallsign(); } + +protected: + // data + bool m_bOpen; + uint16_t m_uiStreamId; + CTimePoint m_LastPacketTime; + CPacket m_Header; + std::shared_ptr m_OwnerClient; +}; diff --git a/peer.cpp b/peer.cpp new file mode 100644 index 0000000..f38a25f --- /dev/null +++ b/peer.cpp @@ -0,0 +1,130 @@ +// +// cpeer.cpp +// M17Refd +// +// Created by Jean-Luc Deltombe (LX3JL) on 10/12/2016. +// Copyright © 2016 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of M17Refd. +// +// M17Refd 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. +// +// M17Refd 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include +#include "reflector.h" +#include "peer.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + + +CPeer::CPeer() +{ + ::memset(m_ReflectorModules, 0, sizeof(m_ReflectorModules)); + m_ConnectTime = std::time(nullptr); + m_LastHeardTime = std::time(nullptr); +} + +CPeer::CPeer(const CCallsign &callsign, const CIp &ip, const char *modules) +{ + m_Callsign = callsign; + m_Ip = ip; + ::memset(m_ReflectorModules, 0, sizeof(m_ReflectorModules)); + ::strncpy(m_ReflectorModules, modules, sizeof(m_ReflectorModules)-1); + m_LastKeepaliveTime.Now(); + m_ConnectTime = std::time(nullptr); + m_LastHeardTime = std::time(nullptr); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// destructors + +CPeer::~CPeer() +{ + m_Clients.clear(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// operators + +bool CPeer::operator ==(const CPeer &peer) const +{ + if (peer.m_Callsign != m_Callsign) + return false; + if (peer.m_Ip != m_Ip) + return false; + auto it1 = cbegin(); + auto it2 = peer.cbegin(); + while (true) + { + if (it1==cend() && it2==peer.cend()) + break; + if (it1==cend() || it2==peer.cend()) + return false; + if (*it1 != *it2) + return false; + it1++; + it2++; + } + return true; +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// status + +bool CPeer::IsAMaster(void) const +{ + for ( auto it=cbegin(); it!=cend(); it++ ) + { + if ((*it)->IsAMaster()) + return true; + } + return false; +} + +void CPeer::Alive(void) +{ + m_LastKeepaliveTime.Now(); + for ( auto it=begin(); it!=end(); it++ ) + { + (*it)->Alive(); + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// reporting + +void CPeer::WriteXml(std::ofstream &xmlFile) +{ + xmlFile << "" << std::endl; + xmlFile << "\t" << m_Callsign << "" << std::endl; + xmlFile << "\t" << m_Ip.GetAddress() << "" << std::endl; + xmlFile << "\t" << m_ReflectorModules << "" << std::endl; + xmlFile << "\t" << GetProtocolName() << "" << std::endl; + char mbstr[100]; + if (std::strftime(mbstr, sizeof(mbstr), "%A %c", std::localtime(&m_ConnectTime))) + { + xmlFile << "\t" << mbstr << "" << std::endl; + } + if (std::strftime(mbstr, sizeof(mbstr), "%A %c", std::localtime(&m_LastHeardTime))) + { + xmlFile << "\t" << mbstr << "" << std::endl; + } + xmlFile << "" << std::endl; +} diff --git a/peer.h b/peer.h new file mode 100644 index 0000000..a4c2e0b --- /dev/null +++ b/peer.h @@ -0,0 +1,95 @@ +// +// cpeer.h +// M17Refd +// +// Created by Jean-Luc Deltombe (LX3JL) on 10/12/2016. +// Copyright © 2016 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of M17Refd. +// +// M17Refd 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. +// +// M17Refd 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + +#include "version.h" +#include "timepoint.h" +#include "ip.h" +#include "callsign.h" +#include "client.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CPeer +{ +public: + // constructors + CPeer(); + CPeer(const CCallsign &, const CIp &, const char *); + CPeer(const CPeer &) = delete; + + // destructor + virtual ~CPeer(); + + // operators + bool operator ==(const CPeer &) const; + + // get + const CCallsign &GetCallsign(void) const { return m_Callsign; } + const CIp &GetIp(void) const { return m_Ip; } + char *GetReflectorModules(void) { return m_ReflectorModules; } + + // set + + // identity + virtual int GetProtocolRevision(void) const { return 0; } + virtual const char *GetProtocolName(void) const { return "none"; } + + // status + virtual bool IsAMaster(void) const; + virtual void Alive(void); + virtual bool IsAlive(void) const { return false; } + virtual void Heard(void) { m_LastHeardTime = std::time(nullptr); } + + // clients access + int GetNbClients(void) const { return (int)m_Clients.size(); } + void ClearClients(void) { m_Clients.clear(); } + + // pass-thru + std::list>::iterator begin() { return m_Clients.begin(); } + std::list>::iterator end() { return m_Clients.end(); } + std::list>::const_iterator cbegin() const { return m_Clients.cbegin(); } + std::list>::const_iterator cend() const { return m_Clients.cend(); } + + // reporting + virtual void WriteXml(std::ofstream &); + +protected: + // data + CCallsign m_Callsign; + CIp m_Ip; + char m_ReflectorModules[27]; + std::list> m_Clients; + + // status + CTimePoint m_LastKeepaliveTime; + std::time_t m_ConnectTime; + std::time_t m_LastHeardTime; +}; diff --git a/peermap.cpp b/peermap.cpp new file mode 100644 index 0000000..137648e --- /dev/null +++ b/peermap.cpp @@ -0,0 +1,244 @@ +// +// ccallsignlist.cpp +// m17ref +// +// Created by Jean-Luc Deltombe (LX3JL) on 30/12/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include +#include +#include + +#include "main.h" +#include "peermap.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// constructors + +CPeerMap::CPeerMap() +{ + m_Filename = nullptr; + ::memset(&m_LastModTime, 0, sizeof(time_t)); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// file io + +bool CPeerMap::LoadFromFile(const char *filename) +{ + bool ok = false; + char line[256]; + + // and load + std::ifstream file (filename); + if ( file.is_open() ) + { + Lock(); + + // empty list + m_Peers.clear(); + // fill with file content + while ( file.getline(line, sizeof(line)).good() ) + { + // remove leading & trailing spaces + auto name = TrimWhiteSpaces(line); + // crack it + if ( (strlen(name) > 0) && (name[0] != '#') ) + { + // 1st token is callsign + if ( (name = strtok(name, " ,\t")) != nullptr ) + { + if (strcmp(name, CALLSIGN)) + { + if (m_Peers.end() == m_Peers.find(name)) + { + CCallsign callsign(ToUpper(name)); + // 2nd token is ip + char *szip, *szmods; + if ( (szip = strtok(nullptr, " ,\t")) != nullptr ) + { + // 3rd token is modules list + if ( (szmods = strtok(nullptr, " ,\t")) != nullptr ) + { + // create and and store + m_Peers[name] = CPeerMapItem(callsign, szip, ToUpper(szmods)); + } + else + { + std::cerr << "No modules defined for peeer " << name << std::endl; + } + } + else + { + std::cerr << "No IP address defined for peer " << name << std::endl; + } + } + else + { + std::cerr << "Duplicate found: " << name << " in " << filename << std::endl; + } + } + else + { + std::cerr << "Self linking is not allowed! You cannot use " << name << " in " << filename << std::endl; + } + } + } + } + // close file + file.close(); + + // keep file path + m_Filename = filename; + + // update time + GetLastModTime(&m_LastModTime); + + // and done + Unlock(); + ok = true; + std::cout << "Gatekeeper loaded " << m_Peers.size() << " lines from " << filename << std::endl; + } + else + { + std::cout << "Gatekeeper cannot find " << filename << std::endl; + } + + return ok; +} + +bool CPeerMap::ReloadFromFile(void) +{ + bool ok = false; + + if ( m_Filename != nullptr ) + { + ok = LoadFromFile(m_Filename); + } + return ok; +} + +bool CPeerMap::NeedReload(void) +{ + bool needReload = false; + + time_t time; + if ( GetLastModTime(&time) ) + { + needReload = time != m_LastModTime; + } + return needReload; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// compare + +bool CPeerMap::IsCallsignListed(const CCallsign &callsign, char module) const +{ + for ( const auto &item : m_Peers ) + { + if (item.second.HasSameCallsign(callsign) && item.second.HasModuleListed(module)) + return true; + } + + return false; +} + +bool CPeerMap::IsCallsignListed(const CCallsign &callsign, const CIp &ip, const char *modules) const +{ + for ( const auto &item : m_Peers ) + { + if ( item.second.HasSameCallsign(callsign) ) + { + if ( item.second.CheckListedModules(modules) ) + { + if ( ip == item.second.GetIp() ) + { + return true; + } + } + } + } + + return false; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// find + +CPeerMapItem *CPeerMap::FindMapItem(const std::string &cs) +{ + auto it = m_Peers.find(cs); + if (m_Peers.end() == it) + return nullptr; + return &it->second; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// helpers + +char *CPeerMap::TrimWhiteSpaces(char *str) +{ + char *end; + + // Trim leading space & tabs + while((*str == ' ') || (*str == '\t')) str++; + + // All spaces? + if(*str == 0) + return str; + + // Trim trailing space, tab or lf + end = str + ::strlen(str) - 1; + while((end > str) && ((*end == ' ') || (*end == '\t') || (*end == '\r'))) end--; + + // Write new null terminator + *(end+1) = 0; + + return str; +} + +bool CPeerMap::GetLastModTime(time_t *time) +{ + bool ok = false; + + if ( m_Filename != nullptr ) + { + struct stat fileStat; + if( ::stat(m_Filename, &fileStat) != -1 ) + { + *time = fileStat.st_mtime; + ok = true; + } + } + return ok; +} + +char *CPeerMap::ToUpper(char *str) +{ + constexpr auto diff = 'a' - 'A'; + for (char *p=str; *p; p++) + { + if (*p >= 'a' && *p <= 'z') + *p -= diff; + } + return str; +} diff --git a/peermap.h b/peermap.h new file mode 100644 index 0000000..6f37b68 --- /dev/null +++ b/peermap.h @@ -0,0 +1,73 @@ +// +// Created by Jean-Luc Deltombe (LX3JL) on 30/12/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + +#include + +#include "main.h" +#include "peermapitem.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CPeerMap +{ +public: + // constructor + CPeerMap(); + + // destructor + virtual ~CPeerMap() {} + + // locks + void Lock(void) const { m_Mutex.lock(); } + void Unlock(void) const { m_Mutex.unlock(); } + + // file io + virtual bool LoadFromFile(const char *); + bool ReloadFromFile(void); + bool NeedReload(void); + + // compare + bool IsCallsignListed(const CCallsign &, const char) const; + bool IsCallsignListed(const CCallsign &, const CIp &ip, const char*) const; + + // pass-thru + bool empty() const { return m_Peers.empty(); } + std::unordered_map::iterator begin() { return m_Peers.begin(); } + std::unordered_map::iterator end() { return m_Peers.end(); } + + // find + CPeerMapItem *FindMapItem(const std::string &); + +protected: + bool GetLastModTime(time_t *); + char *TrimWhiteSpaces(char *); + char *ToUpper(char *str); + + // data + mutable std::mutex m_Mutex; + const char *m_Filename; + time_t m_LastModTime; + std::unordered_map m_Peers; +}; diff --git a/peermapitem.cpp b/peermapitem.cpp new file mode 100644 index 0000000..d44c14f --- /dev/null +++ b/peermapitem.cpp @@ -0,0 +1,142 @@ +// +// ccallsignlistitem.cpp +// m17ref +// +// Created by Jean-Luc Deltombe (LX3JL) on 31/01/2016. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include + +#include "main.h" +#include "peermapitem.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CPeerMapItem::CPeerMapItem() {} + +CPeerMapItem::CPeerMapItem(const CCallsign &callsign, const CIp &ip, const char *modules) +{ + m_Callsign.CSIn(callsign.GetCS()); + m_Ip = ip; + m_Ip.SetPort(M17_PORT); + m_Mods.clear(); + if ( modules != nullptr ) + { + if ( modules[0] == '*' ) + { + for ( char i = 0; i < NB_OF_MODULES; i++ ) + { + m_Mods.append(1, 'A' + i); + } + } + else + { + for (const char *p=modules; *p; p++) + { + // duplicates not allowed! + if (m_Mods.npos == (m_Mods.find(*p))) + { + int i = *p - 'A'; + // don't add mods that aren't configured + if (i >= 0 && i < NB_OF_MODULES) + { + m_Mods.append(1, *p); + } + else + { + std::cerr << "Peer module " << *p << " is not configured!" << std::endl; + } + } + else + { + std::cout << "Warning: Module " << *p << " is listed multiple times!" << std::endl; + } + + } + } + } +} + +CPeerMapItem::CPeerMapItem(const CCallsign &callsign, const char *url, const char *modules) +{ + m_Callsign.CSIn(callsign.GetCS()); + m_Ip = CIp(strchr(url, ':') ? AF_INET6 : AF_INET, M17_PORT, url); + m_Mods.assign(modules); +} + +CPeerMapItem::CPeerMapItem(const CPeerMapItem &item) +{ + m_Callsign.CSIn(item.m_Callsign.GetCS()); + m_Ip = item.m_Ip; + m_Mods.assign(item.m_Mods); +} + +void CPeerMapItem::operator=(const CPeerMapItem &rhs) +{ + m_Callsign.CSIn(rhs.m_Callsign.GetCS()); + m_Ip = rhs.m_Ip; + m_Mods.assign(rhs.m_Mods); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// compare + +bool CPeerMapItem::HasSameCallsign(const CCallsign &callsign) const +{ + return m_Callsign.HasSameCallsign(callsign); +} + +bool CPeerMapItem::HasModuleListed(char module) const +{ + return m_Mods.npos != m_Mods.find(module); +} + +bool CPeerMapItem::HasSameIp(const CIp &ip) +{ + return ip == m_Ip; +} + +bool CPeerMapItem::CheckListedModules(const char *mods) const +{ + if (mods == nullptr) + return false; + + // make sure every mods character is matched in m_Mods + const auto count = m_Mods.size(); + bool found[count]; + for (unsigned i=0; i. +// ---------------------------------------------------------------------------- + +#pragma once + +#include "main.h" +#include "callsign.h" +#include "ip.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// define + +#define URL_MAXLEN 256 + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CPeerMapItem +{ +public: + // constructor + CPeerMapItem(); + CPeerMapItem(const CCallsign &, const CIp &, const char *); + CPeerMapItem(const CCallsign &, const char *, const char *); + CPeerMapItem(const CPeerMapItem &); + + // assignment + void operator=(const CPeerMapItem &rhs); + + // compare + bool HasSameCallsign(const CCallsign &) const; + bool HasSameIp(const CIp &ip); + bool HasModuleListed(char) const; + bool CheckListedModules(const char*) const; + + // get + const CCallsign &GetCallsign(void) const { return m_Callsign; } + const CIp &GetIp(void) const { return m_Ip; } + const std::string &GetModules(void) const { return m_Mods; } + +protected: + // data + CCallsign m_Callsign; + CIp m_Ip; + std::string m_Mods; +}; diff --git a/peers.cpp b/peers.cpp new file mode 100644 index 0000000..5e14a2f --- /dev/null +++ b/peers.cpp @@ -0,0 +1,175 @@ +// +// cpeers.cpp +// M17Refd +// +// Created by Jean-Luc Deltombe (LX3JL) on 10/12/2016. +// Copyright © 2016 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of M17Refd. +// +// M17Refd 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. +// +// M17Refd 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "reflector.h" +#include "peers.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + + +CPeers::CPeers() {} + +//////////////////////////////////////////////////////////////////////////////////////// +// destructors + +CPeers::~CPeers() +{ + m_Mutex.lock(); + m_Peers.clear(); + m_Mutex.unlock(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// manage peers + +void CPeers::AddPeer(std::shared_ptr peer) +{ + // first check if peer already exists + for ( auto it=begin(); it!=end(); it++ ) + { + if (*peer == *(*it)) + // if found, just do nothing + // so *peer keep pointing on a valid object + // on function return + { + // delete new one + return; + } + } + + // if not, append to the vector (put them in alphabetical order) + auto pit = m_Peers.begin(); + for ( ; pit!=m_Peers.end(); pit++) + { + if (peer->GetCallsign().GetCS().compare((*pit)->GetCallsign().GetCS()) < 0) { + m_Peers.insert(pit, peer); + break; + } + } + if (pit == m_Peers.end()) + m_Peers.push_back(peer); + std::cout << "New peer " << peer->GetCallsign() << " at " << peer->GetIp() << " added with protocol " << peer->GetProtocolName() << std::endl; + // and append all peer's client to reflector client list + // it is double lock safe to lock Clients list after Peers list + CClients *clients = g_Reflector.GetClients(); + for ( auto cit=peer->cbegin(); cit!=peer->cend(); cit++ ) + { + clients->AddClient(*cit); + } + g_Reflector.ReleaseClients(); + + // notify + g_Reflector.OnPeersChanged(); +} + +void CPeers::RemovePeer(std::shared_ptr peer) +{ + // look for the client + for ( auto pit=begin(); pit!=end(); /*increment done in body */ ) + { + // compare object pointers + if (( *pit == peer ) && ( !(*pit)->IsAMaster() )) + { + // remove all clients from reflector client list + // it is double lock safe to lock Clients list after Peers list + CClients *clients = g_Reflector.GetClients(); + for ( auto cit=peer->begin(); cit!=peer->end(); cit++ ) + { + // this also delete the client object + clients->RemoveClient(*cit); + } + // so clear it then + (*pit)->ClearClients(); + g_Reflector.ReleaseClients(); + + // remove it + std::cout << "Peer " << (*pit)->GetCallsign() << " at " << (*pit)->GetIp() << " removed" << std::endl; + pit = m_Peers.erase(pit); + // notify + g_Reflector.OnPeersChanged(); + } + else + { + pit++; + } + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// find peers + +std::shared_ptr CPeers::FindPeer(const CIp &Ip) +{ + for ( auto it=begin(); it!=end(); it++ ) + { + if ( ((*it)->GetIp() == Ip) ) + { + return *it; + } + } + + return nullptr; +} + +std::shared_ptr CPeers::FindPeer(const CCallsign &Callsign, const CIp &Ip) +{ + for ( auto it=begin(); it!=end(); it++ ) + { + if ( (*it)->GetCallsign().HasSameCallsign(Callsign) && ((*it)->GetIp() == Ip) ) + { + return *it; + } + } + + return nullptr; +} + +std::shared_ptr CPeers::FindPeer(const CCallsign &Callsign) +{ + for ( auto it=begin(); it!=end(); it++ ) + { + if ( (*it)->GetCallsign().HasSameCallsign(Callsign) ) + { + return *it; + } + } + + return nullptr; +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// iterate on peers + +std::shared_ptr CPeers::FindNextPeer(std::list>::iterator &it) +{ + if ( it!=end() ) + return *it++; + + return nullptr; +} diff --git a/peers.h b/peers.h new file mode 100644 index 0000000..9828806 --- /dev/null +++ b/peers.h @@ -0,0 +1,74 @@ +// +// cpeers.h +// M17Refd +// +// Created by Jean-Luc Deltombe (LX3JL) on 10/12/2016. +// Copyright © 2016 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of M17Refd. +// +// M17Refd 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. +// +// M17Refd 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + +#include "peer.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// define + + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CPeers +{ +public: + // constructors + CPeers(); + + // destructors + virtual ~CPeers(); + + // locks + void Lock(void) { m_Mutex.lock(); } + void Unlock(void) { m_Mutex.unlock(); } + + // manage peers + int GetSize(void) const { return (int)m_Peers.size(); } + void AddPeer(std::shared_ptr); + void RemovePeer(std::shared_ptr); + + // pass-thru + std::list>::iterator begin() { return m_Peers.begin(); } + std::list>::iterator end() { return m_Peers.end(); } + std::list>::const_iterator cbegin() const { return m_Peers.cbegin(); } + std::list>::const_iterator cend() const { return m_Peers.cend(); } + + // find peers + std::shared_ptr FindPeer(const CIp &); + std::shared_ptr FindPeer(const CCallsign &, const CIp &); + std::shared_ptr FindPeer(const CCallsign &); + + // iterate on peers + std::shared_ptr FindNextPeer(std::list>::iterator &); + +protected: + // data + std::mutex m_Mutex; + std::list> m_Peers; +}; diff --git a/protocol.cpp b/protocol.cpp new file mode 100644 index 0000000..0794279 --- /dev/null +++ b/protocol.cpp @@ -0,0 +1,328 @@ +// +// cprotocol.cpp +// mrefd +// +// Created by Jean-Luc Deltombe (LX3JL) on 01/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of mrefd. +// +// mrefd 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. +// +// mrefd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "protocol.h" +#include "clients.h" +#include "reflector.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + + +CProtocol::CProtocol() : keep_running(true) {} + + +//////////////////////////////////////////////////////////////////////////////////////// +// destructor + +CProtocol::~CProtocol() +{ + // kill threads + Close(); + + // empty queue + m_Queue.Lock(); + while ( !m_Queue.empty() ) + { + m_Queue.pop(); + } + m_Queue.Unlock(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// initialization + +bool CProtocol::Initialize(const uint16_t port, const bool has_ipv4, const bool has_ipv6) +{ + // init reflector apparent callsign + m_ReflectorCallsign = g_Reflector.GetCallsign(); + + // reset stop flag + keep_running = true; + + // create our sockets +#ifdef LISTEN_IPV4 + if (has_ipv4) + { + CIp ip4(AF_INET, port, LISTEN_IPV4); + if ( ip4.IsSet() ) + { + if (! m_Socket4.Open(ip4)) + return false; + } + std::cout << "Listening on " << ip4 << std::endl; + } +#endif + +#ifdef LISTEN_IPV6 + if (has_ipv6) + { + CIp ip6(AF_INET6, port, LISTEN_IPV6); + if ( ip6.IsSet() ) + { + if (! m_Socket6.Open(ip6)) + { + m_Socket4.Close(); + return false; + } + std::cout << "Listening on " << ip6 << std::endl; + } + } +#endif + + try { + m_Future = std::async(std::launch::async, &CProtocol::Thread, this); + } + catch (const std::exception &e) + { + std::cerr << "Could not start protocol on port " << port << ": " << e.what() << std::endl; + m_Socket4.Close(); + m_Socket6.Close(); + return false; + } + + return true; +} + +void CProtocol::Thread() +{ + while (keep_running) + { + Task(); + } +} + +void CProtocol::Close(void) +{ + keep_running = false; + if ( m_Future.valid() ) + { + m_Future.get(); + } + m_Socket4.Close(); + m_Socket6.Close(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// streams helpers + +void CProtocol::OnPacketIn(std::unique_ptr &packet, const CIp &ip) +{ + // find the stream + CPacketStream *stream = GetStream(packet->GetStreamId(), ip); + if ( stream ) + { + auto islast = packet->IsLastPacket(); // we'll need this after the std::move()! + + // and push the packet + stream->Lock(); + stream->Push(std::move(packet)); + stream->Unlock(); + + if (islast) + g_Reflector.CloseStream(stream); + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// stream handle helpers + +CPacketStream *CProtocol::GetStream(uint16_t uiStreamId, const CIp &Ip) +{ + for ( auto it=m_Streams.begin(); it!=m_Streams.end(); it++ ) + { + if ( (*it)->GetPacketStreamId() == uiStreamId ) + { + // if Ip not nullptr, also check if IP match + if ( (*it)->GetOwnerIp() != nullptr ) + { + if ( Ip == *((*it)->GetOwnerIp()) ) + { + return *it; + } + } + } + } + // done + return nullptr; +} + +void CProtocol::CheckStreamsTimeout(void) +{ + for ( auto it=m_Streams.begin(); it!=m_Streams.end(); ) + { + // time out ? + (*it)->Lock(); + if ( (*it)->IsExpired() ) + { + // yes, close it + (*it)->Unlock(); + g_Reflector.CloseStream(*it); + // and remove it + it = m_Streams.erase(it); + } + else + { + (*it++)->Unlock(); + } + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// syntax helper + +bool CProtocol::IsNumber(char c) const +{ + return ((c >= '0') && (c <= '9')); +} + +bool CProtocol::IsLetter(char c) const +{ + return ((c >= 'A') && (c <= 'Z')); +} + +bool CProtocol::IsSpace(char c) const +{ + return (c == ' '); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// Receivers + +ssize_t CProtocol::Receive6(uint8_t *buf, CIp &ip, int time_ms) +{ + return m_Socket6.Receive(buf, ip, time_ms); +} + +ssize_t CProtocol::Receive4(uint8_t *buf, CIp &ip, int time_ms) +{ + return m_Socket4.Receive(buf, ip, time_ms); +} + +ssize_t CProtocol::ReceiveDS(uint8_t *buf, CIp &ip, int time_ms) +{ + auto fd4 = m_Socket4.GetSocket(); + auto fd6 = m_Socket6.GetSocket(); + + if (fd4 < 0) + { + if (fd6 < 0) + return false; + return m_Socket6.Receive(buf, ip, time_ms); + } + else if (fd6 < 0) + return m_Socket4.Receive(buf, ip, time_ms); + + fd_set fset; + FD_ZERO(&fset); + FD_SET(fd4, &fset); + FD_SET(fd6, &fset); + int max = (fd4 > fd6) ? fd4 : fd6; + struct timeval tv; + tv.tv_sec = time_ms / 1000; + tv.tv_usec = (time_ms % 1000) * 1000; + + auto rval = select(max+1, &fset, 0, 0, &tv); + if (rval <= 0) + { + if (rval < 0) + std::cerr << "ReceiveDS select error: " << strerror(errno) << std::endl; + return 0; + } + + if (FD_ISSET(fd4, &fset)) + return m_Socket4.ReceiveFrom(buf, ip); + else + return m_Socket6.ReceiveFrom(buf, ip); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// dual stack senders + +void CProtocol::Send(const char *buf, const CIp &Ip) const +{ + switch (Ip.GetFamily()) + { + case AF_INET: + m_Socket4.Send(buf, Ip); + break; + case AF_INET6: + m_Socket6.Send(buf, Ip); + break; + default: + std::cerr << "ERROR: wrong family: " << Ip.GetFamily() << std::endl; + break; + } +} + +void CProtocol::Send(const uint8_t *buf, size_t size, const CIp &Ip) const +{ + switch (Ip.GetFamily()) + { + case AF_INET: + m_Socket4.Send(buf, size, Ip); + break; + case AF_INET6: + m_Socket6.Send(buf, size, Ip); + break; + default: + std::cerr << "ERROR: wrong family: " << Ip.GetFamily() << std::endl; + break; + } +} + +void CProtocol::Send(const char *buf, const CIp &Ip, uint16_t port) const +{ + switch (Ip.GetFamily()) + { + case AF_INET: + m_Socket4.Send(buf, Ip, port); + break; + case AF_INET6: + m_Socket6.Send(buf, Ip, port); + break; + default: + std::cerr << "ERROR: wrong family: " << Ip.GetFamily() << " on port " << port << std::endl; + break; + } +} + +void CProtocol::Send(const uint8_t *buf, size_t size, const CIp &Ip, uint16_t port) const +{ + switch (Ip.GetFamily()) + { + case AF_INET: + m_Socket4.Send(buf, size, Ip, port); + break; + case AF_INET6: + m_Socket6.Send(buf, size, Ip, port); + break; + default: + std::cerr << "ERROR: wrong family: " << Ip.GetFamily() << " on port " << port << std::endl; + break; + } +} diff --git a/protocol.h b/protocol.h new file mode 100644 index 0000000..3586d3f --- /dev/null +++ b/protocol.h @@ -0,0 +1,113 @@ +// +// cprotocol.h +// mrefd +// +// Created by Jean-Luc Deltombe (LX3JL) on 01/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of mrefd. +// +// mrefd 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. +// +// mrefd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + +#include "udpsocket.h" +#include "packetstream.h" +#include "packet.h" +#include "base.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CProtocol : public CBase +{ +public: + // constructor + CProtocol(); + + // destructor + virtual ~CProtocol(); + + // initialization + virtual bool Initialize(const uint16_t port, const bool has_ipv4, const bool has_ipv6); + virtual void Close(void); + + // queue + CPacketQueue *GetQueue(void) { m_Queue.Lock(); return &m_Queue; } + void ReleaseQueue(void) { m_Queue.Unlock(); } + + // get + const CCallsign &GetReflectorCallsign(void)const { return m_ReflectorCallsign; } + + // task + void Thread(void); + virtual void Task(void) = 0; + +protected: + // packet encoding helpers + virtual bool EncodeDvHeaderPacket(const CPacket &, uint8_t *) const { return false; } + virtual bool EncodeDvFramePacket(const CPacket &, uint8_t *) const { return false; } + virtual bool EncodeDvLastFramePacket(const CPacket &, uint8_t *) const { return false; } + + // stream helpers + virtual void OnPacketIn(std::unique_ptr &, const CIp &); + + // stream handle helpers + CPacketStream *GetStream(uint16_t, const CIp &); + void CheckStreamsTimeout(void); + + // queue helper + virtual void HandleQueue(void) = 0; + + // keepalive helpers + virtual void HandleKeepalives(void) = 0; + + // syntax helper + bool IsNumber(char) const; + bool IsLetter(char) const; + bool IsSpace(char) const; + + ssize_t Receive6(uint8_t *buf, CIp &Ip, int time_ms); + ssize_t Receive4(uint8_t *buf, CIp &Ip, int time_ms); + ssize_t ReceiveDS(uint8_t *buf, CIp &Ip, int time_ms); + + void Send(const char *buf, const CIp &Ip) const; + void Send(const uint8_t *buf, size_t size, const CIp &Ip) const; + void Send(const char *buf, const CIp &Ip, uint16_t port) const; + void Send(const uint8_t *buf, size_t size, const CIp &Ip, uint16_t port) const; + + // socket + CUdpSocket m_Socket4; + CUdpSocket m_Socket6; + + // streams + std::list m_Streams; + + // queue + CPacketQueue m_Queue; + + // thread + std::atomic keep_running; + std::future m_Future; + + // identity + CCallsign m_ReflectorCallsign; + + // debug + CTimePoint m_DebugTimer; +}; diff --git a/rconfig b/rconfig new file mode 100644 index 0000000..db35e3c --- /dev/null +++ b/rconfig @@ -0,0 +1,234 @@ +#!/bin/bash +# +# Copyright (c) 2020 by Thomas A. Early N7TAE +# +# 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 2 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 . + +SetBooleanValue () +{ + local dvname + local cv + if [ -z $2 ]; then + if [ -z ${!1+x} ]; then + if [[ "$1" == module_[abc]_* ]]; then + echo matches + dvname=${1//_[abc]_/_x_} + else + echo does not match + dvname=${1}_d + fi + cv=${!dvname} + else + cv=${!1} + fi + if [[ $cv == [tT]* ]]; then + eval ${1}=false + else + eval ${1}=true + fi + elif [[ "$2" == [tT]* ]]; then + eval ${1}=true + else + eval ${1}=false + fi +} + +EvaluateVar () +{ + if [ -z ${!1+x} ]; then + if [ -z "${!2}" ]; then + echo "'' " + else + echo "${!2} " + fi + else + if [ -z "${!1}" ]; then + echo "''" + else + echo "${!1}" + fi + fi +} + +WriteMemFile () +{ + local file + file="$rcfg" + echo "# created on `date`" > $file + [ -z ${callsign+x} ] || echo "callsign='$callsign'" >> $file + [ -z ${nummod+x} ] || echo "nummod=$nummod" >> $file + [ -z ${mclients+x} ] || echo "mclients=$mclients" >> $file + [ -z ${ip4addr+x} ] || echo "ip4addr='$ip4addr'" >> $file + [ -z ${ip6addr+x} ] || echo "ip6addr='$ip6addr'" >> $file + [ -z ${dbsupport+x} ] || echo "dbsupport=$dbsupport" >> $file +} + +WriteSRCHFile () +{ + local file m + file="$srch" + echo "// Created on `date`" > $file + echo "#define CALLSIGN \"${callsign}\"" >> $file + if [ -z ${nummod+x} ]; then + echo "#define NB_OF_MODULES ${nummod_d}" >> $file + else + echo "#define NB_OF_MODULES ${nummod}" >> $file + fi + if [ ! -z ${ip4addr+x} ]; then + echo "#define LISTEN_IPV4 \"${ip4addr}\"" >> $file + fi + if [ ! -z ${ip6addr+x} ]; then + echo "#define LISTEN_IPV6 \"${ip6addr}\"" >> $file + fi + if [ ! -z ${mclients+x} ]; then + if [[ "$mclients" == "true" ]]; then + echo "#define MCLIENTS" >> $file + fi + fi +} + +WriteSRCMKFile () +{ + local file + file="$srcm" + echo "# Created on `date`" > $file + if [ -z ${dbsupport+x} ]; then + echo "debug = $dbsupport_d" >> $file + else + echo "debug = $dbsupport" >> $file + fi +} + +WriteCFGFiles () +{ + WriteMemFile + WriteSRCHFile + WriteSRCMKFile +} + +ListCFGFiles () +{ + echo "===========${rcfg}=============" + cat $rcfg + echo "===========${srch}=============" + cat $srch + echo "===========${srcm}=============" + cat $srcm +} + +# Execution starts here! +# file locations +rcfg='reflector.cfg' +srch='configure.h' +srcm='configure.mk' +mrefserv='/etc/systemd/system/mrefd.service' +# default values +callsign_d='CHNGME' +nummod_d=26 +mclients_d=false +ip4addr_d='none' +ip6addr_d='none' +dbsupport_d=false + +if [ -e reflector.cfg ]; then + source reflector.cfg +else + echo 'No configuration file found...' + sleep 1 +fi + +if [ -z ${expertmode+x} ]; then + if [ -e $mrefserv ]; then + echo -n "You cannot change the configuration right now beacuse there is an m17 server running." + echo "===========${rcfg}=============" + cat $rcfg + echo + echo "Please uninstall the running server before attempting to modify the configuration." + exit 1 + fi +fi + +key='x' +# main loop +while [[ "$key" != q* ]] +do + clear + echo + echo " Reflector Configuration, Version #201104" + echo + echo " ************** REFLECTOR ****************" + echo -n "cs : Reflector Callsign = "; EvaluateVar callsign{,_d} + echo -n "nm : Number of Modules = "; EvaluateVar nummod{,_d} + echo -n "mc : Allow multiple clients on the same IP = "; EvaluateVar mclients{,_d} + echo " ************* IP ADDRESSES ***************" + echo " You must set at least one of these addresses!" + echo " Usually, IPv4 is 0.0.0.0 and/or IPv6 is ::" + echo " but might be different in special curcumstances" + echo " where you cannot bind to the 'any' address." + echo -n "i4 : IPv4 Listen Address = "; EvaluateVar ip4addr{,_d} + echo -n "i6 : IPv6 Listen Address = "; EvaluateVar ip6addr{,_d} + echo " *************** DEBUGGING ****************" + echo -n "db : Debugging Support = "; EvaluateVar dbsupport{,_d} + echo + if [[ "$callsign" == M17-* ]] && ( [ ! -z ${ip4addr+x} ] || [ ! -z ${ip6addr+x} ] ); then + echo "w : Write configuration files (overwrites any existing files) and quit" + fi + echo "q : Quit without saving" + echo "u : Unset the value of (revert to the default value)." + echo + read -p "Please input - omit value to toggle a true/false : " key value garbage + if [[ "$key" == cs* ]]; then + if [[ "${value^^}" =~ ^M17-([0-9A-Z]){3,3}$ ]]; then + callsign="${value^^}" + else + clear + echo "${value^^} is not a valid reflector name" + read -p " to continue: " garbage + fi + elif [[ "$key" == i6* ]]; then + if [[ "${value^^}" =~ ^(([0-9A-F]{1,4}:){7,7}[0-9A-F]{1,4}|([0-9A-F]{1,4}:){1,7}:|([0-9A-F]{1,4}:){1,6}(:[0-9A-F]{1,4}){1,1}|([0-9A-F]{1,4}:){1,5}(:[0-9A-F]{1,4}){1,2}|([0-9A-F]{1,4}:){1,4}(:[0-9A-F]{1,4}){1,3}|([0-9A-F]{1,4}:){1,3}(:[0-9A-F]{1,4}){1,4}|([0-9A-F]{1,4}:){1,2}(:[0-9A-F]{1,4}){1,5}|([0-9A-F]{1,4}:){1,1}(:[0-9A-F]{1,4}){1,6}|:((:[0-9A-F]{1,4}){1,7}|:))$ ]]; then + ip6addr="$value" + else + clear + echo "$value is not a valid IPv6 address!" + read -p " to continue: " garbage + fi + elif [[ "$key" == db* ]]; then SetBooleanValue dbsupport "$value" + elif [[ "$key" == w* ]]; then + if [[ "$callsign" == M17-* ]] && ( [ ! -z ${ip4addr+x} ] || [ ! -z ${ip6addr+x} ] ); then + WriteCFGFiles + ListCFGFiles + exit 0 + fi + elif [[ "$key" == u* ]]; then + if [[ "$value" == cs* ]]; then unset callsign + elif [[ "$value" == nm* ]]; then unset nummod + elif [[ "$value" == i4* ]]; then unset ip4addr + elif [[ "$value" == i6* ]]; then unset ip6addr + elif [[ "$value" == mc* ]]; then unset mclients + elif [[ "$value" == db* ]]; then unset dbsupport + fi + fi +done +exit 0 diff --git a/reflector.cfg b/reflector.cfg new file mode 100644 index 0000000..41e3a42 --- /dev/null +++ b/reflector.cfg @@ -0,0 +1,4 @@ +# created on Tue 24 Jan 2023 07:18:41 AM -03 +callsign='M17-YSF' +mclients=true +ip4addr='0.0.0.0' diff --git a/reflector.cpp b/reflector.cpp new file mode 100644 index 0000000..81c5dd5 --- /dev/null +++ b/reflector.cpp @@ -0,0 +1,462 @@ +// +// creflector.cpp +// M17Refd +// +// Created by Jean-Luc Deltombe (LX3JL) on 31/10/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of M17Refd. +// +// M17Refd 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. +// +// M17Refd 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include +#include "reflector.h" +#include "gatekeeper.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CReflector::CReflector() +{ + keep_running = true; +} + +CReflector::CReflector(const CCallsign &callsign) +{ + keep_running = true; + m_Callsign = callsign; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// destructor + +CReflector::~CReflector() +{ + keep_running = false; + if ( m_XmlReportFuture.valid() ) + { + m_XmlReportFuture.get(); + } + for ( int i = 0; i < NB_OF_MODULES; i++ ) + { + if ( m_RouterFuture[i].valid() ) + { + m_RouterFuture[i].get(); + } + } +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// operation + +bool CReflector::Start(void) +{ + // let's go! + keep_running = true; + + // init gate keeper. It can only return true! + g_GateKeeper.Init(); + + // create protocols + if (! m_Protocol.Initialize(M17_PORT, true, true)) + { + m_Protocol.Close(); + return false; + } + + // start one thread per reflector module + for ( int i = 0; i < NB_OF_MODULES; i++ ) + { + m_RouterFuture[i] = std::async(std::launch::async, &CReflector::RouterThread, this, &(m_Stream[i])); + } + + // start the reporting threads + m_XmlReportFuture = std::async(std::launch::async, &CReflector::XmlReportThread, this); + + return true; +} + +void CReflector::Stop(void) +{ + // stop & delete all threads + keep_running = false; + + // stop & delete report threads + if ( m_XmlReportFuture.valid() ) + { + m_XmlReportFuture.get(); + } + + // stop & delete all router thread + for ( int i = 0; i < NB_OF_MODULES; i++ ) + { + if ( m_RouterFuture[i].valid() ) + { + m_RouterFuture[i].get(); + } + } + + // close protocols + m_Protocol.Close(); + + // close gatekeeper + g_GateKeeper.Close(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// stream opening & closing + +bool CReflector::IsStreaming(char module) +{ + return false; +} + +// clients MUST have been locked by the caller so we can freely access it within the fuction +CPacketStream *CReflector::OpenStream(std::unique_ptr &Header, std::shared_ptrclient) +{ + // check sid is not zero + if ( 0U == Header->GetStreamId() ) + { + std::cerr << "Incoming stream has zero streamID" << std::endl; + return nullptr; + } + + // check if client is valid candidate + if ( ! m_Clients.IsClient(client) ) + { + std::cerr << "can't find client " << client->GetCallsign() << std::endl; + return nullptr; + } + + if ( client->IsAMaster() ) + { + std::cerr << "Client " << client->GetCallsign() << " is already a Master" << std::endl; + return nullptr; + } + + // get the module's queue + char module = Header->GetDestModule(); + + // check if no stream with same streamid already open + // to prevent loops + if ( IsStreamOpen(Header) ) + { + std::cerr << "Detected stream loop on module " << module << " for client " << client->GetCallsign() << " with sid " << Header->GetStreamId() << std::endl; + return nullptr; + } + + CPacketStream *stream = GetStream(module); + if ( stream == nullptr ) { + std::cerr << "Can't get stream from module '" << module << "'" << std::endl; + return nullptr; + } + + stream->Lock(); + // is it available ? + if ( stream->OpenPacketStream(*Header, client) ) + { + // stream open, mark client as master + // so that it can't be deleted + client->SetMasterOfModule(module); + + // update last heard time + client->Heard(); + + // report + std::cout << "Opening stream on module " << module << " for client " << client->GetCallsign() << " with id 0x" << std::hex << Header->GetStreamId() << std::dec << " by user " << Header->GetSourceCallsign() << std::endl; + + // and push header packet + stream->Push(std::move(Header)); + + // notify + g_Reflector.OnStreamOpen(stream->GetUserCallsign()); + + } + stream->Unlock(); + return stream; +} + +void CReflector::CloseStream(CPacketStream *stream) +{ + if ( stream != nullptr ) + { + // wait queue is empty. this waits forever + bool bEmpty = false; + do + { + stream->Lock(); + // do not use stream->IsEmpty() has this "may" never succeed + // and anyway, the DvLastFramPacket short-circuit the transcoder + // loop queues + bEmpty = stream->empty(); + stream->Unlock(); + if ( !bEmpty ) + CTimePoint::TaskSleepFor(10); + } + while (!bEmpty); + + GetClients(); // lock clients + stream->Lock(); // lock stream + + // get and check the master + std::shared_ptrclient = stream->GetOwnerClient(); + if ( client != nullptr ) + { + // client no longer a master + client->NotAMaster(); + + // notify + OnStreamClose(stream->GetUserCallsign()); + + std::cout << "Closing stream on module " << GetStreamModule(stream) << std::endl; + } + + // release clients + ReleaseClients(); + + // unlock before closing + // to avoid double lock in assiociated + // codecstream close/thread-join + stream->Unlock(); + + // and stop the queue + stream->ClosePacketStream(); + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// router threads + +void CReflector::RouterThread(CPacketStream *streamIn) +{ + // get our module + uint8_t uiModuleId = GetStreamModule(streamIn); + + // get on input queue + std::unique_ptr packet; + + while (keep_running) + { + // any packet in our input queue ? + streamIn->Lock(); + if ( !streamIn->empty() ) + { + // get the packet + packet = streamIn->front(); + streamIn->pop(); + } + else + { + packet = nullptr; + } + streamIn->Unlock(); + + // route it + if ( packet != nullptr ) + { + // duplicate packet + auto packetClone = packet->Duplicate(); + + // and push it + CPacketQueue *queue = m_Protocol.GetQueue(); + queue->push(packetClone); + m_Protocol.ReleaseQueue(); + } + else + { + CTimePoint::TaskSleepFor(10); + } + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// report threads + +void CReflector::XmlReportThread() +{ + while (keep_running) + { + // report to xml file + std::ofstream xmlFile; + xmlFile.open(XML_PATH, std::ios::out | std::ios::trunc); + if ( xmlFile.is_open() ) + { + // write xml file + WriteXmlFile(xmlFile); + + // and close file + xmlFile.close(); + } + else + { + std::cout << "Failed to open " << XML_PATH << std::endl; + } + + // and wait a bit + for (int i=0; i< XML_UPDATE_PERIOD && keep_running; i++) + CTimePoint::TaskSleepFor(1000); + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// notifications + +void CReflector::OnPeersChanged(void) +{ + CNotification notification(NOTIFICATION_PEERS); + + m_Notifications.Lock(); + m_Notifications.push(notification); + m_Notifications.Unlock(); +} + +void CReflector::OnClientsChanged(void) +{ + CNotification notification(NOTIFICATION_CLIENTS); + + m_Notifications.Lock(); + m_Notifications.push(notification); + m_Notifications.Unlock(); +} + +void CReflector::OnUsersChanged(void) +{ + CNotification notification(NOTIFICATION_USERS); + + m_Notifications.Lock(); + m_Notifications.push(notification); + m_Notifications.Unlock(); +} + +void CReflector::OnStreamOpen(const CCallsign &callsign) +{ + CNotification notification(NOTIFICATION_STREAM_OPEN, callsign); + + m_Notifications.Lock(); + m_Notifications.push(notification); + m_Notifications.Unlock(); +} + +void CReflector::OnStreamClose(const CCallsign &callsign) +{ + CNotification notification(NOTIFICATION_STREAM_CLOSE, callsign); + + m_Notifications.Lock(); + m_Notifications.push(notification); + m_Notifications.Unlock(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// modules & queues + +int CReflector::GetModuleIndex(char module) const +{ + int i = (int)module - (int)'A'; + if ( (i < 0) || (i >= NB_OF_MODULES) ) + { + i = -1; + } + return i; +} + +CPacketStream *CReflector::GetStream(char module) +{ + int i = GetModuleIndex(module); + if ( i >= 0 ) + { + return &(m_Stream[i]); + } + return nullptr; +} + +bool CReflector::IsStreamOpen(const std::unique_ptr &DvHeader) +{ + for ( unsigned i = 0; i < m_Stream.size(); i++ ) + { + if ( (m_Stream[i].GetPacketStreamId() == DvHeader->GetStreamId()) && (m_Stream[i].IsOpen()) ) + return true; + } + return false; +} + +char CReflector::GetStreamModule(CPacketStream *stream) +{ + for ( unsigned i = 0; i < m_Stream.size(); i++ ) + { + if ( &(m_Stream[i]) == stream ) + return GetModuleLetter(i); + } + return ' '; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// xml helpers + +void CReflector::WriteXmlFile(std::ofstream &xmlFile) +{ + // write header + xmlFile << "" << std::endl; + + // software version + char sz[64]; + ::sprintf(sz, "%d.%d.%d", VERSION_MAJOR, VERSION_MINOR, VERSION_REVISION); + xmlFile << "" << sz << "" << std::endl; + + // linked peers + xmlFile << "<" << m_Callsign << " linked peers>" << std::endl; + // lock + CPeers *peers = GetPeers(); + // iterate on peers + for ( auto pit=peers->cbegin(); pit!=peers->cend(); pit++ ) + { + (*pit)->WriteXml(xmlFile); + } + // unlock + ReleasePeers(); + xmlFile << "" << std::endl; + + // linked nodes + xmlFile << "<" << m_Callsign << " linked nodes>" << std::endl; + // lock + CClients *clients = GetClients(); + // iterate on clients + for ( auto cit=clients->cbegin(); cit!=clients->cend(); cit++ ) + { + if ( (*cit)->IsNode() && (*cit)->GetCallsign().GetCS(4).compare("M17-") ) + { + (*cit)->WriteXml(xmlFile); + } + } + // unlock + ReleaseClients(); + xmlFile << "" << std::endl; + + // last heard users + xmlFile << "<" << m_Callsign << " heard users>" << std::endl; + // lock + CUsers *users = GetUsers(); + // iterate on users + for ( auto it=users->begin(); it!=users->end(); it++ ) + { + (*it).WriteXml(xmlFile); + } + // unlock + ReleaseUsers(); + xmlFile << "" << std::endl; +} diff --git a/reflector.h b/reflector.h new file mode 100644 index 0000000..c770041 --- /dev/null +++ b/reflector.h @@ -0,0 +1,123 @@ +// +// Created by Jean-Luc Deltombe (LX3JL) on 31/10/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of M17Refd. +// +// M17Refd 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. +// +// M17Refd 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + +#include "users.h" +#include "clients.h" +#include "peers.h" +#include "m17protocol.h" +#include "packetstream.h" +#include "notificationqueue.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// define + +// event defines +#define EVENT_NONE 0 +#define EVENT_CLIENTS 1 +#define EVENT_USERS 2 + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CReflector +{ +public: + // constructor + CReflector(); + CReflector(const CCallsign &); + + // destructor + virtual ~CReflector(); + + // settings + void SetCallsign(const CCallsign &callsign) { m_Callsign = callsign; } + const CCallsign &GetCallsign(void) const { return m_Callsign; } + + + // operation + bool Start(void); + void Stop(void); + + // clients + CClients *GetClients(void) { m_Clients.Lock(); return &m_Clients; } + void ReleaseClients(void) { m_Clients.Unlock(); } + + // peers + CPeers *GetPeers(void) { m_Peers.Lock(); return &m_Peers; } + void ReleasePeers(void) { m_Peers.Unlock(); } + + // stream opening & closing + CPacketStream *OpenStream(std::unique_ptr &, std::shared_ptr); + bool IsStreaming(char); + void CloseStream(CPacketStream *); + + // users + CUsers *GetUsers(void) { m_Users.Lock(); return &m_Users; } + void ReleaseUsers(void) { m_Users.Unlock(); } + + // get + bool IsValidModule(char c) const { return (GetModuleIndex(c) >= 0); } + int GetModuleIndex(char) const; + char GetModuleLetter(int i) const { return 'A' + (char)i; } + + // notifications + void OnPeersChanged(void); + void OnClientsChanged(void); + void OnUsersChanged(void); + void OnStreamOpen(const CCallsign &); + void OnStreamClose(const CCallsign &); + +protected: + // threads + void RouterThread(CPacketStream *); + void XmlReportThread(void); + // streams + CPacketStream *GetStream(char); + bool IsStreamOpen(const std::unique_ptr &); + char GetStreamModule(CPacketStream *); + + // xml helpers + void WriteXmlFile(std::ofstream &); + +protected: + // identity + CCallsign m_Callsign; + + // objects + CUsers m_Users; // sorted list of lastheard stations + CClients m_Clients; // list of linked repeaters/nodes/peers's modules + CPeers m_Peers; // list of linked peers + CM17Protocol m_Protocol; // the only protocol + // queues + std::array m_Stream; + + // threads + std::atomic keep_running; + std::array, NB_OF_MODULES> m_RouterFuture; + std::future m_XmlReportFuture, m_JsonReportFuture; + + // notifications + CNotificationQueue m_Notifications; +}; diff --git a/systemd/mrefd.service b/systemd/mrefd.service new file mode 100644 index 0000000..9e84963 --- /dev/null +++ b/systemd/mrefd.service @@ -0,0 +1,12 @@ +[Unit] +Description=mrefd +Requires=network.target +After=systemd-user-session.service network.target + +[Service] +Type=simple +ExecStart=/usr/local/bin/mrefd +Restart=always + +[Install] +WantedBy=multi-user.target diff --git a/test-all.cpp b/test-all.cpp new file mode 100644 index 0000000..81e4579 --- /dev/null +++ b/test-all.cpp @@ -0,0 +1,57 @@ +#include +#include + +#include "crc.h" +#include "callsign.h" + +int main() +{ + if (sizeof(uint64_t) != sizeof(size_t)) + { + printf("ERROR! Type size_t is not 64 bits.\n"); + return 1; + } + + std::string callsign("M17-USA A"); + CCallsign cs(callsign); + auto coded = cs.Hash(); + if (coded == 0x05f74c74caedu) + { + uint8_t code[6] = { 0 }; + auto c = coded; + for (int i=5; c; i--) + { + code[i] = c % 0x100u; + c /= 0x100u; + } + CCallsign cs1(code); + printf("Callsign %s is 0x%lx and decodes back to %s\n", callsign.c_str(), coded, cs1.GetCS().c_str()); + } + else + { + printf("ERROR with callsign encoding!\n"); + return 1; + } + + CCRC crc; + + unsigned char string[256]; + + string[0] = 'A'; + + auto calc = crc.CalcCRC(string, 1); + printf("\nThe calcluated crc of \"A\" is 0x%x. This result is %s!\n\n", calc, (calc==0x206eu) ? "correct" : "INCORRECT"); + + memcpy(string, "123456789", 9); + + calc = crc.CalcCRC(string, 9); + printf("The calcluated crc of \"123456789\" is 0x%x. This result is %s!\n\n", calc, (calc==0x772bu) ? "correct" : "INCORRECT"); + + string[0] = 'A'; + for (int i=0; i<0x100; i++) + string[i] = i; + calc = crc.CalcCRC(string, 256); + printf("The calcluated crc of {0x0..0xff} is 0x%x. This result is %s!\n\n", calc, (calc==0x1c31u) ? "correct" : "INCORRECT"); + + return 0; +} diff --git a/timepoint.cpp b/timepoint.cpp new file mode 100644 index 0000000..724fb6e --- /dev/null +++ b/timepoint.cpp @@ -0,0 +1,53 @@ +// +// ctimepoint.cpp +// m17ref +// +// Created by Jean-Luc Deltombe (LX3JL) on 05/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "timepoint.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CTimePoint::CTimePoint() +{ + m_TimePoint = std::chrono::steady_clock::now(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// operation + +double CTimePoint::DurationSinceNow(void) const +{ + std::chrono::steady_clock::time_point Now = std::chrono::steady_clock::now(); + std::chrono::steady_clock::duration time_span = (Now - m_TimePoint); + return double(time_span.count()) * std::chrono::steady_clock::period::num / std::chrono::steady_clock::period::den; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// task + +void CTimePoint::TaskSleepFor(uint32_t ms) +{ + std::chrono::milliseconds timespan(ms); + std::this_thread::sleep_for(timespan); +} diff --git a/timepoint.h b/timepoint.h new file mode 100644 index 0000000..9efa6b5 --- /dev/null +++ b/timepoint.h @@ -0,0 +1,48 @@ +// +// Created by Jean-Luc Deltombe (LX3JL) on 05/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CTimePoint : public std::chrono::steady_clock::time_point +{ +public: + // constructor + CTimePoint(); + + // destructor + virtual ~CTimePoint() {} + + // operation + void Now(void) { m_TimePoint = std::chrono::steady_clock::now(); } + double DurationSinceNow(void) const; + + // task + static void TaskSleepFor(uint32_t); + +protected: + // data + std::chrono::steady_clock::time_point m_TimePoint; +}; diff --git a/udpsocket.cpp b/udpsocket.cpp new file mode 100644 index 0000000..656816e --- /dev/null +++ b/udpsocket.cpp @@ -0,0 +1,171 @@ +// +// Created by Jean-Luc Deltombe (LX3JL) on 31/10/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include +#include "main.h" +#include "udpsocket.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CUdpSocket::CUdpSocket() : m_fd(-1) {} + +//////////////////////////////////////////////////////////////////////////////////////// +// destructor + +CUdpSocket::~CUdpSocket() +{ + Close(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// open & close + +// returns true on error +bool CUdpSocket::Open(const CIp &Ip) +{ + // check for a vaild family + if (AF_UNSPEC == Ip.GetFamily()) + return true; + + // create socket + m_fd = socket(Ip.GetFamily(), SOCK_DGRAM, 0); + if ( m_fd < 0 ) + { + std::cerr << "Unable to open socket on " << Ip << ", " << strerror(errno) << std::endl; + return false; + } + // initialize sockaddr struct + m_addr = Ip; + + int reuse = 1; + if ( 0 > setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int))) + { + std::cerr << "Cannot set the UDP socket option on " << m_addr << ", " << strerror(errno) << std::endl; + Close(); + return false; + } + + if (fcntl(m_fd, F_SETFL, O_NONBLOCK)) + { + std::cerr << "fcntl set non-blocking failed on " << m_addr << ", " << strerror(errno) << std::endl; + Close(); + return false; + } + + if ( bind(m_fd, m_addr.GetCPointer(), m_addr.GetSize()) ) + { + std::cerr << "bind failed on " << m_addr << ", " << strerror(errno) << std::endl; + Close(); + return false; + } + + if (0 == m_addr.GetPort()) // get the assigned port for an ephemeral port request + { + CIp a; + socklen_t len = sizeof(struct sockaddr_storage); + if (getsockname(m_fd, a.GetPointer(), &len)) + { + std::cerr << "getsockname error " << m_addr << ", " << strerror(errno) << std::endl; + Close(); + return false; + } + if (a != m_addr) + std::cout << "getsockname didn't return the same address as set: returned " << a << ", should have been " << m_addr << std::endl; + + m_addr.SetPort(a.GetPort()); + } + + // done + return true; +} + +void CUdpSocket::Close(void) +{ + if ( m_fd >= 0 ) + { + close(m_fd); + m_fd = -1; + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// read + +ssize_t CUdpSocket::Receive(uint8_t *Buffer, CIp &Ip, int timeout) +{ + // socket valid ? + if ( 0 > m_fd ) + return false; + + // control socket + fd_set FdSet; + FD_ZERO(&FdSet); + FD_SET(m_fd, &FdSet); + struct timeval tv; + tv.tv_sec = timeout / 1000; + tv.tv_usec = (timeout % 1000) * 1000; + + auto rval = select(m_fd + 1, &FdSet, 0, 0, &tv); + if (rval > 0) + return ReceiveFrom(Buffer, Ip); + + if (rval < 0) + std::cerr << "select error on UPD port " << m_addr << ": " << strerror(errno) << std::endl; + + return -1; +} + +ssize_t CUdpSocket::ReceiveFrom(uint8_t *Buffer, CIp &ip) +{ + // read + socklen_t fromsize = sizeof(struct sockaddr_storage); + return recvfrom(m_fd, Buffer, UDP_BUFFER_LENMAX, 0, ip.GetPointer(), &fromsize); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// write + +void CUdpSocket::Send(const char *Buffer, const CIp &Ip) const +{ + sendto(m_fd, Buffer, ::strlen(Buffer), 0, Ip.GetCPointer(), Ip.GetSize()); +} + +void CUdpSocket::Send(const uint8_t *Buffer, size_t size, const CIp &Ip) const +{ + sendto(m_fd, Buffer, size, 0, Ip.GetCPointer(), Ip.GetSize()); +} + +void CUdpSocket::Send(const char *Buffer, const CIp &Ip, uint16_t destport) const +{ + CIp temp(Ip); + temp.SetPort(destport); + sendto(m_fd, Buffer, ::strlen(Buffer), 0, temp.GetCPointer(), temp.GetSize()); +} + +void CUdpSocket::Send(const uint8_t *Buffer, size_t size, const CIp &Ip, uint16_t destport) const +{ + CIp temp(Ip); + temp.SetPort(destport); + sendto(m_fd, Buffer, size, 0, temp.GetCPointer(), temp.GetSize()); +} diff --git a/udpsocket.h b/udpsocket.h new file mode 100644 index 0000000..c64a1e9 --- /dev/null +++ b/udpsocket.h @@ -0,0 +1,75 @@ +// +// Created by Jean-Luc Deltombe (LX3JL) on 31/10/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "ip.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// define + +#define UDP_BUFFER_LENMAX 1024 + + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CUdpSocket +{ +public: + // constructor + CUdpSocket(); + + // destructor + ~CUdpSocket(); + + // open & close + bool Open(const CIp &Ip); + void Close(void); + int GetSocket(void) + { + return m_fd; + } + + // read + ssize_t Receive (uint8_t *, CIp &, int); + ssize_t ReceiveFrom(uint8_t *, CIp &); + + // write + void Send(const char *, const CIp &) const; + void Send(const uint8_t *, size_t, const CIp &) const; + void Send(const char *, const CIp &, uint16_t) const; + void Send(const uint8_t *, size_t, const CIp &, uint16_t) const; + +protected: + // data + int m_fd; + CIp m_addr; +}; diff --git a/user.cpp b/user.cpp new file mode 100644 index 0000000..f683234 --- /dev/null +++ b/user.cpp @@ -0,0 +1,84 @@ +// +// Created by Jean-Luc Deltombe (LX3JL) on 13/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early +// +// ---------------------------------------------------------------------------- +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include + +#include "main.h" +#include "user.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructors + +CUser::CUser() +{ + m_LastHeardTime = std::time(nullptr); +} + +CUser::CUser(const CCallsign &source, const CCallsign &destination, const CCallsign &reflector) +{ + m_Source = source; + m_Destination = destination; + m_Reflector = reflector; + m_LastHeardTime = std::time(nullptr); +} + +CUser::CUser(const CUser &user) +{ + m_Source = user.m_Source; + m_Destination = user.m_Destination; + m_Reflector = user.m_Reflector; + m_LastHeardTime = user.m_LastHeardTime; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// operators + +bool CUser::operator ==(const CUser &user) const +{ + return ((user.m_Source == m_Source) && (user.m_Destination == m_Destination) && (user.m_Reflector == m_Reflector)); +} + + +bool CUser::operator <(const CUser &user) const +{ + // smallest is youngest + return (std::difftime(m_LastHeardTime, user.m_LastHeardTime) > 0); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// reporting + +void CUser::WriteXml(std::ofstream &xmlFile) +{ + xmlFile << "" << std::endl; + xmlFile << "\t" << m_Source << "" << std::endl; + xmlFile << "\t" << m_Destination << "" << std::endl; + xmlFile << "\t" << m_Reflector.GetModule() << "" << std::endl; + xmlFile << "\t" << m_Reflector.GetCS(7) << "" << std::endl; + + char mbstr[100]; + if (std::strftime(mbstr, sizeof(mbstr), "%A %c", std::localtime(&m_LastHeardTime))) + { + xmlFile << "\t" << mbstr << "" << std::endl; + } + xmlFile << "" << std::endl; +} diff --git a/user.h b/user.h new file mode 100644 index 0000000..5ac4022 --- /dev/null +++ b/user.h @@ -0,0 +1,55 @@ +// +// cuser.h +// m17ref +// +// Created by Jean-Luc Deltombe (LX3JL) on 13/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + +#include "callsign.h" + +//////////////////////////////////////////////////////////////////////////////////////// + +class CUser +{ +public: + // constructor + CUser(); + CUser(const CCallsign &, const CCallsign &, const CCallsign &); + CUser(const CUser &); + + // operation + void HeardNow(void) { m_LastHeardTime = std::time(nullptr); } + + // operators + bool operator ==(const CUser &) const; + bool operator <(const CUser &) const; + + // reporting + void WriteXml(std::ofstream &); + +protected: + // data + CCallsign m_Source; + CCallsign m_Destination; + CCallsign m_Reflector; + std::time_t m_LastHeardTime; +}; diff --git a/users.cpp b/users.cpp new file mode 100644 index 0000000..9617321 --- /dev/null +++ b/users.cpp @@ -0,0 +1,71 @@ +// +// cusers.cpp +// m17ref +// +// Created by Jean-Luc Deltombe (LX3JL) on 13/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "users.h" +#include "reflector.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CUsers::CUsers() {} + +//////////////////////////////////////////////////////////////////////////////////////// +// users management + +void CUsers::AddUser(const CUser &user) +{ + // add + m_Users.push_front(user); + + // if list size too big, remove oldest + if ( m_Users.size() >= (LASTHEARD_USERS_MAX_SIZE-1) ) + { + m_Users.resize(m_Users.size()-1); + } + + // notify + g_Reflector.OnUsersChanged(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// operation + +void CUsers::Hearing(const CCallsign &source, const CCallsign &destination, const CCallsign &reflector) +{ + CUser heard(source, destination, reflector); + + // first check if this user is already listed. If so, erase him. + for ( auto it=begin(); it!=end(); it++ ) + { + if (*it == heard) + { + m_Users.erase(it); + break; + } + } + + AddUser(heard); +} diff --git a/users.h b/users.h new file mode 100644 index 0000000..6312d3b --- /dev/null +++ b/users.h @@ -0,0 +1,53 @@ +// +// Created by Jean-Luc Deltombe (LX3JL) on 13/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// Copyright © 2020 Thomas A. Early, N7TAE +// +// ---------------------------------------------------------------------------- +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#pragma once + +#include "user.h" + +//////////////////////////////////////////////////////////////////////////////////////// + +class CUsers +{ +public: + // constructor + CUsers(); + + // locks + void Lock(void) { m_Mutex.lock(); } + void Unlock(void) { m_Mutex.unlock(); } + + // management + int GetSize(void) const { return (int)m_Users.size(); } + void AddUser(const CUser &); + + // pass-thru + std::list::iterator begin() { return m_Users.begin(); } + std::list::iterator end() { return m_Users.end(); } + + // operation + void Hearing(const CCallsign &, const CCallsign &, const CCallsign &); + +protected: + // data + std::mutex m_Mutex; + std::list m_Users; +}; diff --git a/version.cpp b/version.cpp new file mode 100644 index 0000000..c5875ca --- /dev/null +++ b/version.cpp @@ -0,0 +1,79 @@ +// +// cversion.cpp +// m17ref +// +// Created by Jean-Luc Deltombe (LX3JL) on 05/01/2018. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "version.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CVersion::CVersion() +{ + m_iMajor = 0; + m_iMinor = 0; + m_iRevision = 0; +} + +CVersion::CVersion(int iMajor, int iMinor, int iRevision) +{ + m_iMajor = iMajor; + m_iMinor = iMinor; + m_iRevision = iRevision; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// comparaison + +bool CVersion::IsEqualOrHigherTo(const CVersion &version) const +{ + if ( m_iMajor > version.m_iMajor ) + { + return true; + } + else if ( m_iMajor == version.m_iMajor ) + { + if ( m_iMinor > version.m_iMinor ) + { + return true; + } + else if ( m_iMinor == version.m_iMinor ) + { + if ( m_iRevision >= version.m_iRevision ) + { + return true; + } + } + } + return false; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// operator + +bool CVersion::operator ==(const CVersion &Version) const +{ + return ( (Version.m_iMajor == m_iMajor) && + (Version.m_iMinor == m_iMinor) && + (Version.m_iRevision == m_iRevision )) ; +} diff --git a/version.h b/version.h new file mode 100644 index 0000000..0b5613a --- /dev/null +++ b/version.h @@ -0,0 +1,60 @@ +// +// cversion.h +// m17ref +// +// Created by Jean-Luc Deltombe (LX3JL) on 05/01/2018. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of m17ref. +// +// m17ref 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. +// +// m17ref 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 +// with this software. If not, see . +// ---------------------------------------------------------------------------- + + +#ifndef cversion_h +#define cversion_h + + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CVersion +{ +public: + // constructor + CVersion(); + CVersion(int, int, int); + + // get + int GetMajor(void) const { return m_iMajor; } + int GetMinor(void) const { return m_iMinor; } + int GetRevision(void) const { return m_iRevision; } + + // comparaison + bool IsEqualOrHigherTo(const CVersion &) const; + + // operator + bool operator ==(const CVersion &) const; + +protected: + // data + int m_iMajor; + int m_iMinor; + int m_iRevision; +}; + + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cversion_h */