From: Sergey Matveev Date: Fri, 6 Jan 2017 11:06:21 +0000 (+0300) Subject: Initial X-Git-Tag: 0.1~43 X-Git-Url: http://www.git.cypherpunks.ru/?p=nncp.git;a=commitdiff_plain;h=d1cd3a4bf2dac997edea5a76bccad6e0c9e2f65f Initial --- d1cd3a4bf2dac997edea5a76bccad6e0c9e2f65f diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..bfa3d31 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,35 @@ +[submodule "src/github.com/davecgh/go-xdr"] + path = src/github.com/davecgh/go-xdr + url = https://github.com/davecgh/go-xdr.git +[submodule "src/github.com/devi/blake2"] + path = src/github.com/devi/blake2 + url = https://github.com/devi/blake2.git +[submodule "src/github.com/dustin/go-humanize"] + path = src/github.com/dustin/go-humanize + url = https://github.com/dustin/go-humanize.git +[submodule "src/github.com/flynn/noise"] + path = src/github.com/flynn/noise + url = https://github.com/flynn/noise.git +[submodule "src/github.com/minio/blake2b-simd"] + path = src/github.com/minio/blake2b-simd + url = https://github.com/minio/blake2b-simd.git +[submodule "src/gopkg.in/check.v1"] + path = src/gopkg.in/check.v1 + url = https://github.com/go-check/check.git + branch = v1 +[submodule "src/gopkg.in/yaml.v2"] + path = src/gopkg.in/yaml.v2 + url = https://github.com/go-yaml/yaml.git + branch = v2 +[submodule "src/golang.org/x/crypto"] + path = src/golang.org/x/crypto + url = https://go.googlesource.com/crypto +[submodule "src/golang.org/x/sys"] + path = src/golang.org/x/sys + url = https://go.googlesource.com/sys +[submodule "src/golang.org/x/net"] + path = src/golang.org/x/net + url = https://go.googlesource.com/net +[submodule "src/github.com/devi/chap"] + path = src/github.com/devi/chap + url = https://github.com/devi/chap.git diff --git a/BSDmakefile b/BSDmakefile new file mode 100644 index 0000000..9edf8cd --- /dev/null +++ b/BSDmakefile @@ -0,0 +1,6 @@ +GOPATH != pwd +VERSION != cat VERSION +CFGPATH ?= /usr/local/etc/nncp.yaml +SENDMAIL ?= /usr/sbin/sendmail + +include common.mk diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..9a2708d --- /dev/null +++ b/COPYING @@ -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/VERSION b/VERSION new file mode 100644 index 0000000..49d5957 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.1 diff --git a/common.mk b/common.mk new file mode 100644 index 0000000..78ba42c --- /dev/null +++ b/common.mk @@ -0,0 +1,76 @@ +.PHONY: doc + +LDFLAGS = \ + -X cypherpunks.ru/nncp.Version=$(VERSION) \ + -X cypherpunks.ru/nncp.DefaultCfgPath=$(CFGPATH) \ + -X cypherpunks.ru/nncp.DefaultSendmailPath=$(SENDMAIL) + +all: \ + nncp-call \ + nncp-check \ + nncp-daemon \ + nncp-file \ + nncp-freq \ + nncp-log \ + nncp-mail \ + nncp-newnode \ + nncp-pkt \ + nncp-stat \ + nncp-toss \ + nncp-xfer + +nncp-call: + GOPATH=$(GOPATH) go build -ldflags "$(LDFLAGS)" cypherpunks.ru/nncp/cmd/nncp-call + +nncp-check: + GOPATH=$(GOPATH) go build -ldflags "$(LDFLAGS)" cypherpunks.ru/nncp/cmd/nncp-check + +nncp-daemon: + GOPATH=$(GOPATH) go build -ldflags "$(LDFLAGS)" cypherpunks.ru/nncp/cmd/nncp-daemon + +nncp-file: + GOPATH=$(GOPATH) go build -ldflags "$(LDFLAGS)" cypherpunks.ru/nncp/cmd/nncp-file + +nncp-freq: + GOPATH=$(GOPATH) go build -ldflags "$(LDFLAGS)" cypherpunks.ru/nncp/cmd/nncp-freq + +nncp-log: + GOPATH=$(GOPATH) go build -ldflags "$(LDFLAGS)" cypherpunks.ru/nncp/cmd/nncp-log + +nncp-mail: + GOPATH=$(GOPATH) go build -ldflags "$(LDFLAGS)" cypherpunks.ru/nncp/cmd/nncp-mail + +nncp-newnode: + GOPATH=$(GOPATH) go build -ldflags "$(LDFLAGS)" cypherpunks.ru/nncp/cmd/nncp-newnode + +nncp-pkt: + GOPATH=$(GOPATH) go build -ldflags "$(LDFLAGS)" cypherpunks.ru/nncp/cmd/nncp-pkt + +nncp-stat: + GOPATH=$(GOPATH) go build -ldflags "$(LDFLAGS)" cypherpunks.ru/nncp/cmd/nncp-stat + +nncp-toss: + GOPATH=$(GOPATH) go build -ldflags "$(LDFLAGS)" cypherpunks.ru/nncp/cmd/nncp-toss + +nncp-xfer: + GOPATH=$(GOPATH) go build -ldflags "$(LDFLAGS)" cypherpunks.ru/nncp/cmd/nncp-xfer + +test: + GOPATH=$(GOPATH) go test cypherpunks.ru/nncp/... + +clean: + rm -f \ + nncp-call \ + nncp-daemon \ + nncp-file \ + nncp-freq \ + nncp-log \ + nncp-mail \ + nncp-newnode \ + nncp-pkt \ + nncp-stat \ + nncp-toss \ + nncp-xfer + +doc: + $(MAKE) -C doc diff --git a/src/cypherpunks.ru/nncp/base32.go b/src/cypherpunks.ru/nncp/base32.go new file mode 100644 index 0000000..0f7db5b --- /dev/null +++ b/src/cypherpunks.ru/nncp/base32.go @@ -0,0 +1,23 @@ +package nncp + +import ( + "encoding/base32" + "strings" +) + +func ToBase32(data []byte) string { + return strings.TrimRight(base32.StdEncoding.EncodeToString(data), "=") +} + +func FromBase32(data string) ([]byte, error) { + padSize := len(data) % 8 + if padSize != 0 { + padSize = 8 - padSize + pad := make([]byte, 0, padSize) + for i := 0; i < padSize; i++ { + pad = append(pad, '=') + } + data += string(pad) + } + return base32.StdEncoding.DecodeString(data) +} diff --git a/src/cypherpunks.ru/nncp/cfg.go b/src/cypherpunks.ru/nncp/cfg.go new file mode 100644 index 0000000..bb6c520 --- /dev/null +++ b/src/cypherpunks.ru/nncp/cfg.go @@ -0,0 +1,283 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +package nncp + +import ( + "errors" + "path" + + "golang.org/x/crypto/ed25519" + "gopkg.in/yaml.v2" +) + +var ( + DefaultCfgPath string = "/usr/local/etc/nncp.yaml" + DefaultSendmailPath string = "/usr/sbin/sendmail" +) + +type NodeYAML struct { + Id string + ExchPub string + SignPub string + NoisePub string + Incoming *string `incoming,omitempty` + Freq *string `freq,omitempty` + Via []string `via,omitempty` +} + +type NodeOurYAML struct { + Id string + ExchPub string + ExchPrv string + SignPub string + SignPrv string + NoisePrv string + NoisePub string +} + +type FromToYAML struct { + From string + To string +} + +type NotifyYAML struct { + File *FromToYAML `file,omitempty` + Freq *FromToYAML `freq,omitempty` +} + +type CfgYAML struct { + Self NodeOurYAML + Neigh map[string]NodeYAML + + Spool string + Log string + Sendmail []string + Notify *NotifyYAML `notify,omitempty` +} + +func NewNode(name string, yml NodeYAML) (*Node, error) { + nodeId, err := NodeIdFromString(yml.Id) + if err != nil { + return nil, err + } + + exchPub, err := FromBase32(yml.ExchPub) + if err != nil { + return nil, err + } + if len(exchPub) != 32 { + return nil, errors.New("Invalid exchPub size") + } + + signPub, err := FromBase32(yml.SignPub) + if err != nil { + return nil, err + } + if len(signPub) != ed25519.PublicKeySize { + return nil, errors.New("Invalid signPub size") + } + + noisePub, err := FromBase32(yml.NoisePub) + if err != nil { + return nil, err + } + if len(noisePub) != 32 { + return nil, errors.New("Invalid noisePub size") + } + + var incoming *string + if yml.Incoming != nil { + inc := path.Clean(*yml.Incoming) + if !path.IsAbs(inc) { + return nil, errors.New("Incoming path must be absolute") + } + incoming = &inc + } + + var freq *string + if yml.Freq != nil { + fr := path.Clean(*yml.Freq) + if !path.IsAbs(fr) { + return nil, errors.New("Freq path must be absolute") + } + freq = &fr + } + + node := Node{ + Name: name, + Id: nodeId, + ExchPub: new([32]byte), + SignPub: ed25519.PublicKey(signPub), + NoisePub: new([32]byte), + Incoming: incoming, + Freq: freq, + } + copy(node.ExchPub[:], exchPub) + copy(node.NoisePub[:], noisePub) + return &node, nil +} + +func NewNodeOur(yml NodeOurYAML) (*NodeOur, error) { + id, err := NodeIdFromString(yml.Id) + if err != nil { + return nil, err + } + + exchPub, err := FromBase32(yml.ExchPub) + if err != nil { + return nil, err + } + if len(exchPub) != 32 { + return nil, errors.New("Invalid exchPub size") + } + + exchPrv, err := FromBase32(yml.ExchPrv) + if err != nil { + return nil, err + } + if len(exchPrv) != 32 { + return nil, errors.New("Invalid exchPrv size") + } + + signPub, err := FromBase32(yml.SignPub) + if err != nil { + return nil, err + } + if len(signPub) != ed25519.PublicKeySize { + return nil, errors.New("Invalid signPub size") + } + + signPrv, err := FromBase32(yml.SignPrv) + if err != nil { + return nil, err + } + if len(signPrv) != ed25519.PrivateKeySize { + return nil, errors.New("Invalid signPrv size") + } + + noisePub, err := FromBase32(yml.NoisePub) + if err != nil { + return nil, err + } + if len(noisePub) != 32 { + return nil, errors.New("Invalid noisePub size") + } + + noisePrv, err := FromBase32(yml.NoisePrv) + if err != nil { + return nil, err + } + if len(noisePrv) != 32 { + return nil, errors.New("Invalid noisePrv size") + } + + node := NodeOur{ + Id: id, + ExchPub: new([32]byte), + ExchPrv: new([32]byte), + SignPub: ed25519.PublicKey(signPub), + SignPrv: ed25519.PrivateKey(signPrv), + NoisePub: new([32]byte), + NoisePrv: new([32]byte), + } + copy(node.ExchPub[:], exchPub) + copy(node.ExchPrv[:], exchPrv) + copy(node.NoisePub[:], noisePub) + copy(node.NoisePrv[:], noisePrv) + return &node, nil +} + +func (nodeOur *NodeOur) ToYAML() string { + yml := NodeOurYAML{ + Id: nodeOur.Id.String(), + ExchPub: ToBase32(nodeOur.ExchPub[:]), + ExchPrv: ToBase32(nodeOur.ExchPrv[:]), + SignPub: ToBase32(nodeOur.SignPub[:]), + SignPrv: ToBase32(nodeOur.SignPrv[:]), + NoisePub: ToBase32(nodeOur.NoisePub[:]), + NoisePrv: ToBase32(nodeOur.NoisePrv[:]), + } + raw, err := yaml.Marshal(&yml) + if err != nil { + panic(err) + } + return string(raw) +} + +func CfgParse(data []byte) (*Ctx, error) { + var cfgYAML CfgYAML + err := yaml.Unmarshal(data, &cfgYAML) + if err != nil { + return nil, err + } + self, err := NewNodeOur(cfgYAML.Self) + if err != nil { + return nil, err + } + spoolPath := path.Clean(cfgYAML.Spool) + if !path.IsAbs(spoolPath) { + return nil, errors.New("Spool path must be absolute") + } + logPath := path.Clean(cfgYAML.Log) + if !path.IsAbs(logPath) { + return nil, errors.New("Log path must be absolute") + } + ctx := Ctx{ + Spool: spoolPath, + LogPath: logPath, + Self: self, + Neigh: make(map[NodeId]*Node, len(cfgYAML.Neigh)), + Alias: make(map[string]*NodeId), + Sendmail: cfgYAML.Sendmail, + } + if cfgYAML.Notify != nil { + if cfgYAML.Notify.File != nil { + ctx.NotifyFile = cfgYAML.Notify.File + } + if cfgYAML.Notify.Freq != nil { + ctx.NotifyFreq = cfgYAML.Notify.Freq + } + } + vias := make(map[NodeId][]string) + for name, neighYAML := range cfgYAML.Neigh { + neigh, err := NewNode(name, neighYAML) + if err != nil { + return nil, err + } + ctx.Neigh[*neigh.Id] = neigh + if _, already := ctx.Alias[name]; already { + return nil, errors.New("Node names conflict") + } + ctx.Alias[name] = neigh.Id + vias[*neigh.Id] = neighYAML.Via + } + for neighId, viasRaw := range vias { + for _, viaRaw := range viasRaw { + foundNodeId, err := ctx.FindNode(viaRaw) + if err != nil { + return nil, err + } + ctx.Neigh[neighId].Via = append( + ctx.Neigh[neighId].Via, + foundNodeId.Id, + ) + } + } + return &ctx, nil +} diff --git a/src/cypherpunks.ru/nncp/check.go b/src/cypherpunks.ru/nncp/check.go new file mode 100644 index 0000000..07732b4 --- /dev/null +++ b/src/cypherpunks.ru/nncp/check.go @@ -0,0 +1,61 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +package nncp + +import ( + "bufio" + "bytes" + "io" + "log" + + "golang.org/x/crypto/blake2b" +) + +func Check(src io.Reader, checksum []byte) (bool, error) { + hsh, err := blake2b.New256(nil) + if err != nil { + log.Fatalln(err) + } + if _, err = io.Copy(hsh, bufio.NewReader(src)); err != nil { + return false, err + } + return bytes.Compare(hsh.Sum(nil), checksum) == 0, nil +} + +func (ctx *Ctx) checkXx(nodeId *NodeId, xx TRxTx) bool { + isBad := false + for job := range ctx.Jobs(nodeId, xx) { + sds := SDS{"xx": string(xx), "node": nodeId, "pkt": job.Fd.Name()} + gut, err := Check(job.Fd, job.HshValue[:]) + job.Fd.Close() + if err != nil { + ctx.LogE("toss-check", SdsAdd(sds, SDS{"err": err}), "") + return false + } + if !gut { + isBad = true + ctx.LogE("toss-check", sds, "bad") + } + } + return isBad +} + +func (ctx *Ctx) Check(nodeId *NodeId) bool { + return ctx.checkXx(nodeId, TRx) || ctx.checkXx(nodeId, TTx) +} diff --git a/src/cypherpunks.ru/nncp/cmd/nncp-call/main.go b/src/cypherpunks.ru/nncp/cmd/nncp-call/main.go new file mode 100644 index 0000000..4a25e21 --- /dev/null +++ b/src/cypherpunks.ru/nncp/cmd/nncp-call/main.go @@ -0,0 +1,115 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +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 . +*/ + +// Call NNCP TCP daemon +package main + +import ( + "flag" + "fmt" + "io/ioutil" + "log" + "net" + "os" + "strconv" + + "cypherpunks.ru/nncp" +) + +func usage() { + fmt.Fprintf(os.Stderr, nncp.UsageHeader()) + fmt.Fprintln(os.Stderr, "nncp-call -- call TCP daemon\n") + fmt.Fprintln(os.Stderr, "Usage: %s [options] NODE ADDR\nOptions:", os.Args[0]) + flag.PrintDefaults() +} + +func main() { + var ( + cfgPath = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file") + niceRaw = flag.Int("nice", 255, "Minimal required niceness") + rxOnly = flag.Bool("rx", false, "Only receive packets") + txOnly = flag.Bool("tx", false, "Only transfer packets") + debug = flag.Bool("debug", false, "Enable debugging information") + version = flag.Bool("version", false, "Print version information") + warranty = flag.Bool("warranty", false, "Print warranty information") + ) + flag.Usage = usage + flag.Parse() + if *warranty { + fmt.Println(nncp.Warranty) + return + } + if *version { + fmt.Println(nncp.VersionGet()) + return + } + if flag.NArg() != 2 { + usage() + os.Exit(1) + } + if *niceRaw < 1 || *niceRaw > 255 { + log.Fatalln("-nice must be between 1 and 255") + } + nice := uint8(*niceRaw) + if *rxOnly && *txOnly { + log.Fatalln("-rx and -tx can not be set simultaneously") + } + + cfgRaw, err := ioutil.ReadFile(*cfgPath) + if err != nil { + log.Fatalln("Can not read config:", err) + } + ctx, err := nncp.CfgParse(cfgRaw) + if err != nil { + log.Fatalln("Can not parse config:", err) + } + ctx.Debug = *debug + + node, err := ctx.FindNode(flag.Arg(0)) + if err != nil { + log.Fatalln("Invalid NODE specified:", err) + } + + conn, err := net.Dial("tcp", flag.Arg(1)) + if err != nil { + log.Fatalln("Can not connect:", err) + } + ctx.LogD("call", nncp.SDS{"addr": flag.Arg(1)}, "connected") + var xxOnly nncp.TRxTx + if *rxOnly { + xxOnly = nncp.TRx + } else if *txOnly { + xxOnly = nncp.TTx + } + state, err := ctx.StartI(conn, node.Id, nice, &xxOnly) + if err == nil { + ctx.LogI("call-start", nncp.SDS{"node": state.NodeId}, "connected") + state.Wait() + ctx.LogI("call-finish", nncp.SDS{ + "node": state.NodeId, + "duration": strconv.FormatInt(int64(state.Duration.Seconds()), 10), + "rxbytes": strconv.FormatInt(state.RxBytes, 10), + "txbytes": strconv.FormatInt(state.TxBytes, 10), + "rxspeed": strconv.FormatInt(state.RxSpeed, 10), + "txspeed": strconv.FormatInt(state.TxSpeed, 10), + }, "") + } else { + ctx.LogE("call-start", nncp.SDS{"node": state.NodeId, "err": err}, "") + } + conn.Close() +} diff --git a/src/cypherpunks.ru/nncp/cmd/nncp-check/main.go b/src/cypherpunks.ru/nncp/cmd/nncp-check/main.go new file mode 100644 index 0000000..9eac639 --- /dev/null +++ b/src/cypherpunks.ru/nncp/cmd/nncp-check/main.go @@ -0,0 +1,87 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +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 . +*/ + +// Verify NNCP Rx/Tx packets checksum +package main + +import ( + "flag" + "fmt" + "io/ioutil" + "log" + "os" + + "cypherpunks.ru/nncp" +) + +func usage() { + fmt.Fprintf(os.Stderr, nncp.UsageHeader()) + fmt.Fprintln(os.Stderr, "nncp-check -- verify Rx/Tx packets checksum\n") + fmt.Fprintln(os.Stderr, "Usage: %s [options]\nOptions:", os.Args[0]) + flag.PrintDefaults() +} + +func main() { + var ( + cfgPath = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file") + nodeRaw = flag.String("node", "", "Process only that node") + debug = flag.Bool("debug", false, "Enable debugging information") + version = flag.Bool("version", false, "Print version information") + warranty = flag.Bool("warranty", false, "Print warranty information") + ) + flag.Usage = usage + flag.Parse() + if *warranty { + fmt.Println(nncp.Warranty) + return + } + if *version { + fmt.Println(nncp.VersionGet()) + return + } + + cfgRaw, err := ioutil.ReadFile(*cfgPath) + if err != nil { + log.Fatalln("Can not read config:", err) + } + ctx, err := nncp.CfgParse(cfgRaw) + if err != nil { + log.Fatalln("Can not parse config:", err) + } + ctx.Debug = *debug + + var nodeOnly *nncp.Node + if *nodeRaw != "" { + nodeOnly, err = ctx.FindNode(*nodeRaw) + if err != nil { + log.Fatalln("Invalid -node specified:", err) + } + } + + checkIsBad := false + for nodeId, node := range ctx.Neigh { + if nodeOnly != nil && nodeId != *nodeOnly.Id { + continue + } + checkIsBad = checkIsBad || ctx.Check(node.Id) + } + + if checkIsBad { + os.Exit(1) + } +} diff --git a/src/cypherpunks.ru/nncp/cmd/nncp-daemon/main.go b/src/cypherpunks.ru/nncp/cmd/nncp-daemon/main.go new file mode 100644 index 0000000..90b467d --- /dev/null +++ b/src/cypherpunks.ru/nncp/cmd/nncp-daemon/main.go @@ -0,0 +1,108 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +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 . +*/ + +// NNCP TCP daemon +package main + +import ( + "flag" + "fmt" + "io/ioutil" + "log" + "net" + "os" + "strconv" + + "cypherpunks.ru/nncp" + "golang.org/x/net/netutil" +) + +func usage() { + fmt.Fprintf(os.Stderr, nncp.UsageHeader()) + fmt.Fprintln(os.Stderr, "nncp-daemon -- TCP daemon\n") + fmt.Fprintln(os.Stderr, "Usage: %s [options]\nOptions:", os.Args[0]) + flag.PrintDefaults() +} + +func main() { + var ( + cfgPath = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file") + niceRaw = flag.Int("nice", 255, "Minimal required niceness") + bind = flag.String("bind", ":5400", "Address to bind to") + maxConn = flag.Int("maxconn", 128, "Maximal number of simultaneous connections") + debug = flag.Bool("debug", false, "Enable debugging information") + version = flag.Bool("version", false, "Print version information") + warranty = flag.Bool("warranty", false, "Print warranty information") + ) + flag.Usage = usage + flag.Parse() + if *warranty { + fmt.Println(nncp.Warranty) + return + } + if *version { + fmt.Println(nncp.VersionGet()) + return + } + if *niceRaw < 1 || *niceRaw > 255 { + log.Fatalln("-nice must be between 1 and 255") + } + nice := uint8(*niceRaw) + + cfgRaw, err := ioutil.ReadFile(*cfgPath) + if err != nil { + log.Fatalln("Can not read config:", err) + } + ctx, err := nncp.CfgParse(cfgRaw) + if err != nil { + log.Fatalln("Can not parse config:", err) + } + ctx.Debug = *debug + + ln, err := net.Listen("tcp", *bind) + if err != nil { + log.Fatalln("Can not listen:", err) + } + ln = netutil.LimitListener(ln, *maxConn) + ctx.LogI("daemon", nncp.SDS{"bind": *bind}, "listening") + for { + conn, err := ln.Accept() + if err != nil { + log.Fatalln("Can not accept connection:", err) + } + ctx.LogD("daemon", nncp.SDS{"addr": conn.RemoteAddr()}, "accepted") + go func(conn net.Conn) { + state, err := ctx.StartR(conn, nice, nil) + if err == nil { + ctx.LogI("call-start", nncp.SDS{"node": state.NodeId}, "connected") + state.Wait() + ctx.LogI("call-finish", nncp.SDS{ + "node": state.NodeId, + "duration": strconv.FormatInt(int64(state.Duration.Seconds()), 10), + "rxbytes": strconv.FormatInt(state.RxBytes, 10), + "txbytes": strconv.FormatInt(state.TxBytes, 10), + "rxspeed": strconv.FormatInt(state.RxSpeed, 10), + "txspeed": strconv.FormatInt(state.TxSpeed, 10), + }, "") + } else { + ctx.LogE("call-start", nncp.SDS{"node": state.NodeId, "err": err}, "") + } + conn.Close() + }(conn) + } +} diff --git a/src/cypherpunks.ru/nncp/cmd/nncp-file/main.go b/src/cypherpunks.ru/nncp/cmd/nncp-file/main.go new file mode 100644 index 0000000..6730a26 --- /dev/null +++ b/src/cypherpunks.ru/nncp/cmd/nncp-file/main.go @@ -0,0 +1,90 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +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 . +*/ + +// Send file via NNCP +package main + +import ( + "flag" + "fmt" + "io/ioutil" + "log" + "os" + "strings" + + "cypherpunks.ru/nncp" +) + +func usage() { + fmt.Fprintf(os.Stderr, nncp.UsageHeader()) + fmt.Fprintln(os.Stderr, "nncp-file -- send file\n") + fmt.Fprintln(os.Stderr, "Usage: %s [options] SRC NODE:DST\nOptions:", os.Args[0]) + flag.PrintDefaults() +} + +func main() { + var ( + cfgPath = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file") + niceRaw = flag.Int("nice", nncp.DefaultNiceMail, "Outbound packet niceness") + debug = flag.Bool("debug", false, "Enable debugging information") + version = flag.Bool("version", false, "Print version information") + warranty = flag.Bool("warranty", false, "Print warranty information") + ) + flag.Usage = usage + flag.Parse() + if *warranty { + fmt.Println(nncp.Warranty) + return + } + if *version { + fmt.Println(nncp.VersionGet()) + return + } + if flag.NArg() != 2 { + usage() + os.Exit(1) + } + if *niceRaw < 1 || *niceRaw > 255 { + log.Fatalln("-nice must be between 1 and 255") + } + nice := uint8(*niceRaw) + + cfgRaw, err := ioutil.ReadFile(*cfgPath) + if err != nil { + log.Fatalln("Can not read config:", err) + } + ctx, err := nncp.CfgParse(cfgRaw) + if err != nil { + log.Fatalln("Can not parse config:", err) + } + ctx.Debug = *debug + + splitted := strings.SplitN(flag.Arg(1), ":", 2) + if len(splitted) != 2 { + usage() + os.Exit(1) + } + node, err := ctx.FindNode(splitted[0]) + if err != nil { + log.Fatalln("Invalid NODE specified:", err) + } + + if err = ctx.TxFile(node, nice, flag.Arg(0), splitted[1]); err != nil { + log.Fatalln(err) + } +} diff --git a/src/cypherpunks.ru/nncp/cmd/nncp-freq/main.go b/src/cypherpunks.ru/nncp/cmd/nncp-freq/main.go new file mode 100644 index 0000000..64db25a --- /dev/null +++ b/src/cypherpunks.ru/nncp/cmd/nncp-freq/main.go @@ -0,0 +1,90 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +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 . +*/ + +// Send file request via NNCP +package main + +import ( + "flag" + "fmt" + "io/ioutil" + "log" + "os" + "strings" + + "cypherpunks.ru/nncp" +) + +func usage() { + fmt.Fprintf(os.Stderr, nncp.UsageHeader()) + fmt.Fprintln(os.Stderr, "nncp-freq -- send file request\n") + fmt.Fprintln(os.Stderr, "Usage: %s [options] NODE:SRC DST\nOptions:", os.Args[0]) + flag.PrintDefaults() +} + +func main() { + var ( + cfgPath = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file") + niceRaw = flag.Int("nice", nncp.DefaultNiceMail, "Outbound packet niceness") + debug = flag.Bool("debug", false, "Enable debugging information") + version = flag.Bool("version", false, "Print version information") + warranty = flag.Bool("warranty", false, "Print warranty information") + ) + flag.Usage = usage + flag.Parse() + if *warranty { + fmt.Println(nncp.Warranty) + return + } + if *version { + fmt.Println(nncp.VersionGet()) + return + } + if flag.NArg() != 2 { + usage() + os.Exit(1) + } + if *niceRaw < 1 || *niceRaw > 255 { + log.Fatalln("-nice must be between 1 and 255") + } + nice := uint8(*niceRaw) + + cfgRaw, err := ioutil.ReadFile(*cfgPath) + if err != nil { + log.Fatalln("Can not read config:", err) + } + ctx, err := nncp.CfgParse(cfgRaw) + if err != nil { + log.Fatalln("Can not parse config:", err) + } + ctx.Debug = *debug + + splitted := strings.SplitN(flag.Arg(0), ":", 2) + if len(splitted) != 2 { + usage() + os.Exit(1) + } + node, err := ctx.FindNode(splitted[0]) + if err != nil { + log.Fatalln("Invalid NODE specified:", err) + } + + if err = ctx.TxFreq(node, nice, splitted[1], flag.Arg(1)); err != nil { + log.Fatalln(err) + } +} diff --git a/src/cypherpunks.ru/nncp/cmd/nncp-log/main.go b/src/cypherpunks.ru/nncp/cmd/nncp-log/main.go new file mode 100644 index 0000000..4ca8c84 --- /dev/null +++ b/src/cypherpunks.ru/nncp/cmd/nncp-log/main.go @@ -0,0 +1,82 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +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 . +*/ + +// Read NNCP logs +package main + +import ( + "bufio" + "flag" + "fmt" + "io/ioutil" + "log" + "os" + + "cypherpunks.ru/nncp" +) + +func usage() { + fmt.Fprintf(os.Stderr, nncp.UsageHeader()) + fmt.Fprintln(os.Stderr, "nncp-log -- read logs\n") + fmt.Fprintln(os.Stderr, "Usage: %s [options]\nOptions:", os.Args[0]) + flag.PrintDefaults() +} + +func main() { + var ( + cfgPath = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file") + debug = flag.Bool("debug", false, "Enable debugging information") + version = flag.Bool("version", false, "Print version information") + warranty = flag.Bool("warranty", false, "Print warranty information") + ) + flag.Usage = usage + flag.Parse() + if *warranty { + fmt.Println(nncp.Warranty) + return + } + if *version { + fmt.Println(nncp.VersionGet()) + return + } + + cfgRaw, err := ioutil.ReadFile(*cfgPath) + if err != nil { + log.Fatalln("Can not read config:", err) + } + ctx, err := nncp.CfgParse(cfgRaw) + if err != nil { + log.Fatalln("Can not parse config:", err) + } + + fd, err := os.Open(ctx.LogPath) + if err != nil { + log.Fatalln("Can not open log:", err) + } + scanner := bufio.NewScanner(fd) + for scanner.Scan() { + t := scanner.Text() + if *debug { + fmt.Println(t) + } + fmt.Println(ctx.Humanize(t)) + } + if err = scanner.Err(); err != nil { + log.Fatalln("Can not read log:", err) + } +} diff --git a/src/cypherpunks.ru/nncp/cmd/nncp-mail/main.go b/src/cypherpunks.ru/nncp/cmd/nncp-mail/main.go new file mode 100644 index 0000000..5c7d16b --- /dev/null +++ b/src/cypherpunks.ru/nncp/cmd/nncp-mail/main.go @@ -0,0 +1,92 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +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 . +*/ + +// Send email via NNCP +package main + +import ( + "bufio" + "flag" + "fmt" + "io/ioutil" + "log" + "os" + "strings" + + "cypherpunks.ru/nncp" +) + +func usage() { + fmt.Fprintf(os.Stderr, nncp.UsageHeader()) + fmt.Fprintln(os.Stderr, "nncp-mail -- send email\n") + fmt.Fprintln(os.Stderr, "Usage: %s [options] NODE USER ...\nOptions:", os.Args[0]) + flag.PrintDefaults() + fmt.Fprintln(os.Stderr, "Email body is read from stdin.") +} + +func main() { + var ( + cfgPath = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file") + niceRaw = flag.Int("nice", nncp.DefaultNiceMail, "Outbound packet niceness") + debug = flag.Bool("debug", false, "Enable debugging information") + version = flag.Bool("version", false, "Print version information") + warranty = flag.Bool("warranty", false, "Print warranty information") + ) + flag.Usage = usage + flag.Parse() + if *warranty { + fmt.Println(nncp.Warranty) + return + } + if *version { + fmt.Println(nncp.VersionGet()) + return + } + if flag.NArg() < 2 { + usage() + os.Exit(1) + } + if *niceRaw < 1 || *niceRaw > 255 { + log.Fatalln("-nice must be between 1 and 255") + } + nice := uint8(*niceRaw) + + cfgRaw, err := ioutil.ReadFile(*cfgPath) + if err != nil { + log.Fatalln("Can not read config:", err) + } + ctx, err := nncp.CfgParse(cfgRaw) + if err != nil { + log.Fatalln("Can not parse config:", err) + } + ctx.Debug = *debug + + node, err := ctx.FindNode(flag.Arg(0)) + if err != nil { + log.Fatalln("Invalid NODE specified:", err) + } + + body, err := ioutil.ReadAll(bufio.NewReader(os.Stdin)) + if err != nil { + log.Fatalln("Can not read mail body from stdin:", err) + } + + if err = ctx.TxMail(node, nice, strings.Join(flag.Args()[1:], " "), body); err != nil { + log.Fatalln(err) + } +} diff --git a/src/cypherpunks.ru/nncp/cmd/nncp-newnode/main.go b/src/cypherpunks.ru/nncp/cmd/nncp-newnode/main.go new file mode 100644 index 0000000..feee10a --- /dev/null +++ b/src/cypherpunks.ru/nncp/cmd/nncp-newnode/main.go @@ -0,0 +1,97 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +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 . +*/ + +// Generate new NNCP node keys +package main + +import ( + "flag" + "fmt" + "os" + + "cypherpunks.ru/nncp" + "gopkg.in/yaml.v2" +) + +func usage() { + fmt.Fprintf(os.Stderr, nncp.UsageHeader()) + fmt.Fprintln(os.Stderr, "nncp-newnode -- generate new node keys\nOptions:") + flag.PrintDefaults() +} + +func main() { + var ( + version = flag.Bool("version", false, "Print version information") + warranty = flag.Bool("warranty", false, "Print warranty information") + ) + flag.Usage = usage + flag.Parse() + if *warranty { + fmt.Println(nncp.Warranty) + return + } + if *version { + fmt.Println(nncp.VersionGet()) + return + } + nodeOur, err := nncp.NewNodeGenerate() + if err != nil { + panic(err) + } + incoming := "/path/to/upload/dir, omit it to forbid uploading" + freq := "/path/to/freq/able/dir, omit to forbid freqing" + cfg := nncp.CfgYAML{ + Self: nncp.NodeOurYAML{ + Id: nodeOur.Id.String(), + ExchPub: nncp.ToBase32(nodeOur.ExchPub[:]), + ExchPrv: nncp.ToBase32(nodeOur.ExchPrv[:]), + SignPub: nncp.ToBase32(nodeOur.SignPub[:]), + SignPrv: nncp.ToBase32(nodeOur.SignPrv[:]), + NoisePub: nncp.ToBase32(nodeOur.NoisePub[:]), + NoisePrv: nncp.ToBase32(nodeOur.NoisePrv[:]), + }, + Neigh: map[string]nncp.NodeYAML{ + "myself": nncp.NodeYAML{ + Id: nodeOur.Id.String(), + ExchPub: nncp.ToBase32(nodeOur.ExchPub[:]), + SignPub: nncp.ToBase32(nodeOur.SignPub[:]), + NoisePub: nncp.ToBase32(nodeOur.NoisePub[:]), + Incoming: &incoming, + Freq: &freq, + }, + }, + Spool: "/path/to/spool", + Log: "/path/to/log.file", + Sendmail: []string{nncp.DefaultSendmailPath}, + Notify: &nncp.NotifyYAML{ + File: &nncp.FromToYAML{ + From: "nncp@localhost", + To: "root@localhost, delete section to disable notifies", + }, + Freq: &nncp.FromToYAML{ + From: "nncp@localhost", + To: "root@localhost, delete section to disable notifies", + }, + }, + } + raw, err := yaml.Marshal(&cfg) + if err != nil { + panic(err) + } + fmt.Print(string(raw)) +} diff --git a/src/cypherpunks.ru/nncp/cmd/nncp-pkt/main.go b/src/cypherpunks.ru/nncp/cmd/nncp-pkt/main.go new file mode 100644 index 0000000..b196652 --- /dev/null +++ b/src/cypherpunks.ru/nncp/cmd/nncp-pkt/main.go @@ -0,0 +1,139 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +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 . +*/ + +// Parse raw NNCP packet +package main + +import ( + "bufio" + "bytes" + "flag" + "fmt" + "io" + "io/ioutil" + "log" + "os" + + "cypherpunks.ru/nncp" + "github.com/davecgh/go-xdr/xdr2" + "github.com/dustin/go-humanize" + "golang.org/x/crypto/blake2b" +) + +func usage() { + fmt.Fprintf(os.Stderr, nncp.UsageHeader()) + fmt.Fprintln(os.Stderr, "nncp-pkt -- parse raw packet\n") + fmt.Fprintln(os.Stderr, "Usage: %s [options]\nOptions:", os.Args[0]) + flag.PrintDefaults() + fmt.Fprintln(os.Stderr, "Packet is read from stdin.") +} + +func main() { + var ( + dump = flag.Bool("dump", false, "Write decrypted/parsed payload to stdout") + cfgPath = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file") + version = flag.Bool("version", false, "Print version information") + warranty = flag.Bool("warranty", false, "Print warranty information") + ) + flag.Usage = usage + flag.Parse() + if *warranty { + fmt.Println(nncp.Warranty) + return + } + if *version { + fmt.Println(nncp.VersionGet()) + return + } + + var err error + beginning := make([]byte, nncp.PktOverhead-blake2b.Size256) + if _, err = io.ReadFull(os.Stdin, beginning); err != nil { + log.Fatalln("Not enough data to read") + } + var pkt nncp.Pkt + _, err = xdr.Unmarshal(bytes.NewReader(beginning), &pkt) + if err == nil && pkt.Magic == nncp.MagicNNCPPv1 { + if *dump { + bufW := bufio.NewWriter(os.Stdout) + if _, err = io.Copy(bufW, bufio.NewReader(os.Stdin)); err != nil { + log.Fatalln(err) + } + if err = bufW.Flush(); err != nil { + log.Fatalln(err) + } + return + } + payloadType := "unknown" + switch pkt.Type { + case nncp.PktTypeFile: + payloadType = "file" + case nncp.PktTypeFreq: + payloadType = "file request" + case nncp.PktTypeMail: + payloadType = "mail" + case nncp.PktTypeTrns: + payloadType = "transitional" + } + var path string + switch pkt.Type { + case nncp.PktTypeTrns: + path = nncp.ToBase32(pkt.Path[:pkt.PathLen]) + default: + path = string(pkt.Path[:pkt.PathLen]) + } + fmt.Printf("Packet type: plain\nPayload type: %s\nPath: %s\n", payloadType, path) + return + } + var pktEnc nncp.PktEnc + _, err = xdr.Unmarshal(bytes.NewReader(beginning), &pktEnc) + if err == nil && pktEnc.Magic == nncp.MagicNNCPEv1 { + if *dump { + cfgRaw, err := ioutil.ReadFile(*cfgPath) + if err != nil { + log.Fatalln("Can not read config:", err) + } + ctx, err := nncp.CfgParse(cfgRaw) + if err != nil { + log.Fatalln("Can not parse config:", err) + } + bufW := bufio.NewWriter(os.Stdout) + if _, err = nncp.PktEncRead( + ctx.Self, + ctx.Neigh, + io.MultiReader( + bytes.NewReader(beginning), + bufio.NewReader(os.Stdin), + ), + bufW, + ); err != nil { + log.Fatalln(err) + } + if err = bufW.Flush(); err != nil { + log.Fatalln(err) + } + return + } + fmt.Printf( + "Packet type: encrypted\nNiceness: %d\nSender: %s\nPayload size: %s (%d bytes)\n", + pktEnc.Nice, pktEnc.Sender, humanize.IBytes(pktEnc.Size), pktEnc.Size, + ) + return + } + log.Fatalln("Unable to determine packet type") +} diff --git a/src/cypherpunks.ru/nncp/cmd/nncp-stat/main.go b/src/cypherpunks.ru/nncp/cmd/nncp-stat/main.go new file mode 100644 index 0000000..5481a4e --- /dev/null +++ b/src/cypherpunks.ru/nncp/cmd/nncp-stat/main.go @@ -0,0 +1,112 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +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 . +*/ + +// Show queued NNCP Rx/Tx stats +package main + +import ( + "flag" + "fmt" + "io/ioutil" + "log" + "os" + + "cypherpunks.ru/nncp" + "github.com/dustin/go-humanize" +) + +func usage() { + fmt.Fprintf(os.Stderr, nncp.UsageHeader()) + fmt.Fprintln(os.Stderr, "nncp-stat -- show queued Rx/Tx stats\n") + fmt.Fprintln(os.Stderr, "Usage: %s [options]\nOptions:", os.Args[0]) + flag.PrintDefaults() +} + +func main() { + var ( + cfgPath = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file") + nodeRaw = flag.String("node", "", "Process only that node") + debug = flag.Bool("debug", false, "Enable debugging information") + version = flag.Bool("version", false, "Print version information") + warranty = flag.Bool("warranty", false, "Print warranty information") + ) + flag.Usage = usage + flag.Parse() + if *warranty { + fmt.Println(nncp.Warranty) + return + } + if *version { + fmt.Println(nncp.VersionGet()) + return + } + + cfgRaw, err := ioutil.ReadFile(*cfgPath) + if err != nil { + log.Fatalln("Can not read config:", err) + } + ctx, err := nncp.CfgParse(cfgRaw) + if err != nil { + log.Fatalln("Can not parse config:", err) + } + ctx.Debug = *debug + + var nodeOnly *nncp.Node + if *nodeRaw != "" { + nodeOnly, err = ctx.FindNode(*nodeRaw) + if err != nil { + log.Fatalln("Invalid -node specified:", err) + } + } + + for nodeId, node := range ctx.Neigh { + if nodeOnly != nil && nodeId != *nodeOnly.Id { + continue + } + rxNums := make(map[uint8]int) + rxBytes := make(map[uint8]int64) + for job := range ctx.Jobs(&nodeId, nncp.TRx) { + job.Fd.Close() + rxNums[job.PktEnc.Nice] = rxNums[job.PktEnc.Nice] + 1 + rxBytes[job.PktEnc.Nice] = rxBytes[job.PktEnc.Nice] + job.Size + } + txNums := make(map[uint8]int) + txBytes := make(map[uint8]int64) + for job := range ctx.Jobs(&nodeId, nncp.TTx) { + job.Fd.Close() + txNums[job.PktEnc.Nice] = txNums[job.PktEnc.Nice] + 1 + txBytes[job.PktEnc.Nice] = txBytes[job.PktEnc.Nice] + job.Size + } + fmt.Println(node.Name) + for nice := 0; nice < 256; nice++ { + rxNum, rxExists := rxNums[uint8(nice)] + txNum, txExists := txNums[uint8(nice)] + if !(rxExists || txExists) { + continue + } + fmt.Printf( + "\tnice:% 3d | Rx: % 10s, % 3d pkts | Tx: % 10s, % 3d pkts\n", + nice, + humanize.IBytes(uint64(rxBytes[uint8(nice)])), + rxNum, + humanize.IBytes(uint64(txBytes[uint8(nice)])), + txNum, + ) + } + } +} diff --git a/src/cypherpunks.ru/nncp/cmd/nncp-toss/main.go b/src/cypherpunks.ru/nncp/cmd/nncp-toss/main.go new file mode 100644 index 0000000..7bdffb6 --- /dev/null +++ b/src/cypherpunks.ru/nncp/cmd/nncp-toss/main.go @@ -0,0 +1,87 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +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 . +*/ + +// Process inbound NNCP packets +package main + +import ( + "flag" + "fmt" + "io/ioutil" + "log" + "os" + + "cypherpunks.ru/nncp" +) + +func usage() { + fmt.Fprintf(os.Stderr, nncp.UsageHeader()) + fmt.Fprintln(os.Stderr, "nncp-toss -- process inbound packets\n") + fmt.Fprintln(os.Stderr, "Usage: %s [options]\nOptions:", os.Args[0]) + flag.PrintDefaults() +} + +func main() { + var ( + cfgPath = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file") + nodeRaw = flag.String("node", "", "Process only that node") + niceRaw = flag.Int("nice", 255, "Minimal required niceness") + debug = flag.Bool("debug", false, "Enable debugging information") + version = flag.Bool("version", false, "Print version information") + warranty = flag.Bool("warranty", false, "Print warranty information") + ) + flag.Usage = usage + flag.Parse() + if *warranty { + fmt.Println(nncp.Warranty) + return + } + if *version { + fmt.Println(nncp.VersionGet()) + return + } + if *niceRaw < 1 || *niceRaw > 255 { + log.Fatalln("-nice must be between 1 and 255") + } + nice := uint8(*niceRaw) + + cfgRaw, err := ioutil.ReadFile(*cfgPath) + if err != nil { + log.Fatalln("Can not read config:", err) + } + ctx, err := nncp.CfgParse(cfgRaw) + if err != nil { + log.Fatalln("Can not parse config:", err) + } + ctx.Debug = *debug + + var nodeOnly *nncp.Node + if *nodeRaw != "" { + nodeOnly, err = ctx.FindNode(*nodeRaw) + if err != nil { + log.Fatalln("Invalid -node specified:", err) + } + } + + for nodeId, node := range ctx.Neigh { + if nodeOnly != nil && nodeId != *nodeOnly.Id { + continue + } + ctx.Toss(node.Id, nice) + } +} diff --git a/src/cypherpunks.ru/nncp/cmd/nncp-xfer/main.go b/src/cypherpunks.ru/nncp/cmd/nncp-xfer/main.go new file mode 100644 index 0000000..59d7d25 --- /dev/null +++ b/src/cypherpunks.ru/nncp/cmd/nncp-xfer/main.go @@ -0,0 +1,333 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +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 . +*/ + +// Copy NNCP inbound and outbounds packets +package main + +import ( + "bufio" + "flag" + "fmt" + "io" + "io/ioutil" + "log" + "os" + "path/filepath" + "strconv" + + "cypherpunks.ru/nncp" + "github.com/davecgh/go-xdr/xdr2" +) + +func usage() { + fmt.Fprintf(os.Stderr, nncp.UsageHeader()) + fmt.Fprintln(os.Stderr, "nncp-xfer -- copy inbound and outbounds packets\n") + fmt.Fprintln(os.Stderr, "Usage: %s [options] DIR\nOptions:", os.Args[0]) + flag.PrintDefaults() +} + +func main() { + var ( + cfgPath = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file") + nodeRaw = flag.String("node", "", "Process only that node") + niceRaw = flag.Int("nice", 255, "Minimal required niceness") + rxOnly = flag.Bool("rx", false, "Only receive packets") + txOnly = flag.Bool("tx", false, "Only transfer packets") + force = flag.Bool("force", false, "Force outbound directories creation") + keep = flag.Bool("keep", false, "Do not delete transferred packets") + debug = flag.Bool("debug", false, "Enable debugging information") + version = flag.Bool("version", false, "Print version information") + warranty = flag.Bool("warranty", false, "Print warranty information") + ) + flag.Usage = usage + flag.Parse() + if *warranty { + fmt.Println(nncp.Warranty) + return + } + if *version { + fmt.Println(nncp.VersionGet()) + return + } + if flag.NArg() != 1 { + usage() + os.Exit(1) + } + if *niceRaw < 1 || *niceRaw > 255 { + log.Fatalln("-nice must be between 1 and 255") + } + nice := uint8(*niceRaw) + if *rxOnly && *txOnly { + log.Fatalln("-rx and -tx can not be set simultaneously") + } + + cfgRaw, err := ioutil.ReadFile(*cfgPath) + if err != nil { + log.Fatalln("Can not read config:", err) + } + ctx, err := nncp.CfgParse(cfgRaw) + if err != nil { + log.Fatalln("Can not parse config:", err) + } + ctx.Debug = *debug + + var nodeOnly *nncp.Node + if *nodeRaw != "" { + nodeOnly, err = ctx.FindNode(*nodeRaw) + if err != nil { + log.Fatalln("Invalid -node specified:", err) + } + } + + selfPath := filepath.Join(flag.Arg(0), ctx.Self.Id.String()) + badExit := false + var dir *os.File + var fis []os.FileInfo + sds := nncp.SDS{} + if *txOnly { + goto Tx + } + sds["xx"] = string(nncp.TRx) + sds["dir"] = selfPath + ctx.LogD("nncp-xfer", sds, "self") + if _, err = os.Stat(selfPath); err != nil { + if os.IsNotExist(err) { + ctx.LogD("nncp-xfer", sds, "no dir") + goto Tx + } + ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "stat") + badExit = true + goto Tx + } + dir, err = os.Open(selfPath) + if err != nil { + ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "open") + badExit = true + goto Tx + } + fis, err = dir.Readdir(0) + dir.Close() + if err != nil { + ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "read") + badExit = true + goto Tx + } + for _, fi := range fis { + if !fi.IsDir() { + continue + } + nodeId, err := nncp.NodeIdFromString(fi.Name()) + sds["node"] = fi.Name() + if err != nil { + ctx.LogD("nncp-xfer", sds, "is not NodeId") + continue + } + if nodeOnly != nil && *nodeId != *nodeOnly.Id { + ctx.LogD("nncp-xfer", sds, "skip") + continue + } + if _, known := ctx.Neigh[*nodeId]; !known { + ctx.LogD("nncp-xfer", sds, "unknown") + continue + } + dir, err = os.Open(filepath.Join(selfPath, fi.Name())) + if err != nil { + ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "open") + badExit = true + continue + } + fisInt, err := dir.Readdir(0) + dir.Close() + if err != nil { + ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "read") + badExit = true + continue + } + for _, fiInt := range fisInt { + if !fi.IsDir() { + continue + } + filename := filepath.Join(dir.Name(), fiInt.Name()) + sds["file"] = filename + fd, err := os.Open(filename) + if err != nil { + ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "open") + badExit = true + continue + } + var pktEnc nncp.PktEnc + _, err = xdr.Unmarshal(fd, &pktEnc) + if err != nil || pktEnc.Magic != nncp.MagicNNCPEv1 { + ctx.LogD("nncp-xfer", sds, "is not a packet") + fd.Close() + continue + } + if pktEnc.Nice > nice { + ctx.LogD("nncp-xfer", sds, "too nice") + fd.Close() + continue + } + fd.Seek(0, 0) + tmp, err := ctx.NewTmpFileWHash() + if err != nil { + log.Fatalln(err) + } + copied, err := io.Copy(tmp.W, bufio.NewReader(fd)) + if err != nil { + ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "copy") + badExit = true + fd.Close() + tmp.Cancel() + continue + } + fd.Close() + if err = tmp.Commit(filepath.Join( + ctx.Spool, + nodeId.String(), + string(nncp.TRx), + )); err != nil { + log.Fatalln(err) + } + ctx.LogI("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{ + "size": strconv.FormatInt(copied, 10), + }), "") + if !*keep { + if err = os.Remove(filename); err != nil { + ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "remove") + badExit = true + } + } + } + } + +Tx: + if *rxOnly { + if badExit { + os.Exit(1) + } + return + } + sds["xx"] = string(nncp.TTx) + for nodeId, _ := range ctx.Neigh { + sds["node"] = nodeId + if nodeOnly != nil && nodeId != *nodeOnly.Id { + ctx.LogD("nncp-xfer", sds, "skip") + continue + } + dirLock, err := ctx.LockDir(&nodeId, nncp.TTx) + if err != nil { + continue + } + nodePath := filepath.Join(flag.Arg(0), nodeId.String()) + sds["dir"] = nodePath + _, err = os.Stat(nodePath) + if err != nil { + if os.IsNotExist(err) { + ctx.LogD("nncp-xfer", sds, "does not exist") + if !*force { + ctx.UnlockDir(dirLock) + continue + } + if err = os.Mkdir(nodePath, os.FileMode(0700)); err != nil { + ctx.UnlockDir(dirLock) + ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "mkdir") + badExit = true + continue + } + } else { + ctx.UnlockDir(dirLock) + ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "stat") + badExit = true + continue + } + } + dstPath := filepath.Join(nodePath, ctx.Self.Id.String()) + sds["dir"] = dstPath + _, err = os.Stat(dstPath) + if err != nil { + if os.IsNotExist(err) { + if err = os.Mkdir(dstPath, os.FileMode(0700)); err != nil { + ctx.UnlockDir(dirLock) + ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "mkdir") + badExit = true + continue + } + } else { + ctx.UnlockDir(dirLock) + ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "stat") + badExit = true + continue + } + } + delete(sds, "dir") + for job := range ctx.Jobs(&nodeId, nncp.TTx) { + pktName := filepath.Base(job.Fd.Name()) + sds["pkt"] = pktName + if job.PktEnc.Nice > nice { + ctx.LogD("nncp-xfer", sds, "too nice") + job.Fd.Close() + continue + } + tmp, err := ioutil.TempFile(dstPath, "nncp-xfer") + if err != nil { + ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "mktemp") + job.Fd.Close() + badExit = true + break + } + sds["tmp"] = tmp.Name() + ctx.LogD("nncp-xfer", sds, "created") + bufW := bufio.NewWriter(tmp) + copied, err := io.Copy(bufW, bufio.NewReader(job.Fd)) + job.Fd.Close() + if err != nil { + ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "copy") + tmp.Close() + badExit = true + continue + } + err = bufW.Flush() + tmp.Sync() + tmp.Close() + if err != nil { + ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "copy") + badExit = true + continue + } + if err = os.Rename(tmp.Name(), filepath.Join(dstPath, pktName)); err != nil { + ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "rename") + badExit = true + continue + } + delete(sds, "tmp") + ctx.LogI("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{ + "size": strconv.FormatInt(copied, 10), + }), "") + if !*keep { + if err = os.Remove(job.Fd.Name()); err != nil { + ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "remove") + badExit = true + } + } + } + ctx.UnlockDir(dirLock) + } + if badExit { + os.Exit(1) + } +} diff --git a/src/cypherpunks.ru/nncp/ctx.go b/src/cypherpunks.ru/nncp/ctx.go new file mode 100644 index 0000000..872e12c --- /dev/null +++ b/src/cypherpunks.ru/nncp/ctx.go @@ -0,0 +1,53 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +package nncp + +import ( + "errors" +) + +type Ctx struct { + Self *NodeOur + Neigh map[NodeId]*Node + Alias map[string]*NodeId + + Spool string + Sendmail []string + + LogPath string + Debug bool + NotifyFile *FromToYAML + NotifyFreq *FromToYAML +} + +func (ctx *Ctx) FindNode(id string) (*Node, error) { + nodeId, known := ctx.Alias[id] + if known { + return ctx.Neigh[*nodeId], nil + } + nodeId, err := NodeIdFromString(id) + if err != nil { + return nil, err + } + node, known := ctx.Neigh[*nodeId] + if !known { + return nil, errors.New("Unknown node") + } + return node, nil +} diff --git a/src/cypherpunks.ru/nncp/humanizer.go b/src/cypherpunks.ru/nncp/humanizer.go new file mode 100644 index 0000000..062c070 --- /dev/null +++ b/src/cypherpunks.ru/nncp/humanizer.go @@ -0,0 +1,227 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +package nncp + +import ( + "fmt" + "regexp" + "strconv" + "strings" + "time" + + "github.com/dustin/go-humanize" +) + +func (ctx *Ctx) Humanize(s string) string { + s = strings.TrimRight(s, "\n") + splitted := strings.SplitN(s, " ", 4) + if len(splitted) != 4 { + return s + } + var level string + if splitted[0] == "E" { + level = "ERROR " + } + when, err := time.Parse(time.RFC3339Nano, splitted[1]) + if err != nil { + return s + } + who := splitted[2][1:] + closingBracket := strings.LastIndex(splitted[3], "]") + if closingBracket == -1 { + return s + } + rem := strings.Trim(splitted[3][closingBracket+1:], " ") + sds := make(map[string]string) + + re := regexp.MustCompile(`\w+="[^"]+"`) + for _, pair := range re.FindAllString(splitted[3][:closingBracket+1], -1) { + sep := strings.Index(pair, "=") + sds[pair[:sep]] = pair[sep+2 : len(pair)-1] + } + + nodeS := sds["node"] + node, err := ctx.FindNode(nodeS) + if err == nil { + nodeS = node.Name + } + var size string + if sizeRaw, exists := sds["size"]; exists { + sp, err := strconv.ParseUint(sizeRaw, 10, 64) + if err != nil { + return s + } + size = humanize.IBytes(uint64(sp)) + } + + var msg string + switch who { + case "tx": + switch sds["type"] { + case "file": + msg = fmt.Sprintf( + "File %s (%s) transfer to %s:%s (nice %s): %s", + sds["src"], size, nodeS, sds["dst"], sds["nice"], rem, + ) + case "freq": + msg = fmt.Sprintf( + "File request from %s:%s to %s (nice %s): %s", + nodeS, sds["src"], sds["dst"], sds["nice"], rem, + ) + case "mail": + msg = fmt.Sprintf( + "Mail to %s@%s (%s) (nice %s): %s", + nodeS, strings.Replace(sds["dst"], " ", ",", -1), size, sds["nice"], rem, + ) + case "trns": + msg = fmt.Sprintf( + "Transitional packet to %s (%s) (nice %s): %s", + nodeS, size, sds["nice"], rem, + ) + default: + return s + } + if err, exists := sds["err"]; exists { + msg += ": " + err + } + case "rx": + switch sds["type"] { + case "mail": + msg = fmt.Sprintf( + "Got mail from %s to %s (%s)", + nodeS, strings.Replace(sds["dst"], " ", ",", -1), size, + ) + case "file": + msg = fmt.Sprintf("Got file %s (%s) from %s", sds["dst"], size, nodeS) + case "freq": + msg = fmt.Sprintf("Got file request %s to %s", sds["src"], nodeS) + case "trns": + nodeT := sds["dst"] + node, err := ctx.FindNode(nodeT) + if err == nil { + nodeT = node.Name + } + msg = fmt.Sprintf( + "Got transitional packet from %s to %s (%s)", + nodeS, nodeT, size, + ) + default: + return s + } + if err, exists := sds["err"]; exists { + msg += ": " + err + } + case "toss-check": + msg = fmt.Sprintf( + "Integrity check: %s/%s/%s %s", + sds["node"], sds["xx"], sds["pkt"], sds["err"], + ) + case "nncp-xfer": + switch sds["xx"] { + case "rx": + msg = "Packet transfer, received from" + case "tx": + msg = "Packet transfer, sent to" + default: + return s + } + if nodeS != "" { + msg += " node " + nodeS + } + if size != "" { + msg += fmt.Sprintf(" (%s)", size) + } + if err, exists := sds["err"]; exists { + msg += ": " + err + } + case "daemon": + msg = fmt.Sprintf("Daemon listening on %s", sds["bind"]) + case "call-start": + msg = fmt.Sprintf("Connected to %s", nodeS) + case "call-finish": + rx, err := strconv.ParseUint(sds["rxbytes"], 10, 64) + if err != nil { + return s + } + rxs, err := strconv.ParseUint(sds["rxspeed"], 10, 64) + if err != nil { + return s + } + tx, err := strconv.ParseUint(sds["txbytes"], 10, 64) + if err != nil { + return s + } + txs, err := strconv.ParseUint(sds["txspeed"], 10, 64) + if err != nil { + return s + } + msg = fmt.Sprintf( + "Finished call with %s: %s received (%s/sec), %s transferred (%s/sec)", + nodeS, + humanize.IBytes(uint64(rx)), humanize.IBytes(uint64(rxs)), + humanize.IBytes(uint64(tx)), humanize.IBytes(uint64(txs)), + ) + case "llp-infos": + switch sds["xx"] { + case "rx": + msg = fmt.Sprintf("We have got for %s: ", nodeS) + case "tx": + msg = fmt.Sprintf("%s has got for us: ", nodeS) + default: + return s + } + msg += fmt.Sprintf("%s packets, %s", sds["pkts"], size) + case "llp-file": + switch sds["xx"] { + case "rx": + msg = "Got file " + case "tx": + msg = "Sent file " + default: + return s + } + fullsize, err := strconv.ParseUint(sds["fullsize"], 10, 64) + if err != nil { + return s + } + sizeParsed, err := strconv.ParseUint(sds["size"], 10, 64) + if err != nil { + return s + } + msg += fmt.Sprintf( + "%s %d%% (%s / %s)", + sds["hash"], + 100*sizeParsed/fullsize, + humanize.IBytes(uint64(sizeParsed)), + humanize.IBytes(uint64(fullsize)), + ) + case "llp-done": + switch sds["xx"] { + case "rx": + msg = fmt.Sprintf("File %s is retreived (%s)", sds["hash"], size) + case "tx": + msg = fmt.Sprintf("File %s is sent (%s)", sds["hash"], size) + default: + return s + } + default: + return s + } + return fmt.Sprintf("%s %s%s", when.Format(time.RFC3339), level, msg) +} diff --git a/src/cypherpunks.ru/nncp/jobs.go b/src/cypherpunks.ru/nncp/jobs.go new file mode 100644 index 0000000..705bcf7 --- /dev/null +++ b/src/cypherpunks.ru/nncp/jobs.go @@ -0,0 +1,90 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +package nncp + +import ( + "os" + "path/filepath" + "strconv" + + "github.com/davecgh/go-xdr/xdr2" +) + +type TRxTx string + +const ( + TRx TRxTx = "rx" + TTx TRxTx = "tx" +) + +type Job struct { + PktEnc *PktEnc + Fd *os.File + Size int64 + HshValue *[32]byte +} + +func (ctx *Ctx) Jobs(nodeId *NodeId, xx TRxTx) chan Job { + rxPath := filepath.Join(ctx.Spool, nodeId.String(), string(xx)) + jobs := make(chan Job, 16) + go func() { + defer close(jobs) + dir, err := os.Open(rxPath) + if err != nil { + return + } + fis, err := dir.Readdir(0) + dir.Close() + if err != nil { + return + } + for _, fi := range fis { + hshValue, err := FromBase32(fi.Name()) + if err != nil { + continue + } + fd, err := os.Open(filepath.Join(rxPath, fi.Name())) + if err != nil { + continue + } + var pktEnc PktEnc + if _, err = xdr.Unmarshal(fd, &pktEnc); err != nil || pktEnc.Magic != MagicNNCPEv1 { + fd.Close() + continue + } + fd.Seek(0, 0) + ctx.LogD("jobs", SDS{ + "xx": string(xx), + "node": pktEnc.Sender, + "name": fi.Name(), + "nice": strconv.Itoa(int(pktEnc.Nice)), + "size": strconv.FormatInt(fi.Size(), 10), + }, "taken") + job := Job{ + PktEnc: &pktEnc, + Fd: fd, + Size: fi.Size(), + HshValue: new([32]byte), + } + copy(job.HshValue[:], hshValue) + jobs <- job + } + }() + return jobs +} diff --git a/src/cypherpunks.ru/nncp/llp.go b/src/cypherpunks.ru/nncp/llp.go new file mode 100644 index 0000000..6f92bf2 --- /dev/null +++ b/src/cypherpunks.ru/nncp/llp.go @@ -0,0 +1,871 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +package nncp + +import ( + "bytes" + "crypto/subtle" + "errors" + "io" + "net" + "os" + "path/filepath" + "sort" + "strconv" + "sync" + "time" + + "github.com/davecgh/go-xdr/xdr2" + "github.com/flynn/noise" +) + +const ( + MaxLLPSize = 2<<15 - 256 + PartSuffix = ".part" +) + +var ( + MagicNNCPLv1 [8]byte = [8]byte{'N', 'N', 'C', 'P', 'L', 1, 0, 0} + + LLPHeadOverhead int + LLPInfoOverhead int + LLPFreqOverhead int + LLPFileOverhead int + LLPHaltMarshalized []byte + + NoiseCipherSuite noise.CipherSuite = noise.NewCipherSuite( + noise.DH25519, + noise.CipherChaChaPoly, + noise.HashBLAKE2b, + ) + + DeadlineDuration time.Duration = 10 * time.Second +) + +type LLPType uint8 + +const ( + LLPTypeInfo LLPType = iota + LLPTypeFreq LLPType = iota + LLPTypeFile LLPType = iota + LLPTypeDone LLPType = iota + LLPTypeHalt LLPType = iota +) + +type LLPHead struct { + Type LLPType +} + +type LLPInfo struct { + Nice uint8 + Size uint64 + Hash *[32]byte +} + +type LLPFreq struct { + Hash *[32]byte + Offset uint64 +} + +type LLPFile struct { + Hash *[32]byte + Offset uint64 + Payload []byte +} + +type LLPDone struct { + Hash *[32]byte +} + +type LLPRaw struct { + Magic [8]byte + Payload []byte +} + +func init() { + var buf bytes.Buffer + llpHead := LLPHead{Type: LLPTypeHalt} + if _, err := xdr.Marshal(&buf, llpHead); err != nil { + panic(err) + } + copy(LLPHaltMarshalized, buf.Bytes()) + LLPHeadOverhead = buf.Len() + buf.Reset() + + llpInfo := LLPInfo{Nice: 123, Size: 123, Hash: new([32]byte)} + if _, err := xdr.Marshal(&buf, llpInfo); err != nil { + panic(err) + } + LLPInfoOverhead = buf.Len() + buf.Reset() + + llpFreq := LLPFreq{Hash: new([32]byte), Offset: 123} + if _, err := xdr.Marshal(&buf, llpFreq); err != nil { + panic(err) + } + LLPFreqOverhead = buf.Len() + buf.Reset() + + llpFile := LLPFile{Hash: new([32]byte), Offset: 123} + if _, err := xdr.Marshal(&buf, llpFile); err != nil { + panic(err) + } + LLPFileOverhead = buf.Len() +} + +func MarshalLLP(typ LLPType, llp interface{}) []byte { + var buf bytes.Buffer + var err error + if _, err = xdr.Marshal(&buf, LLPHead{typ}); err != nil { + panic(err) + } + if _, err = xdr.Marshal(&buf, llp); err != nil { + panic(err) + } + return buf.Bytes() +} + +func payloadsSplit(payloads [][]byte) [][]byte { + var outbounds [][]byte + outbound := make([]byte, 0, MaxLLPSize) + for i, payload := range payloads { + outbound = append(outbound, payload...) + if i+1 < len(payloads) && len(outbound)+len(payloads[i+1]) > MaxLLPSize { + outbounds = append(outbounds, outbound) + outbound = make([]byte, 0, MaxLLPSize) + } + } + if len(outbound) > 0 { + outbounds = append(outbounds, outbound) + } + return outbounds +} + +type LLPState struct { + ctx *Ctx + NodeId *NodeId + nice uint8 + hs *noise.HandshakeState + csOur *noise.CipherState + csTheir *noise.CipherState + payloads chan []byte + infosTheir map[[32]byte]*LLPInfo + queueTheir []*LLPFreq + isDead bool + wg sync.WaitGroup + RxBytes int64 + RxLastSeen time.Time + TxBytes int64 + TxLastSeen time.Time + started time.Time + Duration time.Duration + RxSpeed int64 + TxSpeed int64 + rxLock *os.File + txLock *os.File + xxOnly *TRxTx + sync.RWMutex +} + +func (state *LLPState) dirUnlock() { + state.ctx.UnlockDir(state.rxLock) + state.ctx.UnlockDir(state.txLock) +} + +func (state *LLPState) WriteLLP(dst io.Writer, payload []byte) error { + n, err := xdr.Marshal(dst, LLPRaw{Magic: MagicNNCPLv1, Payload: payload}) + if err == nil { + state.TxLastSeen = time.Now() + state.TxBytes += int64(n) + } + return err +} + +func (state *LLPState) ReadLLP(src io.Reader) ([]byte, error) { + var llp LLPRaw + n, err := xdr.Unmarshal(src, &llp) + if err != nil { + return nil, err + } + state.RxLastSeen = time.Now() + state.RxBytes += int64(n) + if llp.Magic != MagicNNCPLv1 { + return nil, BadMagic + } + return llp.Payload, nil +} + +func (ctx *Ctx) infosOur(nodeId *NodeId, nice uint8) [][]byte { + var infos []*LLPInfo + var totalSize int64 + for job := range ctx.Jobs(nodeId, TTx) { + job.Fd.Close() + if job.PktEnc.Nice > nice { + continue + } + totalSize += job.Size + infos = append(infos, &LLPInfo{ + Nice: job.PktEnc.Nice, + Size: uint64(job.Size), + Hash: job.HshValue, + }) + } + sort.Sort(ByNice(infos)) + var payloads [][]byte + for _, info := range infos { + payloads = append(payloads, MarshalLLP(LLPTypeInfo, info)) + ctx.LogD("llp-info-our", SDS{ + "node": nodeId, + "name": ToBase32(info.Hash[:]), + "size": strconv.FormatInt(int64(info.Size), 10), + }, "") + } + ctx.LogI("llp-infos", SDS{ + "xx": string(TTx), + "node": nodeId, + "pkts": strconv.Itoa(len(payloads)), + "size": strconv.FormatInt(totalSize, 10), + }, "") + return payloadsSplit(payloads) +} + +func (ctx *Ctx) ensureRxDir(nodeId *NodeId) error { + dirPath := filepath.Join(ctx.Spool, nodeId.String(), string(TRx)) + if err := os.MkdirAll(dirPath, os.FileMode(0700)); err != nil { + ctx.LogE("llp-ensure", SDS{"dir": dirPath, "err": err}, "") + return err + } + fd, err := os.Open(dirPath) + if err != nil { + ctx.LogE("llp-ensure", SDS{"dir": dirPath, "err": err}, "") + return err + } + fd.Close() + return nil +} + +func (ctx *Ctx) StartI(conn net.Conn, nodeId *NodeId, nice uint8, xxOnly *TRxTx) (*LLPState, error) { + err := ctx.ensureRxDir(nodeId) + if err != nil { + return nil, err + } + var rxLock *os.File + if xxOnly != nil && *xxOnly == TRx { + rxLock, err = ctx.LockDir(nodeId, TRx) + if err != nil { + return nil, err + } + } + var txLock *os.File + if xxOnly != nil && *xxOnly == TTx { + txLock, err = ctx.LockDir(nodeId, TTx) + if err != nil { + return nil, err + } + } + started := time.Now() + conf := noise.Config{ + CipherSuite: NoiseCipherSuite, + Pattern: noise.HandshakeIK, + Initiator: true, + StaticKeypair: noise.DHKey{ + Private: ctx.Self.NoisePrv[:], + Public: ctx.Self.NoisePub[:], + }, + PeerStatic: ctx.Neigh[*nodeId].NoisePub[:], + } + state := LLPState{ + ctx: ctx, + hs: noise.NewHandshakeState(conf), + NodeId: nodeId, + nice: nice, + payloads: make(chan []byte), + infosTheir: make(map[[32]byte]*LLPInfo), + started: started, + rxLock: rxLock, + txLock: txLock, + xxOnly: xxOnly, + } + + var infosPayloads [][]byte + if xxOnly == nil || *xxOnly != TTx { + infosPayloads = ctx.infosOur(nodeId, nice) + } + var firstPayload []byte + if len(infosPayloads) > 0 { + firstPayload = infosPayloads[0] + } + for i := 0; i < (MaxLLPSize-len(firstPayload))/LLPHeadOverhead; i++ { + firstPayload = append(firstPayload, LLPHaltMarshalized...) + } + + var buf []byte + var payload []byte + buf, _, _ = state.hs.WriteMessage(nil, firstPayload) + sds := SDS{"node": nodeId, "nice": strconv.Itoa(int(nice))} + ctx.LogD("llp-start", sds, "sending first message") + conn.SetWriteDeadline(time.Now().Add(DeadlineDuration)) + if err = state.WriteLLP(conn, buf); err != nil { + ctx.LogE("llp-start", SdsAdd(sds, SDS{"err": err}), "") + state.dirUnlock() + return nil, err + } + ctx.LogD("llp-start", sds, "waiting for first message") + conn.SetReadDeadline(time.Now().Add(DeadlineDuration)) + if buf, err = state.ReadLLP(conn); err != nil { + ctx.LogE("llp-start", SdsAdd(sds, SDS{"err": err}), "") + state.dirUnlock() + return nil, err + } + payload, state.csOur, state.csTheir, err = state.hs.ReadMessage(nil, buf) + if err != nil { + ctx.LogE("llp-start", SdsAdd(sds, SDS{"err": err}), "") + state.dirUnlock() + return nil, err + } + ctx.LogD("llp-start", sds, "starting workers") + err = state.StartWorkers(conn, infosPayloads, payload) + if err != nil { + ctx.LogE("llp-start", SdsAdd(sds, SDS{"err": err}), "") + state.dirUnlock() + return nil, err + } + return &state, err +} + +func (ctx *Ctx) StartR(conn net.Conn, nice uint8, xxOnly *TRxTx) (*LLPState, error) { + started := time.Now() + conf := noise.Config{ + CipherSuite: NoiseCipherSuite, + Pattern: noise.HandshakeIK, + Initiator: false, + StaticKeypair: noise.DHKey{ + Private: ctx.Self.NoisePrv[:], + Public: ctx.Self.NoisePub[:], + }, + } + state := LLPState{ + ctx: ctx, + hs: noise.NewHandshakeState(conf), + nice: nice, + payloads: make(chan []byte), + infosTheir: make(map[[32]byte]*LLPInfo), + started: started, + xxOnly: xxOnly, + } + var buf []byte + var payload []byte + var err error + ctx.LogD( + "llp-start", + SDS{"nice": strconv.Itoa(int(nice))}, + "waiting for first message", + ) + conn.SetReadDeadline(time.Now().Add(DeadlineDuration)) + if buf, err = state.ReadLLP(conn); err != nil { + ctx.LogE("llp-start", SDS{"err": err}, "") + return nil, err + } + if payload, _, _, err = state.hs.ReadMessage(nil, buf); err != nil { + ctx.LogE("llp-start", SDS{"err": err}, "") + return nil, err + } + + var nodeId *NodeId + for _, node := range ctx.Neigh { + if subtle.ConstantTimeCompare(state.hs.PeerStatic(), node.NoisePub[:]) == 1 { + nodeId = node.Id + break + } + } + if nodeId == nil { + peerId := ToBase32(state.hs.PeerStatic()) + ctx.LogE("llp-start", SDS{"peer": peerId}, "unknown") + return nil, errors.New("Unknown peer: " + peerId) + } + state.NodeId = nodeId + sds := SDS{"node": nodeId, "nice": strconv.Itoa(int(nice))} + + if ctx.ensureRxDir(nodeId); err != nil { + return nil, err + } + var rxLock *os.File + if xxOnly != nil && *xxOnly == TRx { + rxLock, err = ctx.LockDir(nodeId, TRx) + if err != nil { + return nil, err + } + } + state.rxLock = rxLock + var txLock *os.File + if xxOnly != nil && *xxOnly == TTx { + txLock, err = ctx.LockDir(nodeId, TTx) + if err != nil { + return nil, err + } + } + state.txLock = txLock + + var infosPayloads [][]byte + if xxOnly == nil || *xxOnly != TTx { + infosPayloads = ctx.infosOur(nodeId, nice) + } + var firstPayload []byte + if len(infosPayloads) > 0 { + firstPayload = infosPayloads[0] + } + for i := 0; i < (MaxLLPSize-len(firstPayload))/LLPHeadOverhead; i++ { + firstPayload = append(firstPayload, LLPHaltMarshalized...) + } + + ctx.LogD("llp-start", sds, "sending first message") + buf, state.csTheir, state.csOur = state.hs.WriteMessage(nil, firstPayload) + conn.SetWriteDeadline(time.Now().Add(DeadlineDuration)) + if err = state.WriteLLP(conn, buf); err != nil { + ctx.LogE("llp-start", SdsAdd(sds, SDS{"err": err}), "") + state.dirUnlock() + return nil, err + } + ctx.LogD("llp-start", sds, "starting workers") + err = state.StartWorkers(conn, infosPayloads, payload) + if err != nil { + state.dirUnlock() + return nil, err + } + return &state, err +} + +func (state *LLPState) StartWorkers(conn net.Conn, infosPayloads [][]byte, payload []byte) error { + sds := SDS{"node": state.NodeId, "nice": strconv.Itoa(int(state.nice))} + if len(infosPayloads) > 1 { + go func() { + for _, payload := range infosPayloads[1:] { + state.ctx.LogD( + "llp-work", + SdsAdd(sds, SDS{"size": strconv.Itoa(len(payload))}), + "queuing remaining payload", + ) + state.payloads <- payload + } + }() + } + state.ctx.LogD( + "llp-work", + SdsAdd(sds, SDS{"size": strconv.Itoa(len(payload))}), + "processing first payload", + ) + replies, err := state.ProcessLLP(payload) + if err != nil { + state.ctx.LogE("llp-work", SdsAdd(sds, SDS{"err": err}), "") + return err + } + go func() { + for _, reply := range replies { + state.ctx.LogD( + "llp-work", + SdsAdd(sds, SDS{"size": strconv.Itoa(len(reply))}), + "queuing reply", + ) + state.payloads <- reply + } + }() + state.wg.Add(1) + go func() { + defer state.wg.Done() + for { + if state.isDead { + return + } + var payload []byte + select { + case payload = <-state.payloads: + state.ctx.LogD( + "llp-xmit", + SdsAdd(sds, SDS{"size": strconv.Itoa(len(payload))}), + "got payload", + ) + default: + } + if payload == nil { + state.RLock() + if len(state.queueTheir) == 0 { + state.ctx.LogD("llp-xmit", sds, "file queue is empty") + state.RUnlock() + time.Sleep(100 * time.Millisecond) + continue + } + freq := state.queueTheir[0] + state.RUnlock() + sdsp := SdsAdd(sds, SDS{ + "xx": string(TTx), + "hash": ToBase32(freq.Hash[:]), + "size": strconv.FormatInt(int64(freq.Offset), 10), + }) + state.ctx.LogD("llp-file", sdsp, "queueing") + fd, err := os.Open(filepath.Join( + state.ctx.Spool, + state.NodeId.String(), + string(TTx), + ToBase32(freq.Hash[:]), + )) + if err != nil { + state.ctx.LogE("llp-file", SdsAdd(sdsp, SDS{"err": err}), "") + break + } + state.ctx.LogD("llp-file", sdsp, "seeking") + if _, err = fd.Seek(int64(freq.Offset), 0); err != nil { + state.ctx.LogE("llp-file", SdsAdd(sdsp, SDS{"err": err}), "") + break + } + buf := make([]byte, MaxLLPSize-LLPHeadOverhead-LLPFileOverhead) + n, err := fd.Read(buf) + if err != nil { + state.ctx.LogE("llp-file", SdsAdd(sdsp, SDS{"err": err}), "") + break + } + buf = buf[:n] + state.ctx.LogD( + "llp-file", + SdsAdd(sdsp, SDS{"size": strconv.Itoa(n)}), + "read", + ) + fi, err := fd.Stat() + if err != nil { + state.ctx.LogE("llp-file", SdsAdd(sdsp, SDS{"err": err}), "") + break + } + fullSize := uint64(fi.Size()) + fd.Close() + payload = MarshalLLP(LLPTypeFile, LLPFile{ + Hash: freq.Hash, + Offset: freq.Offset, + Payload: buf, + }) + state.ctx.LogP("llp-file", SdsAdd(sdsp, SDS{ + "fullsize": strconv.FormatInt(int64(fullSize), 10), + }), "") + state.Lock() + if len(state.queueTheir) > 0 && *state.queueTheir[0].Hash == *freq.Hash { + if freq.Offset+uint64(len(buf)) == fullSize { + state.ctx.LogD("llp-file", sdsp, "finished") + if len(state.queueTheir) > 1 { + state.queueTheir = state.queueTheir[1:] + } else { + state.queueTheir = state.queueTheir[:0] + } + } else { + state.queueTheir[0].Offset += uint64(len(buf)) + } + } else { + state.ctx.LogD("llp-file", sdsp, "queue disappeared") + } + state.Unlock() + } + state.ctx.LogD( + "llp-xmit", + SdsAdd(sds, SDS{"size": strconv.Itoa(len(payload))}), + "sending", + ) + conn.SetWriteDeadline(time.Now().Add(DeadlineDuration)) + if err := state.WriteLLP(conn, state.csOur.Encrypt(nil, nil, payload)); err != nil { + state.ctx.LogE("llp-xmit", SdsAdd(sds, SDS{"err": err}), "") + break + } + } + state.isDead = true + }() + state.wg.Add(1) + go func() { + defer state.wg.Done() + for { + if state.isDead { + return + } + state.ctx.LogD("llp-recv", sds, "waiting for payload") + conn.SetReadDeadline(time.Now().Add(DeadlineDuration)) + payload, err := state.ReadLLP(conn) + if err != nil { + unmarshalErr := err.(*xdr.UnmarshalError) + netErr, ok := unmarshalErr.Err.(net.Error) + if !(ok && netErr.Timeout()) { + state.ctx.LogE("llp-recv", SdsAdd(sds, SDS{"err": err}), "") + } + break + } + state.ctx.LogD( + "llp-recv", + SdsAdd(sds, SDS{"size": strconv.Itoa(len(payload))}), + "got payload", + ) + payload, err = state.csTheir.Decrypt(nil, nil, payload) + if err != nil { + state.ctx.LogE("llp-recv", SdsAdd(sds, SDS{"err": err}), "") + break + } + state.ctx.LogD( + "llp-recv", + SdsAdd(sds, SDS{"size": strconv.Itoa(len(payload))}), + "processing", + ) + replies, err := state.ProcessLLP(payload) + if err != nil { + state.ctx.LogE("llp-recv", SdsAdd(sds, SDS{"err": err}), "") + break + } + go func() { + for _, reply := range replies { + state.ctx.LogD( + "llp-recv", + SdsAdd(sds, SDS{"size": strconv.Itoa(len(reply))}), + "queuing reply", + ) + state.payloads <- reply + } + }() + } + state.isDead = true + }() + return nil +} + +func (state *LLPState) Wait() { + state.wg.Wait() + state.dirUnlock() + state.Duration = time.Now().Sub(state.started) + state.RxSpeed = state.RxBytes + state.TxSpeed = state.TxBytes + rxDuration := int64(state.RxLastSeen.Sub(state.started).Seconds()) + txDuration := int64(state.TxLastSeen.Sub(state.started).Seconds()) + if rxDuration > 0 { + state.RxSpeed = state.RxBytes / rxDuration + } + if txDuration > 0 { + state.TxSpeed = state.TxBytes / txDuration + } +} + +func (state *LLPState) ProcessLLP(payload []byte) ([][]byte, error) { + sds := SDS{"node": state.NodeId, "nice": strconv.Itoa(int(state.nice))} + r := bytes.NewReader(payload) + var err error + var replies [][]byte + var infosGot bool + for r.Len() > 0 { + state.ctx.LogD("llp-process", sds, "unmarshaling header") + var head LLPHead + if _, err = xdr.Unmarshal(r, &head); err != nil { + state.ctx.LogE("llp-process", SdsAdd(sds, SDS{"err": err}), "") + return nil, err + } + switch head.Type { + case LLPTypeInfo: + infosGot = true + sdsp := SdsAdd(sds, SDS{"type": "info"}) + state.ctx.LogD("llp-process", sdsp, "unmarshaling packet") + var info LLPInfo + if _, err = xdr.Unmarshal(r, &info); err != nil { + state.ctx.LogE("llp-process", SdsAdd(sdsp, SDS{"err": err}), "") + return nil, err + } + sdsp = SdsAdd(sds, SDS{ + "hash": ToBase32(info.Hash[:]), + "size": strconv.FormatInt(int64(info.Size), 10), + }) + if info.Nice > state.nice { + state.ctx.LogD("llp-process", sdsp, "too nice") + continue + } + state.ctx.LogD("llp-process", sdsp, "received") + if state.xxOnly != nil && *state.xxOnly == TTx { + continue + } + state.Lock() + state.infosTheir[*info.Hash] = &info + state.Unlock() + state.ctx.LogD("llp-process", sdsp, "stating part") + fi, err := os.Stat(filepath.Join( + state.ctx.Spool, + state.NodeId.String(), + string(TRx), + ToBase32(info.Hash[:])+PartSuffix, + )) + var offset int64 + if err == nil { + offset = fi.Size() + state.ctx.LogD( + "llp-process", + SdsAdd(sdsp, SDS{"offset": strconv.FormatInt(offset, 10)}), + "part exists", + ) + } + replies = append(replies, MarshalLLP( + LLPTypeFreq, + LLPFreq{info.Hash, uint64(offset)}, + )) + case LLPTypeFile: + state.ctx.LogD( + "llp-process", + SdsAdd(sds, SDS{"type": "file"}), + "unmarshaling packet", + ) + var file LLPFile + if _, err = xdr.Unmarshal(r, &file); err != nil { + state.ctx.LogE("llp-process", SdsAdd(sds, SDS{ + "err": err, + "type": "file", + }), "") + return nil, err + } + sdsp := SdsAdd(sds, SDS{ + "xx": string(TRx), + "hash": ToBase32(file.Hash[:]), + "size": strconv.Itoa(len(file.Payload)), + }) + filePath := filepath.Join( + state.ctx.Spool, + state.NodeId.String(), + string(TRx), + ToBase32(file.Hash[:]), + ) + state.ctx.LogD("llp-file", sdsp, "opening part") + fd, err := os.OpenFile( + filePath+PartSuffix, + os.O_RDWR|os.O_CREATE, + os.FileMode(0600), + ) + if err != nil { + state.ctx.LogE("llp-file", SdsAdd(sdsp, SDS{"err": err}), "") + return nil, err + } + state.ctx.LogD( + "llp-file", + SdsAdd(sdsp, SDS{"offset": strconv.FormatInt(int64(file.Offset), 10)}), + "seeking", + ) + if _, err = fd.Seek(int64(file.Offset), 0); err != nil { + state.ctx.LogE("llp-file", SdsAdd(sdsp, SDS{"err": err}), "") + fd.Close() + return nil, err + } + state.ctx.LogD("llp-file", sdsp, "writing") + _, err = fd.Write(file.Payload) + if err != nil { + state.ctx.LogE("llp-file", SdsAdd(sdsp, SDS{"err": err}), "") + fd.Close() + return nil, err + } + ourSize := uint64(file.Offset) + uint64(len(file.Payload)) + sdsp["fullsize"] = strconv.FormatInt(int64(state.infosTheir[*file.Hash].Size), 10) + sdsp["size"] = strconv.FormatInt(int64(ourSize), 10) + state.ctx.LogP("llp-file", sdsp, "") + if state.infosTheir[*file.Hash].Size != ourSize { + fd.Close() + continue + } + go func() { + if err := fd.Sync(); err != nil { + state.ctx.LogE("llp-file", SdsAdd(sdsp, SDS{"err": err}), "sync") + fd.Close() + return + } + fd.Seek(0, 0) + state.ctx.LogD("llp-file", sdsp, "checking") + gut, err := Check(fd, file.Hash[:]) + fd.Close() + if err != nil || !gut { + state.ctx.LogE("llp-file", sdsp, "checksum mismatch") + return + } + state.ctx.LogI("llp-done", SdsAdd(sdsp, SDS{"xx": string(TRx)}), "") + os.Rename(filePath+PartSuffix, filePath) + state.payloads <- MarshalLLP(LLPTypeDone, LLPDone{file.Hash}) + }() + case LLPTypeDone: + state.ctx.LogD( + "llp-process", + SdsAdd(sds, SDS{"type": "done"}), + "unmarshaling packet", + ) + var done LLPDone + if _, err = xdr.Unmarshal(r, &done); err != nil { + state.ctx.LogE("llp-process", SdsAdd(sds, SDS{ + "type": "done", + "err": err, + }), "") + return nil, err + } + sdsp := SdsAdd(sds, SDS{"hash": ToBase32(done.Hash[:])}) + state.ctx.LogD("llp-done", sdsp, "removing") + err := os.Remove(filepath.Join( + state.ctx.Spool, + state.NodeId.String(), + string(TTx), + ToBase32(done.Hash[:]), + )) + if err == nil { + state.ctx.LogI("llp-done", SdsAdd(sdsp, SDS{"xx": string(TTx)}), "") + } else { + state.ctx.LogE("llp-done", SdsAdd(sdsp, SDS{"xx": string(TTx)}), "") + } + case LLPTypeFreq: + sdsp := SdsAdd(sds, SDS{"type": "freq"}) + state.ctx.LogD("llp-process", sdsp, "unmarshaling packet") + var freq LLPFreq + if _, err = xdr.Unmarshal(r, &freq); err != nil { + state.ctx.LogE("llp-process", SdsAdd(sdsp, SDS{"err": err}), "") + return nil, err + } + state.ctx.LogD("llp-process", SdsAdd(sdsp, SDS{ + "hash": ToBase32(freq.Hash[:]), + "offset": strconv.FormatInt(int64(freq.Offset), 10), + }), "queueing") + state.Lock() + state.queueTheir = append(state.queueTheir, &freq) + state.Unlock() + case LLPTypeHalt: + sdsp := SdsAdd(sds, SDS{"type": "halt"}) + state.ctx.LogD("llp-process", sdsp, "") + state.Lock() + state.queueTheir = nil + state.Unlock() + default: + state.ctx.LogE( + "llp-process", + SdsAdd(sds, SDS{"type": head.Type}), + "unknown", + ) + return nil, BadPktType + } + } + if infosGot { + var pkts int + var size uint64 + for _, info := range state.infosTheir { + pkts++ + size += info.Size + } + state.ctx.LogI("llp-infos", SDS{ + "xx": string(TRx), + "node": state.NodeId, + "pkts": strconv.Itoa(pkts), + "size": strconv.FormatInt(int64(size), 10), + }, "") + } + return payloadsSplit(replies), nil +} diff --git a/src/cypherpunks.ru/nncp/log.go b/src/cypherpunks.ru/nncp/log.go new file mode 100644 index 0000000..0ae0f32 --- /dev/null +++ b/src/cypherpunks.ru/nncp/log.go @@ -0,0 +1,124 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +package nncp + +import ( + "fmt" + "os" + "sort" + "strings" + "time" + + "golang.org/x/sys/unix" +) + +type LogLevel string + +type SDS map[string]interface{} + +func sdFmt(who string, sds SDS) string { + keys := make([]string, 0, len(sds)) + for k, _ := range sds { + keys = append(keys, k) + } + sort.Strings(keys) + result := make([]string, 0, 1+len(keys)) + result = append(result, "["+who) + for _, k := range keys { + result = append(result, fmt.Sprintf(`%s="%s"`, k, sds[k])) + } + return strings.Join(result, " ") + "]" +} + +func msgFmt(level LogLevel, who string, sds SDS, msg string) string { + result := fmt.Sprintf( + "%s %s %s", + level, + time.Now().UTC().Format(time.RFC3339Nano), + sdFmt(who, sds), + ) + if len(msg) > 0 { + result += " " + msg + } + return result + "\n" +} + +func (ctx *Ctx) Log(msg string) { + fdLock, err := os.OpenFile( + ctx.LogPath+".lock", + os.O_CREATE|os.O_WRONLY, + os.FileMode(0600), + ) + if err != nil { + fmt.Fprintln(os.Stderr, "Can not open lock for log:", err) + return + } + fdLockFd := int(fdLock.Fd()) + err = unix.Flock(fdLockFd, unix.LOCK_EX) + if err != nil { + fmt.Fprintln(os.Stderr, "Can not acquire lock for log:", err) + return + } + defer unix.Flock(fdLockFd, unix.LOCK_UN) + fd, err := os.OpenFile( + ctx.LogPath, + os.O_CREATE|os.O_WRONLY|os.O_APPEND, + os.FileMode(0600), + ) + if err != nil { + fmt.Fprintln(os.Stderr, "Can not open log:", err) + return + } + fd.WriteString(msg) + fd.Close() +} + +func (ctx *Ctx) LogD(who string, sds SDS, msg string) { + if !ctx.Debug { + return + } + fmt.Fprint(os.Stderr, msgFmt(LogLevel("D"), who, sds, msg)) +} + +func (ctx *Ctx) LogI(who string, sds SDS, msg string) { + msg = msgFmt(LogLevel("I"), who, sds, msg) + fmt.Fprintln(os.Stderr, ctx.Humanize(msg)) + ctx.Log(msg) +} + +func (ctx *Ctx) LogP(who string, sds SDS, msg string) { + fmt.Fprintln(os.Stderr, ctx.Humanize(msgFmt(LogLevel("P"), who, sds, msg))) +} + +func (ctx *Ctx) LogE(who string, sds SDS, msg string) { + msg = msgFmt(LogLevel("E"), who, sds, msg) + fmt.Fprintln(os.Stderr, ctx.Humanize(msg)) + ctx.Log(msg) +} + +func SdsAdd(sds, add SDS) SDS { + neu := SDS{} + for k, v := range sds { + neu[k] = v + } + for k, v := range add { + neu[k] = v + } + return neu +} diff --git a/src/cypherpunks.ru/nncp/nncp.go b/src/cypherpunks.ru/nncp/nncp.go new file mode 100644 index 0000000..ef44224 --- /dev/null +++ b/src/cypherpunks.ru/nncp/nncp.go @@ -0,0 +1,57 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +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 . +*/ + +// NNCP -- Node-to-Node CoPy +package nncp + +import ( + "runtime" +) + +const ( + Warranty = `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 .` +) + +var ( + Version string +) + +func VersionGet() string { + return "NNCP version " + Version + " built with " + runtime.Version() +} + +func UsageHeader() string { + return VersionGet() + ` +Copyright (C) 2016-2017 Sergey Matveev +License GPLv3+: GNU GPL version 3 or later +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. + +` +} diff --git a/src/cypherpunks.ru/nncp/node.go b/src/cypherpunks.ru/nncp/node.go new file mode 100644 index 0000000..a86f37e --- /dev/null +++ b/src/cypherpunks.ru/nncp/node.go @@ -0,0 +1,107 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +package nncp + +import ( + "crypto/rand" + "errors" + + "github.com/flynn/noise" + "golang.org/x/crypto/blake2b" + "golang.org/x/crypto/ed25519" + "golang.org/x/crypto/nacl/box" +) + +type NodeId [blake2b.Size256]byte + +func (id NodeId) String() string { + return ToBase32(id[:]) +} + +type Node struct { + Name string + Id *NodeId + ExchPub *[32]byte + SignPub ed25519.PublicKey + NoisePub *[32]byte + Incoming *string + Freq *string + Via []*NodeId +} + +type NodeOur struct { + Id *NodeId + ExchPub *[32]byte + ExchPrv *[32]byte + SignPub ed25519.PublicKey + SignPrv ed25519.PrivateKey + NoisePub *[32]byte + NoisePrv *[32]byte +} + +func NewNodeGenerate() (*NodeOur, error) { + exchPub, exchPrv, err := box.GenerateKey(rand.Reader) + if err != nil { + return nil, err + } + signPub, signPrv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + return nil, err + } + noiseKey := noise.DH25519.GenerateKeypair(rand.Reader) + noisePub := new([32]byte) + noisePrv := new([32]byte) + copy(noisePrv[:], noiseKey.Private) + copy(noisePub[:], noiseKey.Public) + + id := NodeId(blake2b.Sum256([]byte(signPub))) + node := NodeOur{ + Id: &id, + ExchPub: exchPub, + ExchPrv: exchPrv, + SignPub: signPub, + SignPrv: signPrv, + NoisePub: noisePub, + NoisePrv: noisePrv, + } + return &node, nil +} + +func (nodeOur *NodeOur) Their() *Node { + return &Node{ + Name: "self", + Id: nodeOur.Id, + ExchPub: nodeOur.ExchPub, + SignPub: nodeOur.SignPub, + } +} + +func NodeIdFromString(raw string) (*NodeId, error) { + decoded, err := FromBase32(raw) + if err != nil { + return nil, err + } + if len(decoded) != blake2b.Size256 { + return nil, errors.New("Invalid node id size") + } + buf := new([blake2b.Size256]byte) + copy(buf[:], decoded) + nodeId := NodeId(*buf) + return &nodeId, nil +} diff --git a/src/cypherpunks.ru/nncp/pkt.go b/src/cypherpunks.ru/nncp/pkt.go new file mode 100644 index 0000000..56b5a47 --- /dev/null +++ b/src/cypherpunks.ru/nncp/pkt.go @@ -0,0 +1,278 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +package nncp + +import ( + "bytes" + "crypto/cipher" + "crypto/rand" + "crypto/subtle" + "errors" + "hash" + "io" + + "github.com/davecgh/go-xdr/xdr2" + "golang.org/x/crypto/blake2b" + "golang.org/x/crypto/curve25519" + "golang.org/x/crypto/ed25519" + "golang.org/x/crypto/hkdf" + "golang.org/x/crypto/nacl/box" + "golang.org/x/crypto/twofish" +) + +type PktType uint8 + +const ( + PktTypeFile PktType = iota + PktTypeFreq PktType = iota + PktTypeMail PktType = iota + PktTypeTrns PktType = iota + + MaxPathSize = 1<<8 - 1 + + DefaultNiceMail = 64 + DefaultNiceFreq = 196 + DefaultNiceFile = 196 +) + +var ( + MagicNNCPPv1 [8]byte = [8]byte{'N', 'N', 'C', 'P', 'P', 1, 0, 0} + MagicNNCPEv1 [8]byte = [8]byte{'N', 'N', 'C', 'P', 'E', 1, 0, 0} + BadMagic error = errors.New("Unknown magic number") + BadPktType error = errors.New("Unknown packet type") + + PktOverhead int64 + PktEncOverhead int64 +) + +type Pkt struct { + Magic [8]byte + Type PktType + PathLen uint8 + Path *[MaxPathSize]byte +} + +type PktTbs struct { + Magic [8]byte + Nice uint8 + Recipient *NodeId + Sender *NodeId + ExchPub *[32]byte + Size uint64 +} + +type PktEnc struct { + Magic [8]byte + Nice uint8 + Sender *NodeId + ExchPub *[32]byte + Sign *[ed25519.SignatureSize]byte + Size uint64 +} + +func init() { + pkt := Pkt{ + Type: PktTypeFile, + Path: new([MaxPathSize]byte), + } + var buf bytes.Buffer + n, err := xdr.Marshal(&buf, pkt) + if err != nil { + panic(err) + } + PktOverhead = int64(n) + blake2b.Size256 + buf.Reset() + + dummyId, err := NodeIdFromString("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA") + if err != nil { + panic(err) + } + pktEnc := PktEnc{ + Magic: MagicNNCPEv1, + Nice: 123, + Sender: dummyId, + ExchPub: new([32]byte), + Sign: new([ed25519.SignatureSize]byte), + Size: 123, + } + n, err = xdr.Marshal(&buf, pktEnc) + if err != nil { + panic(err) + } + PktEncOverhead = int64(n) +} + +func NewPkt(typ PktType, path string) (*Pkt, error) { + pb := []byte(path) + if len(pb) > MaxPathSize { + return nil, errors.New("Too long path") + } + pkt := Pkt{ + Magic: MagicNNCPPv1, + Type: typ, + PathLen: uint8(len(pb)), + Path: new([MaxPathSize]byte), + } + copy(pkt.Path[:], pb) + return &pkt, nil +} + +func blake256() hash.Hash { + h, err := blake2b.New256(nil) + if err != nil { + panic(err) + } + return h +} + +func PktEncWrite(our *NodeOur, their *Node, pkt *Pkt, nice uint8, size int64, data io.Reader, out io.Writer) error { + pubEph, prvEph, err := box.GenerateKey(rand.Reader) + if err != nil { + return err + } + var pktBuf bytes.Buffer + if _, err := xdr.Marshal(&pktBuf, pkt); err != nil { + return err + } + tbs := PktTbs{ + Magic: MagicNNCPEv1, + Nice: nice, + Recipient: their.Id, + Sender: our.Id, + ExchPub: pubEph, + Size: uint64(size + PktOverhead), + } + var tbsBuf bytes.Buffer + if _, err = xdr.Marshal(&tbsBuf, &tbs); err != nil { + return err + } + signature := new([ed25519.SignatureSize]byte) + copy(signature[:], ed25519.Sign(our.SignPrv, tbsBuf.Bytes())) + pktEnc := PktEnc{ + Magic: MagicNNCPEv1, + Nice: nice, + Sender: our.Id, + ExchPub: pubEph, + Sign: signature, + Size: tbs.Size, + } + if _, err = xdr.Marshal(out, &pktEnc); err != nil { + return err + } + sharedKey := new([32]byte) + curve25519.ScalarMult(sharedKey, prvEph, their.ExchPub) + kdf := hkdf.New(blake256, sharedKey[:], nil, MagicNNCPEv1[:]) + keyEnc := make([]byte, 32) + if _, err = io.ReadFull(kdf, keyEnc); err != nil { + return err + } + keyAuth := make([]byte, 64) + if _, err = io.ReadFull(kdf, keyAuth); err != nil { + return err + } + ciph, err := twofish.NewCipher(keyEnc) + if err != nil { + return err + } + ctr := cipher.NewCTR(ciph, make([]byte, twofish.BlockSize)) + mac, err := blake2b.New256(keyAuth) + if err != nil { + return err + } + mw := io.MultiWriter(out, mac) + ae := &cipher.StreamWriter{S: ctr, W: mw} + ae.Write(pktBuf.Bytes()) + if _, err = io.CopyN(ae, data, int64(size)); err != nil { + return err + } + ae.Close() + out.Write(mac.Sum(nil)) + return nil +} + +func TbsVerify(our *NodeOur, their *Node, pktEnc *PktEnc) (bool, error) { + tbs := PktTbs{ + Magic: MagicNNCPEv1, + Nice: pktEnc.Nice, + Recipient: our.Id, + Sender: their.Id, + ExchPub: pktEnc.ExchPub, + Size: pktEnc.Size, + } + var tbsBuf bytes.Buffer + if _, err := xdr.Marshal(&tbsBuf, &tbs); err != nil { + return false, err + } + return ed25519.Verify(their.SignPub, tbsBuf.Bytes(), pktEnc.Sign[:]), nil +} + +func PktEncRead(our *NodeOur, nodes map[NodeId]*Node, data io.Reader, out io.Writer) (*Node, error) { + var pktEnc PktEnc + _, err := xdr.Unmarshal(data, &pktEnc) + if err != nil { + return nil, err + } + if pktEnc.Magic != MagicNNCPEv1 { + return nil, BadMagic + } + their, known := nodes[*pktEnc.Sender] + if !known { + return nil, errors.New("Unknown sender") + } + verified, err := TbsVerify(our, their, &pktEnc) + if err != nil { + return nil, err + } + if !verified { + return their, errors.New("Invalid signature") + } + sharedKey := new([32]byte) + curve25519.ScalarMult(sharedKey, our.ExchPrv, pktEnc.ExchPub) + kdf := hkdf.New(blake256, sharedKey[:], nil, MagicNNCPEv1[:]) + keyEnc := make([]byte, 32) + if _, err = io.ReadFull(kdf, keyEnc); err != nil { + return their, err + } + keyAuth := make([]byte, 64) + if _, err = io.ReadFull(kdf, keyAuth); err != nil { + return their, err + } + ciph, err := twofish.NewCipher(keyEnc) + if err != nil { + return their, err + } + ctr := cipher.NewCTR(ciph, make([]byte, twofish.BlockSize)) + mac, err := blake2b.New256(keyAuth) + if err != nil { + return their, err + } + trA := io.TeeReader(data, mac) + ae := &cipher.StreamReader{S: ctr, R: trA} + if _, err = io.CopyN(out, ae, int64(pktEnc.Size)-blake2b.Size256); err != nil { + return their, err + } + tag := make([]byte, blake2b.Size256) + if _, err = io.ReadFull(data, tag); err != nil { + return their, err + } + if subtle.ConstantTimeCompare(mac.Sum(nil), tag) != 1 { + return their, errors.New("Unauthenticated payload") + } + return their, nil +} diff --git a/src/cypherpunks.ru/nncp/pkt_test.go b/src/cypherpunks.ru/nncp/pkt_test.go new file mode 100644 index 0000000..95d765e --- /dev/null +++ b/src/cypherpunks.ru/nncp/pkt_test.go @@ -0,0 +1,109 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +package nncp + +import ( + "bytes" + "testing" + "testing/quick" + + "github.com/davecgh/go-xdr/xdr2" +) + +func TestPktEncWrite(t *testing.T) { + nodeOur, err := NewNodeGenerate() + if err != nil { + panic(err) + } + nodeTheir, err := NewNodeGenerate() + if err != nil { + panic(err) + } + f := func(path string, pathSize uint8, data [1 << 16]byte, size uint16) bool { + dataR := bytes.NewReader(data[:]) + var ct bytes.Buffer + if len(path) > int(pathSize) { + path = path[:int(pathSize)] + } + pkt, err := NewPkt(PktTypeFile, path) + if err != nil { + panic(err) + } + err = PktEncWrite(nodeOur, nodeTheir.Their(), pkt, 123, int64(size), dataR, &ct) + if err != nil { + return false + } + var pktEnc PktEnc + if _, err = xdr.Unmarshal(&ct, &pktEnc); err != nil { + return false + } + if *pktEnc.Sender != *nodeOur.Id { + return false + } + if pktEnc.Size != uint64(ct.Len()) { + return false + } + return true + } + if err := quick.Check(f, nil); err != nil { + t.Error(err) + } +} + +func TestPktEncRead(t *testing.T) { + node1, err := NewNodeGenerate() + if err != nil { + panic(err) + } + node2, err := NewNodeGenerate() + if err != nil { + panic(err) + } + f := func(path string, pathSize uint8, data [1 << 16]byte, size uint16) bool { + dataR := bytes.NewReader(data[:]) + var ct bytes.Buffer + if len(path) > int(pathSize) { + path = path[:int(pathSize)] + } + pkt, err := NewPkt(PktTypeFile, path) + if err != nil { + panic(err) + } + err = PktEncWrite(node1, node2.Their(), pkt, 123, int64(size), dataR, &ct) + if err != nil { + return false + } + var pt bytes.Buffer + nodes := make(map[NodeId]*Node) + nodes[*node1.Id] = node1.Their() + node, err := PktEncRead(node2, nodes, &ct, &pt) + if err != nil { + return false + } + if *node.Id != *node1.Id { + return false + } + var pktBuf bytes.Buffer + xdr.Marshal(&pktBuf, &pkt) + return bytes.Compare(pt.Bytes(), append(pktBuf.Bytes(), data[:int(size)]...)) == 0 + } + if err := quick.Check(f, nil); err != nil { + t.Error(err) + } +} diff --git a/src/cypherpunks.ru/nncp/sortbynice.go b/src/cypherpunks.ru/nncp/sortbynice.go new file mode 100644 index 0000000..9e68f52 --- /dev/null +++ b/src/cypherpunks.ru/nncp/sortbynice.go @@ -0,0 +1,15 @@ +package nncp + +type ByNice []*LLPInfo + +func (a ByNice) Len() int { + return len(a) +} + +func (a ByNice) Swap(i, j int) { + a[i], a[j] = a[j], a[i] +} + +func (a ByNice) Less(i, j int) bool { + return a[i].Nice < a[j].Nice +} diff --git a/src/cypherpunks.ru/nncp/tmp.go b/src/cypherpunks.ru/nncp/tmp.go new file mode 100644 index 0000000..6cb6723 --- /dev/null +++ b/src/cypherpunks.ru/nncp/tmp.go @@ -0,0 +1,89 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +package nncp + +import ( + "bufio" + "hash" + "io" + "io/ioutil" + "os" + "path/filepath" + + "golang.org/x/crypto/blake2b" +) + +func (ctx *Ctx) NewTmpFile() (*os.File, error) { + jobsPath := filepath.Join(ctx.Spool, "tmp") + var err error + if err = os.MkdirAll(jobsPath, os.FileMode(0700)); err != nil { + return nil, err + } + fd, err := ioutil.TempFile(jobsPath, "") + if err == nil { + ctx.LogD("tmp", SDS{"src": fd.Name()}, "created") + } + return fd, err +} + +type TmpFileWHash struct { + W *bufio.Writer + Fd *os.File + hsh hash.Hash + ctx *Ctx +} + +func (ctx *Ctx) NewTmpFileWHash() (*TmpFileWHash, error) { + tmp, err := ctx.NewTmpFile() + if err != nil { + return nil, err + } + hsh, err := blake2b.New256(nil) + if err != nil { + return nil, err + } + return &TmpFileWHash{ + W: bufio.NewWriter(io.MultiWriter(hsh, tmp)), + Fd: tmp, + hsh: hsh, + ctx: ctx, + }, nil +} + +func (tmp *TmpFileWHash) Cancel() { + tmp.Fd.Truncate(0) + tmp.Fd.Close() + os.Remove(tmp.Fd.Name()) +} + +func (tmp *TmpFileWHash) Commit(dir string) error { + var err error + if err = os.MkdirAll(dir, os.FileMode(0700)); err != nil { + return err + } + if err = tmp.W.Flush(); err != nil { + tmp.Fd.Close() + return err + } + tmp.Fd.Sync() + tmp.Fd.Close() + checksum := ToBase32(tmp.hsh.Sum(nil)) + tmp.ctx.LogD("tmp", SDS{"src": tmp.Fd.Name(), "dst": checksum}, "commit") + return os.Rename(tmp.Fd.Name(), filepath.Join(dir, checksum)) +} diff --git a/src/cypherpunks.ru/nncp/toss.go b/src/cypherpunks.ru/nncp/toss.go new file mode 100644 index 0000000..e95f7be --- /dev/null +++ b/src/cypherpunks.ru/nncp/toss.go @@ -0,0 +1,279 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +package nncp + +import ( + "bufio" + "compress/zlib" + "fmt" + "io" + "io/ioutil" + "log" + "mime" + "os" + "os/exec" + "path" + "path/filepath" + "strconv" + "strings" + + "github.com/davecgh/go-xdr/xdr2" + "github.com/dustin/go-humanize" + "golang.org/x/crypto/blake2b" + "golang.org/x/sys/unix" +) + +func newNotification(fromTo *FromToYAML, subject string) io.Reader { + return strings.NewReader(fmt.Sprintf( + "From: %s\nTo: %s\nSubject: %s\n", + fromTo.From, + fromTo.To, + mime.BEncoding.Encode("UTF-8", subject), + )) +} + +func (ctx *Ctx) LockDir(nodeId *NodeId, xx TRxTx) (*os.File, error) { + lockPath := filepath.Join(ctx.Spool, nodeId.String(), string(xx)) + ".lock" + dirLock, err := os.OpenFile( + lockPath, + os.O_CREATE|os.O_WRONLY, + os.FileMode(0600), + ) + if err != nil { + ctx.LogE("lockdir", SDS{"path": lockPath, "err": err}, "") + return nil, err + } + err = unix.Flock(int(dirLock.Fd()), unix.LOCK_EX|unix.LOCK_NB) + if err != nil { + ctx.LogE("lockdir", SDS{"path": lockPath, "err": err}, "") + dirLock.Close() + return nil, err + } + return dirLock, nil +} + +func (ctx *Ctx) UnlockDir(fd *os.File) { + if fd != nil { + unix.Flock(int(fd.Fd()), unix.LOCK_UN) + fd.Close() + } +} + +func (ctx *Ctx) Toss(nodeId *NodeId, nice uint8) { + dirLock, err := ctx.LockDir(nodeId, TRx) + if err != nil { + return + } + defer ctx.UnlockDir(dirLock) + for job := range ctx.Jobs(nodeId, TRx) { + pktName := filepath.Base(job.Fd.Name()) + sds := SDS{"node": job.PktEnc.Sender, "pkt": pktName} + if job.PktEnc.Nice > nice { + ctx.LogD("rx", SdsAdd(sds, SDS{ + "nice": strconv.Itoa(int(job.PktEnc.Nice)), + }), "too nice") + continue + } + pipeR, pipeW := io.Pipe() + errs := make(chan error, 1) + go func(job Job) { + pipeWB := bufio.NewWriter(pipeW) + _, err := PktEncRead( + ctx.Self, + ctx.Neigh, + bufio.NewReader(job.Fd), + pipeWB, + ) + errs <- err + pipeWB.Flush() + pipeW.Close() + job.Fd.Close() + if err != nil { + ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "decryption") + } + }(job) + var pkt Pkt + var err error + var pktSize int64 + if _, err = xdr.Unmarshal(pipeR, &pkt); err != nil { + ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "unmarshal") + goto Closing + } + pktSize = job.Size - PktEncOverhead - PktOverhead + sds["size"] = strconv.FormatInt(pktSize, 10) + ctx.LogD("rx", sds, "taken") + switch pkt.Type { + case PktTypeMail: + recipients := string(pkt.Path[:int(pkt.PathLen)]) + sds := SdsAdd(sds, SDS{ + "type": "mail", + "dst": recipients, + }) + decompressor, err := zlib.NewReader(pipeR) + if err != nil { + log.Fatalln(err) + } + cmd := exec.Command( + ctx.Sendmail[0], + append( + ctx.Sendmail[1:len(ctx.Sendmail)], + strings.Split(recipients, " ")..., + )..., + ) + cmd.Stdin = decompressor + if err = cmd.Run(); err != nil { + ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "sendmail") + goto Closing + } + ctx.LogI("rx", sds, "") + if err = os.Remove(job.Fd.Name()); err != nil { + ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "remove") + } + case PktTypeFile: + dst := string(pkt.Path[:int(pkt.PathLen)]) + sds := SdsAdd(sds, SDS{"type": "file", "dst": dst}) + incoming := ctx.Neigh[*job.PktEnc.Sender].Incoming + if incoming == nil { + ctx.LogE("rx", sds, "incoming is not allowed") + goto Closing + } + dir := filepath.Join(*incoming, path.Dir(dst)) + if err = os.MkdirAll(dir, os.FileMode(0700)); err != nil { + ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "mkdir") + goto Closing + } + tmp, err := ioutil.TempFile(dir, "nncp-file") + sds["tmp"] = tmp.Name() + ctx.LogD("rx", sds, "created") + if err != nil { + ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "mktemp") + goto Closing + } + bufW := bufio.NewWriter(tmp) + if _, err = io.Copy(bufW, pipeR); err != nil { + ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "copy") + goto Closing + } + bufW.Flush() + tmp.Sync() + tmp.Close() + dstPathOrig := filepath.Join(*incoming, dst) + dstPath := dstPathOrig + dstPathCtr := 0 + for { + if _, err = os.Stat(dstPath); err != nil { + if os.IsNotExist(err) { + break + } + ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "stat") + goto Closing + } + dstPath = dstPathOrig + strconv.Itoa(dstPathCtr) + dstPathCtr++ + } + if err = os.Rename(tmp.Name(), dstPath); err != nil { + ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "rename") + } + delete(sds, "tmp") + ctx.LogI("rx", sds, "") + if err = os.Remove(job.Fd.Name()); err != nil { + ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "remove") + } + if ctx.NotifyFile != nil { + cmd := exec.Command( + ctx.Sendmail[0], + append( + ctx.Sendmail[1:len(ctx.Sendmail)], + ctx.NotifyFile.To, + )..., + ) + cmd.Stdin = newNotification(ctx.NotifyFile, fmt.Sprintf( + "File from %s: %s (%s)", + ctx.Neigh[*job.PktEnc.Sender].Name, + dst, + humanize.IBytes(uint64(pktSize)), + )) + cmd.Run() + } + case PktTypeFreq: + src := string(pkt.Path[:int(pkt.PathLen)]) + sds := SdsAdd(sds, SDS{"type": "freq", "src": src}) + dstRaw, err := ioutil.ReadAll(pipeR) + if err != nil { + ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "read") + goto Closing + } + dst := string(dstRaw) + sds["dst"] = dst + sender := ctx.Neigh[*job.PktEnc.Sender] + freq := sender.Freq + if freq == nil { + ctx.LogE("rx", sds, "freqing is not allowed") + goto Closing + } + err = ctx.TxFile(sender, job.PktEnc.Nice, filepath.Join(*freq, src), dst) + if err != nil { + ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "tx file") + goto Closing + } + ctx.LogI("rx", sds, "") + if err = os.Remove(job.Fd.Name()); err != nil { + ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "remove") + } + if ctx.NotifyFreq != nil { + cmd := exec.Command( + ctx.Sendmail[0], + append( + ctx.Sendmail[1:len(ctx.Sendmail)], + ctx.NotifyFreq.To, + )..., + ) + cmd.Stdin = newNotification(ctx.NotifyFreq, fmt.Sprintf( + "Freq from %s: %s", + ctx.Neigh[*job.PktEnc.Sender].Name, + src, + )) + cmd.Run() + } + case PktTypeTrns: + dst := new([blake2b.Size256]byte) + copy(dst[:], pkt.Path[:int(pkt.PathLen)]) + nodeId := NodeId(*dst) + node, known := ctx.Neigh[nodeId] + sds := SdsAdd(sds, SDS{"type": "trns", "dst": nodeId}) + if !known { + ctx.LogE("rx", sds, "unknown node") + goto Closing + } + ctx.LogD("rx", sds, "taken") + if err = ctx.TxTrns(node, job.PktEnc.Nice, pktSize, pipeR); err != nil { + ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "tx trns") + goto Closing + } + ctx.LogI("rx", sds, "") + if err = os.Remove(job.Fd.Name()); err != nil { + ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "remove") + } + default: + ctx.LogE("rx", sds, "unknown type") + } + Closing: + pipeR.Close() + } +} diff --git a/src/cypherpunks.ru/nncp/toss_test.go b/src/cypherpunks.ru/nncp/toss_test.go new file mode 100644 index 0000000..4751f29 --- /dev/null +++ b/src/cypherpunks.ru/nncp/toss_test.go @@ -0,0 +1,458 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +package nncp + +import ( + "bytes" + "crypto/rand" + "fmt" + "io" + "io/ioutil" + "os" + "path/filepath" + "strconv" + "testing" + "testing/quick" + + "github.com/davecgh/go-xdr/xdr2" + "golang.org/x/crypto/blake2b" +) + +var ( + TDebug bool = false +) + +func dirFiles(path string) []string { + dir, err := os.Open(path) + if err != nil { + panic(err) + } + defer dir.Close() + names, err := dir.Readdirnames(0) + if err != nil { + panic(err) + } + return names +} + +func TestTossEmail(t *testing.T) { + f := func(recipients [16]uint8) bool { + for i, recipient := range recipients { + recipients[i] = recipient % 8 + } + spool, err := ioutil.TempDir("", "testtoss") + if err != nil { + panic(err) + } + defer os.RemoveAll(spool) + nodeOur, err := NewNodeGenerate() + if err != nil { + panic(err) + } + ctx := Ctx{ + Spool: spool, + Self: nodeOur, + Neigh: make(map[NodeId]*Node), + Alias: make(map[string]*NodeId), + LogPath: filepath.Join(spool, "log.log"), + Debug: TDebug, + } + ctx.Neigh[*nodeOur.Id] = nodeOur.Their() + privates := make(map[uint8]*NodeOur) + for _, recipient := range recipients { + if _, exists := privates[recipient]; exists { + continue + } + our, err := NewNodeGenerate() + if err != nil { + panic(err) + } + privates[recipient] = our + ctx.Neigh[*our.Id] = our.Their() + } + for _, recipient := range recipients { + if err := ctx.TxMail( + ctx.Neigh[*privates[recipient].Id], + DefaultNiceMail, + "recipient", + []byte{123}, + ); err != nil { + panic(err) + } + } + for _, recipient := range recipients { + ctx.Self = privates[recipient] + rxPath := filepath.Join(spool, ctx.Self.Id.String(), string(TRx)) + os.Rename(filepath.Join(spool, ctx.Self.Id.String(), string(TTx)), rxPath) + if len(dirFiles(rxPath)) == 0 { + continue + } + ctx.Toss(ctx.Self.Id, DefaultNiceMail-1) + if len(dirFiles(rxPath)) == 0 { + return false + } + ctx.Sendmail = []string{"/bin/sh", "-c", "false"} + ctx.Toss(ctx.Self.Id, DefaultNiceMail) + if len(dirFiles(rxPath)) == 0 { + return false + } + ctx.Sendmail = []string{ + "/bin/sh", "-c", + fmt.Sprintf("cat >> %s", filepath.Join(spool, "mbox")), + } + ctx.Toss(ctx.Self.Id, DefaultNiceMail) + if len(dirFiles(rxPath)) != 0 { + return false + } + } + mbox, err := ioutil.ReadFile(filepath.Join(spool, "mbox")) + if err != nil { + return false + } + expected := make([]byte, 0, 16) + for i := 0; i < 16; i++ { + expected = append(expected, 123) + } + return bytes.Compare(mbox, expected) == 0 + } + if err := quick.Check(f, nil); err != nil { + t.Error(err) + } +} + +func TestTossFile(t *testing.T) { + f := func(fileSizes []uint8) bool { + if len(fileSizes) == 0 { + return true + } + files := make(map[string][]byte) + for i, fileSize := range fileSizes { + data := make([]byte, fileSize) + if _, err := io.ReadFull(rand.Reader, data); err != nil { + panic(err) + } + files[strconv.Itoa(i)] = data + } + spool, err := ioutil.TempDir("", "testtoss") + if err != nil { + panic(err) + } + defer os.RemoveAll(spool) + nodeOur, err := NewNodeGenerate() + if err != nil { + panic(err) + } + ctx := Ctx{ + Spool: spool, + Self: nodeOur, + Neigh: make(map[NodeId]*Node), + Alias: make(map[string]*NodeId), + LogPath: filepath.Join(spool, "log.log"), + Debug: TDebug, + } + ctx.Neigh[*nodeOur.Id] = nodeOur.Their() + incomingPath := filepath.Join(spool, "incoming") + for _, fileData := range files { + checksum := blake2b.Sum256(fileData) + fileName := ToBase32(checksum[:]) + src := filepath.Join(spool, fileName) + if err := ioutil.WriteFile(src, fileData, os.FileMode(0600)); err != nil { + panic(err) + } + if err := ctx.TxFile( + ctx.Neigh[*nodeOur.Id], + DefaultNiceFile, + src, + fileName, + ); err != nil { + panic(err) + } + } + rxPath := filepath.Join(spool, ctx.Self.Id.String(), string(TRx)) + os.Rename(filepath.Join(spool, ctx.Self.Id.String(), string(TTx)), rxPath) + ctx.Toss(ctx.Self.Id, DefaultNiceFile) + if len(dirFiles(rxPath)) == 0 { + return false + } + ctx.Neigh[*nodeOur.Id].Incoming = &incomingPath + ctx.Toss(ctx.Self.Id, DefaultNiceFile) + if len(dirFiles(rxPath)) != 0 { + return false + } + for _, fileData := range files { + checksum := blake2b.Sum256(fileData) + fileName := ToBase32(checksum[:]) + data, err := ioutil.ReadFile(filepath.Join(incomingPath, fileName)) + if err != nil { + panic(err) + } + if bytes.Compare(data, fileData) != 0 { + return false + } + } + return true + } + if err := quick.Check(f, nil); err != nil { + t.Error(err) + } +} + +func TestTossFileSameName(t *testing.T) { + f := func(filesRaw uint8) bool { + files := int(filesRaw)%8 + 1 + spool, err := ioutil.TempDir("", "testtoss") + if err != nil { + panic(err) + } + defer os.RemoveAll(spool) + nodeOur, err := NewNodeGenerate() + if err != nil { + panic(err) + } + ctx := Ctx{ + Spool: spool, + Self: nodeOur, + Neigh: make(map[NodeId]*Node), + Alias: make(map[string]*NodeId), + LogPath: filepath.Join(spool, "log.log"), + Debug: TDebug, + } + ctx.Neigh[*nodeOur.Id] = nodeOur.Their() + srcPath := filepath.Join(spool, "junk") + if err = ioutil.WriteFile( + srcPath, + []byte("doesnotmatter"), + os.FileMode(0600), + ); err != nil { + panic(err) + } + incomingPath := filepath.Join(spool, "incoming") + for i := 0; i < files; i++ { + if err := ctx.TxFile( + ctx.Neigh[*nodeOur.Id], + DefaultNiceFile, + srcPath, + "samefile", + ); err != nil { + panic(err) + } + } + rxPath := filepath.Join(spool, ctx.Self.Id.String(), string(TRx)) + os.Rename(filepath.Join(spool, ctx.Self.Id.String(), string(TTx)), rxPath) + ctx.Neigh[*nodeOur.Id].Incoming = &incomingPath + ctx.Toss(ctx.Self.Id, DefaultNiceFile) + expected := make(map[string]struct{}) + expected["samefile"] = struct{}{} + for i := 0; i < files-1; i++ { + expected["samefile"+strconv.Itoa(i)] = struct{}{} + } + for _, filename := range dirFiles(incomingPath) { + if _, exists := expected[filename]; !exists { + return false + } + delete(expected, filename) + } + if len(expected) != 0 { + return false + } + return true + } + if err := quick.Check(f, nil); err != nil { + t.Error(err) + } +} + +func TestTossFreq(t *testing.T) { + f := func(fileSizes []uint8) bool { + if len(fileSizes) == 0 { + return true + } + spool, err := ioutil.TempDir("", "testtoss") + if err != nil { + panic(err) + } + defer os.RemoveAll(spool) + nodeOur, err := NewNodeGenerate() + if err != nil { + panic(err) + } + ctx := Ctx{ + Spool: spool, + Self: nodeOur, + Neigh: make(map[NodeId]*Node), + Alias: make(map[string]*NodeId), + LogPath: filepath.Join(spool, "log.log"), + Debug: TDebug, + } + ctx.Neigh[*nodeOur.Id] = nodeOur.Their() + files := make(map[string][]byte) + for i, fileSize := range fileSizes { + fileData := make([]byte, fileSize) + if _, err := io.ReadFull(rand.Reader, fileData); err != nil { + panic(err) + } + fileName := strconv.Itoa(i) + files[fileName] = fileData + if err := ctx.TxFreq( + ctx.Neigh[*nodeOur.Id], + DefaultNiceFreq, + fileName, + fileName, + ); err != nil { + panic(err) + } + } + rxPath := filepath.Join(spool, ctx.Self.Id.String(), string(TRx)) + txPath := filepath.Join(spool, ctx.Self.Id.String(), string(TTx)) + os.Rename(txPath, rxPath) + os.MkdirAll(txPath, os.FileMode(0700)) + ctx.Toss(ctx.Self.Id, DefaultNiceFreq) + if len(dirFiles(txPath)) != 0 || len(dirFiles(rxPath)) == 0 { + return false + } + ctx.Neigh[*nodeOur.Id].Freq = &spool + ctx.Toss(ctx.Self.Id, DefaultNiceFreq) + if len(dirFiles(txPath)) != 0 || len(dirFiles(rxPath)) == 0 { + return false + } + for fileName, fileData := range files { + if err := ioutil.WriteFile( + filepath.Join(spool, fileName), + fileData, + os.FileMode(0600), + ); err != nil { + panic(err) + } + } + ctx.Toss(ctx.Self.Id, DefaultNiceFreq) + if len(dirFiles(txPath)) == 0 || len(dirFiles(rxPath)) != 0 { + return false + } + for job := range ctx.Jobs(ctx.Self.Id, TTx) { + var buf bytes.Buffer + _, err := PktEncRead(ctx.Self, ctx.Neigh, job.Fd, &buf) + if err != nil { + panic(err) + } + var pkt Pkt + if _, err = xdr.Unmarshal(&buf, &pkt); err != nil { + panic(err) + } + dst := string(pkt.Path[:int(pkt.PathLen)]) + if bytes.Compare(buf.Bytes(), files[dst]) != 0 { + return false + } + } + return true + } + if err := quick.Check(f, nil); err != nil { + t.Error(err) + } +} + +func TestTossTrns(t *testing.T) { + f := func(datumLens []uint8) bool { + if len(datumLens) == 0 { + return true + } + datum := make(map[int][]byte) + for i, datumLen := range datumLens { + datumLen += 64 + data := make([]byte, datumLen) + if _, err := io.ReadFull(rand.Reader, data); err != nil { + panic(err) + } + datum[i] = data + } + spool, err := ioutil.TempDir("", "testtoss") + if err != nil { + panic(err) + } + defer os.RemoveAll(spool) + nodeOur, err := NewNodeGenerate() + if err != nil { + panic(err) + } + ctx := Ctx{ + Spool: spool, + Self: nodeOur, + Neigh: make(map[NodeId]*Node), + Alias: make(map[string]*NodeId), + LogPath: filepath.Join(spool, "log.log"), + Debug: TDebug, + } + ctx.Neigh[*nodeOur.Id] = nodeOur.Their() + rxPath := filepath.Join(spool, ctx.Self.Id.String(), string(TRx)) + os.MkdirAll(rxPath, os.FileMode(0700)) + txPath := filepath.Join(spool, ctx.Self.Id.String(), string(TTx)) + os.MkdirAll(txPath, os.FileMode(0700)) + for _, data := range datum { + pktTrans := Pkt{ + Magic: MagicNNCPPv1, + Type: PktTypeTrns, + PathLen: blake2b.Size256, + Path: new([MaxPathSize]byte), + } + copy(pktTrans.Path[:], nodeOur.Id[:]) + var dst bytes.Buffer + if err := PktEncWrite( + ctx.Self, + ctx.Neigh[*nodeOur.Id], + &pktTrans, + 123, + int64(len(data)), + bytes.NewReader(data), + &dst, + ); err != nil { + panic(err) + } + checksum := blake2b.Sum256(dst.Bytes()) + if err := ioutil.WriteFile( + filepath.Join(rxPath, ToBase32(checksum[:])), + dst.Bytes(), + os.FileMode(0600), + ); err != nil { + panic(err) + } + } + ctx.Toss(ctx.Self.Id, 123) + if len(dirFiles(rxPath)) != 0 { + return false + } + for _, filename := range dirFiles(txPath) { + dataRead, err := ioutil.ReadFile(filepath.Join(txPath, filename)) + if err != nil { + panic(err) + } + for k, data := range datum { + if bytes.Compare(dataRead, data) == 0 { + delete(datum, k) + break + } + } + } + if len(datum) > 0 { + return false + } + return true + } + if err := quick.Check(f, nil); err != nil { + t.Error(err) + } +} diff --git a/src/cypherpunks.ru/nncp/tx.go b/src/cypherpunks.ru/nncp/tx.go new file mode 100644 index 0000000..0f40fb9 --- /dev/null +++ b/src/cypherpunks.ru/nncp/tx.go @@ -0,0 +1,247 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +package nncp + +import ( + "bufio" + "bytes" + "compress/zlib" + "errors" + "io" + "os" + "path" + "path/filepath" + "strconv" + "strings" + + "golang.org/x/crypto/blake2b" +) + +func (ctx *Ctx) Tx(node *Node, pkt *Pkt, nice uint8, size int64, src io.Reader) (*Node, error) { + tmp, err := ctx.NewTmpFileWHash() + if err != nil { + return nil, err + } + hops := make([]*Node, 0, 1+len(node.Via)) + hops = append(hops, node) + lastNode := node + for i := len(node.Via); i > 0; i-- { + lastNode = ctx.Neigh[*node.Via[i-1]] + hops = append(hops, lastNode) + } + errs := make(chan error) + curSize := size + pipeR, pipeW := io.Pipe() + go func(size int64, src io.Reader, dst io.WriteCloser) { + ctx.LogD("tx", SDS{ + "node": hops[0].Id, + "nice": strconv.Itoa(int(nice)), + "size": strconv.FormatInt(size, 10), + }, "wrote") + errs <- PktEncWrite(ctx.Self, hops[0], pkt, nice, size, src, dst) + dst.Close() + }(curSize, src, pipeW) + + var pipeRPrev io.Reader + for i := 1; i < len(hops); i++ { + pktTrans := Pkt{ + Magic: MagicNNCPPv1, + Type: PktTypeTrns, + PathLen: blake2b.Size256, + Path: new([MaxPathSize]byte), + } + copy(pktTrans.Path[:], hops[i-1].Id[:]) + curSize += PktOverhead + PktEncOverhead + pipeRPrev = pipeR + pipeR, pipeW = io.Pipe() + go func(node *Node, pkt *Pkt, size int64, src io.Reader, dst io.WriteCloser) { + ctx.LogD("tx", SDS{ + "node": node.Id, + "nice": strconv.Itoa(int(nice)), + "size": strconv.FormatInt(size, 10), + }, "trns wrote") + errs <- PktEncWrite(ctx.Self, node, pkt, nice, size, src, dst) + dst.Close() + }(hops[i], &pktTrans, curSize, pipeRPrev, pipeW) + } + go func() { + _, err := io.Copy(tmp.W, pipeR) + errs <- err + }() + for i := 0; i <= len(hops); i++ { + err = <-errs + if err != nil { + tmp.Fd.Close() + return nil, err + } + } + nodePath := filepath.Join(ctx.Spool, lastNode.Id.String()) + err = tmp.Commit(filepath.Join(nodePath, string(TTx))) + os.Symlink(nodePath, filepath.Join(ctx.Spool, lastNode.Name)) + return lastNode, err +} + +func (ctx *Ctx) TxFile(node *Node, nice uint8, srcPath, dstPath string) error { + dstPath = path.Clean(dstPath) + if path.IsAbs(dstPath) { + return errors.New("Relative destination path required") + } + pkt, err := NewPkt(PktTypeFile, dstPath) + if err != nil { + return err + } + src, err := os.Open(srcPath) + if err != nil { + return err + } + defer src.Close() + srcStat, err := src.Stat() + if err != nil { + return err + } + _, err = ctx.Tx(node, pkt, nice, srcStat.Size(), bufio.NewReader(src)) + if err == nil { + ctx.LogI("tx", SDS{ + "type": "file", + "node": node.Id, + "nice": strconv.Itoa(int(nice)), + "src": srcPath, + "dst": dstPath, + "size": strconv.FormatInt(srcStat.Size(), 10), + }, "sent") + } else { + ctx.LogE("tx", SDS{ + "type": "file", + "node": node.Id, + "nice": strconv.Itoa(int(nice)), + "src": srcPath, + "dst": dstPath, + "size": strconv.FormatInt(srcStat.Size(), 10), + "err": err, + }, "sent") + } + return err +} + +func (ctx *Ctx) TxFreq(node *Node, nice uint8, srcPath, dstPath string) error { + dstPath = path.Clean(dstPath) + if path.IsAbs(dstPath) { + return errors.New("Relative destination path required") + } + srcPath = path.Clean(srcPath) + if path.IsAbs(srcPath) { + return errors.New("Relative source path required") + } + pkt, err := NewPkt(PktTypeFreq, srcPath) + if err != nil { + return err + } + src := strings.NewReader(dstPath) + size := int64(src.Len()) + _, err = ctx.Tx(node, pkt, nice, size, src) + if err == nil { + ctx.LogI("tx", SDS{ + "type": "freq", + "node": node.Id, + "nice": strconv.Itoa(int(nice)), + "src": srcPath, + "dst": dstPath, + }, "sent") + } else { + ctx.LogE("tx", SDS{ + "type": "freq", + "node": node.Id, + "nice": strconv.Itoa(int(nice)), + "src": srcPath, + "dst": dstPath, + "err": err, + }, "sent") + } + return err +} + +func (ctx *Ctx) TxMail(node *Node, nice uint8, recipient string, body []byte) error { + pkt, err := NewPkt(PktTypeMail, recipient) + if err != nil { + return err + } + var compressed bytes.Buffer + compressor := zlib.NewWriter(&compressed) + if _, err = io.Copy(compressor, bytes.NewReader(body)); err != nil { + return err + } + compressor.Close() + size := int64(compressed.Len()) + _, err = ctx.Tx(node, pkt, nice, size, &compressed) + if err == nil { + ctx.LogI("tx", SDS{ + "type": "mail", + "node": node.Id, + "nice": strconv.Itoa(int(nice)), + "dst": recipient, + "size": strconv.FormatInt(size, 10), + }, "sent") + } else { + ctx.LogE("tx", SDS{ + "type": "mail", + "node": node.Id, + "nice": strconv.Itoa(int(nice)), + "dst": recipient, + "size": strconv.FormatInt(size, 10), + "err": err, + }, "sent") + } + return err +} + +func (ctx *Ctx) TxTrns(node *Node, nice uint8, size int64, src io.Reader) error { + ctx.LogD("tx", SDS{ + "type": "trns", + "node": node.Id, + "nice": strconv.Itoa(int(nice)), + "size": strconv.FormatInt(size, 10), + }, "taken") + tmp, err := ctx.NewTmpFileWHash() + if err != nil { + return err + } + if _, err = io.Copy(tmp.W, src); err != nil { + return err + } + nodePath := filepath.Join(ctx.Spool, node.Id.String()) + err = tmp.Commit(filepath.Join(nodePath, string(TTx))) + if err == nil { + ctx.LogI("tx", SDS{ + "type": "trns", + "node": node.Id, + "nice": strconv.Itoa(int(nice)), + "size": strconv.FormatInt(size, 10), + }, "sent") + } else { + ctx.LogI("tx", SDS{ + "type": "trns", + "node": node.Id, + "nice": strconv.Itoa(int(nice)), + "size": strconv.FormatInt(size, 10), + "err": err, + }, "sent") + } + os.Symlink(nodePath, filepath.Join(ctx.Spool, node.Name)) + return err +} diff --git a/src/cypherpunks.ru/nncp/tx_test.go b/src/cypherpunks.ru/nncp/tx_test.go new file mode 100644 index 0000000..c582719 --- /dev/null +++ b/src/cypherpunks.ru/nncp/tx_test.go @@ -0,0 +1,139 @@ +/* +NNCP -- Node-to-Node CoPy +Copyright (C) 2016-2017 Sergey Matveev + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +package nncp + +import ( + "bytes" + "io" + "io/ioutil" + "os" + "path" + "strings" + "testing" + "testing/quick" + + "github.com/davecgh/go-xdr/xdr2" + "golang.org/x/crypto/blake2b" +) + +func TestTx(t *testing.T) { + f := func(hops uint8, pathSrc, data string, nice uint8) bool { + if len(pathSrc) > int(MaxPathSize) { + pathSrc = pathSrc[:MaxPathSize] + } + hops = hops % 4 + hops = 1 + spool, err := ioutil.TempDir("", "testtx") + if err != nil { + panic(err) + } + defer os.RemoveAll(spool) + nodeOur, err := NewNodeGenerate() + if err != nil { + panic(err) + } + nodeTgtOur, err := NewNodeGenerate() + if err != nil { + panic(err) + } + nodeTgt := nodeTgtOur.Their() + ctx := Ctx{ + Spool: spool, + LogPath: path.Join(spool, "log.log"), + Debug: true, + Self: nodeOur, + Neigh: make(map[NodeId]*Node, hops), + Alias: make(map[string]*NodeId), + } + ctx.Neigh[*nodeOur.Id] = nodeOur.Their() + ctx.Neigh[*nodeTgt.Id] = nodeTgt + privates := make(map[NodeId]*NodeOur, int(hops)+1) + privates[*nodeTgt.Id] = nodeTgtOur + privates[*nodeOur.Id] = nodeOur + for i := uint8(0); i < hops; i++ { + node, err := NewNodeGenerate() + if err != nil { + panic(err) + } + ctx.Neigh[*node.Id] = node.Their() + privates[*node.Id] = node + nodeTgt.Via = append(nodeTgt.Via, node.Id) + } + pkt, err := NewPkt(PktTypeMail, pathSrc) + src := strings.NewReader(data) + dstNode, err := ctx.Tx(nodeTgt, pkt, 123, int64(src.Len()), src) + if err != nil { + return false + } + + sentJobs := make([]Job, 0, 1) + for txJob := range ctx.Jobs(dstNode.Id, TTx) { + sentJobs = append(sentJobs, txJob) + } + if len(sentJobs) != 1 { + return false + } + txJob := sentJobs[0] + defer txJob.Fd.Close() + var bufR bytes.Buffer + if _, err = io.Copy(&bufR, txJob.Fd); err != nil { + panic(err) + } + var bufW bytes.Buffer + vias := append(nodeTgt.Via, nodeTgt.Id) + for i, hopId := range vias { + hopOur := privates[*hopId] + foundNode, err := PktEncRead(hopOur, ctx.Neigh, &bufR, &bufW) + if err != nil { + return false + } + if *foundNode.Id != *nodeOur.Id { + return false + } + bufR, bufW = bufW, bufR + bufW.Reset() + var pkt Pkt + if _, err = xdr.Unmarshal(&bufR, &pkt); err != nil { + return false + } + if *hopId == *nodeTgt.Id { + if pkt.Type != PktTypeMail { + return false + } + if !bytes.HasPrefix(pkt.Path[:], []byte(pathSrc)) { + return false + } + if bytes.Compare(bufR.Bytes(), []byte(data)) != 0 { + return false + } + } else { + if pkt.Type != PktTypeTrns { + return false + } + if bytes.Compare(pkt.Path[:blake2b.Size256], vias[i+1][:]) != 0 { + return false + } + } + } + return true + } + if err := quick.Check(f, nil); err != nil { + t.Error(err) + } +} diff --git a/src/github.com/davecgh/go-xdr b/src/github.com/davecgh/go-xdr new file mode 160000 index 0000000..e6a2ba0 --- /dev/null +++ b/src/github.com/davecgh/go-xdr @@ -0,0 +1 @@ +Subproject commit e6a2ba005892b6a5b27cb5352f64c2e96942dd28 diff --git a/src/github.com/devi/blake2 b/src/github.com/devi/blake2 new file mode 160000 index 0000000..8470047 --- /dev/null +++ b/src/github.com/devi/blake2 @@ -0,0 +1 @@ +Subproject commit 8470047b978ec419f8551faea5bd64d89bfed6cc diff --git a/src/github.com/devi/chap b/src/github.com/devi/chap new file mode 160000 index 0000000..3d48f07 --- /dev/null +++ b/src/github.com/devi/chap @@ -0,0 +1 @@ +Subproject commit 3d48f07b8862a3450870ec7793ecf5b02bff6790 diff --git a/src/github.com/dustin/go-humanize b/src/github.com/dustin/go-humanize new file mode 160000 index 0000000..ef638b6 --- /dev/null +++ b/src/github.com/dustin/go-humanize @@ -0,0 +1 @@ +Subproject commit ef638b6c2e62b857442c6443dace9366a48c0ee2 diff --git a/src/github.com/flynn/noise b/src/github.com/flynn/noise new file mode 160000 index 0000000..c01f33c --- /dev/null +++ b/src/github.com/flynn/noise @@ -0,0 +1 @@ +Subproject commit c01f33c4187eed59e3e3a75ca1000e2b3501d28a diff --git a/src/github.com/minio/blake2b-simd b/src/github.com/minio/blake2b-simd new file mode 160000 index 0000000..3f5f724 --- /dev/null +++ b/src/github.com/minio/blake2b-simd @@ -0,0 +1 @@ +Subproject commit 3f5f724cb5b182a5c278d6d3d55b40e7f8c2efb4 diff --git a/src/golang.org/x/crypto b/src/golang.org/x/crypto new file mode 160000 index 0000000..5b4074c --- /dev/null +++ b/src/golang.org/x/crypto @@ -0,0 +1 @@ +Subproject commit 5b4074c2c416448b5d06e287167144493aabda43 diff --git a/src/golang.org/x/net b/src/golang.org/x/net new file mode 160000 index 0000000..905989b --- /dev/null +++ b/src/golang.org/x/net @@ -0,0 +1 @@ +Subproject commit 905989bd20b7c354fd28a61074eed1c8f49ebc89 diff --git a/src/golang.org/x/sys b/src/golang.org/x/sys new file mode 160000 index 0000000..d75a526 --- /dev/null +++ b/src/golang.org/x/sys @@ -0,0 +1 @@ +Subproject commit d75a52659825e75fff6158388dddc6a5b04f9ba5 diff --git a/src/gopkg.in/check.v1 b/src/gopkg.in/check.v1 new file mode 160000 index 0000000..20d25e2 --- /dev/null +++ b/src/gopkg.in/check.v1 @@ -0,0 +1 @@ +Subproject commit 20d25e2804050c1cd24a7eea1e7a6447dd0e74ec diff --git a/src/gopkg.in/yaml.v2 b/src/gopkg.in/yaml.v2 new file mode 160000 index 0000000..a5b47d3 --- /dev/null +++ b/src/gopkg.in/yaml.v2 @@ -0,0 +1 @@ +Subproject commit a5b47d31c556af34a302ce5d659e6fea44d90de0