Compare commits

...

53 Commits
1.2.0 ... main

Author SHA1 Message Date
Kasianov Nikolai Alekseevich 1d8f987c27 Removed old email from license notices; minor changes to the program output, help message 2 years ago
Gitea b30d0c3465 No more github 2 years ago
Gitea 6bb927a26e Being idependent from github 2 years ago
Unbewohnte c2bd2cb0cf Apparently my name is spelled differently in English ¯\_(ツ)_/¯ 3 years ago
Unbewohnte 2548fa68e7 Less syscalls to open files on the receiving end 3 years ago
Unbewohnte 8eb2f181fd Symlinks support ! 3 years ago
Unbewohnte 700811b179 [checksum] Micro optimisations; [node] Renamed nodes to receiving and sending; [fsys] ftu now DOES NOT die on 'permission denied's 3 years ago
Unbewohnte 21d16c590f Updated README: I can't be inspired by a thing I've never used, can I ?... Tehehe~ 3 years ago
Unbewohnte 4d12a15a58 [Node] Invalid transfer info printing is >>|FIXED|<< 3 years ago
Unbewohnte 382908c1e5 Updated copyright year 3 years ago
Unbewohnte e4c086b358 make release 3 years ago
Unbewohnte 0ac9cd2b71 v2.2.0; Fixed freezing on big amount of files; Improved transfer data printing; Introduction to some minor bugs with it as well, but that is not a severe problem anyway 3 years ago
Unbewohnte 75cb68dd30 [node] fixed one-file transfer logical issue 3 years ago
Unbewohnte 550c6e26ef [main] changed version 3 years ago
Unbewohnte 74464c9470 [main] verbose output flag changed to ?; [node] added 3 microsecond delay in sender node when sending file info packets 3 years ago
Unbewohnte a8e973645a [main] added a missing new line for verbose output usage message 3 years ago
Unbewohnte d0a0eaf780 [Make] output clean executable names 3 years ago
Unbewohnte 5aae65980d [Make] remove release folders after zipping 3 years ago
Unbewohnte 3a40920af5 Verbose output 3 years ago
Unbewohnte 502877c515 [main] changed version string; [make] pkgrelease for easy cross-building 3 years ago
Unbewohnte 09e3c7b960 [node] print transfer info. The output is not flooded anymore on receiver 3 years ago
Unbewohnte 1a302cb9fb [node] bugfixes? [make] cross compilation automatisation 3 years ago
Unbewohnte b2cff053b0 Removed an old license file 3 years ago
Unbewohnte 9e730bee4c Moved to GPLv3 3 years ago
Unbewohnte fab8aa947b [protocol] added ALREADYHAVE packet; [node] fixed logical path error when receiving a single file; ALREADY HAVE FILE FEATURE 3 years ago
Unbewohnte d598b4d1e7 [README] updated information 3 years ago
Unbewohnte 6ec5eabc93 [fsys] fixed relative path finding; [node] fixed recursive transfer of a directory 3 years ago
Unbewohnte 075c342dbd [protocol] added relative path logic to the FILE packet; [fsys] file relative path to its parent directory; [node&&FTU] CAN SEND DIRECTORIES RECURSIVELY 3 years ago
Unbewohnte d0a8d22d12 [node] non-recursive directory send !; [Makefile] tests 3 years ago
Unbewohnte eb7cd49b0e [fsys] file checksums are automatically generated when GetFile is called; [protocol] ACCEPT and REJECT packets do not need to include file ids now; [node] progress on sending directories 3 years ago
Unbewohnte 1d08ae1ac4 [fsys] get directory files; [node] started to implement directory transfer. DOES NOT WORK NOW 3 years ago
Unbewohnte f2b0cec266 [node|protocol] implemented transfer offer packet construction; moved packets implementation from node package to protocol; fixed a race during offer rejection in receiving node 3 years ago
Unbewohnte c6d2bc80db [README] updated information; [installation process] added install.sh; [protocol] added DIRECTORY header description 3 years ago
Unbewohnte 205fbcc2d3 [node] unexported unnecessary struct fields, divided transferInfo into sending and receiving parts; implemented yet untested sendDirectoryPacket 3 years ago
Unbewohnte 442af0205e [node] clearer sendPiece error handling in sender node 3 years ago
Unbewohnte d0d15f2bd5 [node] improved mainloop logic 3 years ago
Unbewohnte 5b1d964cad [node] documentation 3 years ago
Unbewohnte f0332c8a7f [fsys] correctly calculate directory size 3 years ago
Unbewohnte 49b25443fe Encryption 3 years ago
Unbewohnte 2da9cd5bd0 Rewrite; Current status: can send one file, not encrypted 3 years ago
Unbewohnte 73eb91dce3 Bolerplate code for node 3 years ago
Unbewohnte 77823b1b94 Started to rewrite the entire thing; The old code is still there for now 3 years ago
Unbewohnte a0780a1a5d Removed unnecessary function 3 years ago
Unbewohnte 00729e0f26 Added a license flag 3 years ago
Unbewohnte ac68ddb395 Changed MAXPACKETSIZE, added a time of completion 3 years ago
Unbewohnte 4381de0041 Appropriate 3 years ago
Unbewohnte d30ac7900e Print defaults if no flags specified 3 years ago
Unbewohnte a43b0a10b3 Installation script, improved README 3 years ago
Unbewohnte 1aa968d93e Added a handling for interrupt signal 3 years ago
Unbewohnte 4f5165fa3a Improved flags validation 3 years ago
Unbewohnte 82a1391c9c Added more tests; Probably the last commit for this project; Stopped gaining fun and it's already complete imo 3 years ago
Unbewohnte d7665618de Added first tests 3 years ago
Unbewohnte c1cab012f4 Added printing state of the transfer feature 3 years ago
  1. 2
      .gitignore
  2. 219
      COPYING
  3. 9
      LICENSE
  4. 49
      Makefile
  5. 99
      README.md
  6. 104
      checksum/checksum.go
  7. 30
      encryption/decrypt.go
  8. 24
      encryption/encrypt.go
  9. 27
      encryption/key.go
  10. 3
      go.mod
  11. 11
      install.sh
  12. 72
      main.go
  13. 17
      protocol/constants.go
  14. 83
      protocol/headers.go
  15. 162
      protocol/packet.go
  16. 30
      receiver/file.go
  17. 315
      receiver/receiver.go
  18. 45
      sender/file.go
  19. 35
      sender/ip.go
  20. 297
      sender/sender.go
  21. 219
      src/COPYING
  22. 38
      src/addr/local.go
  23. 101
      src/checksum/checksum.go
  24. 45
      src/checksum/checksum_test.go
  25. 51
      src/encryption/decrypt.go
  26. 45
      src/encryption/encrypt.go
  27. 31
      src/encryption/encryption_test.go
  28. 47
      src/encryption/key.go
  29. 211
      src/fsys/dir.go
  30. 103
      src/fsys/dir_test.go
  31. 115
      src/fsys/file.go
  32. 59
      src/fsys/file_test.go
  33. 70
      src/fsys/symlink.go
  34. 42
      src/fsys/symlink_test.go
  35. 3
      src/go.mod
  36. 142
      src/main.go
  37. 927
      src/node/node.go
  38. 40
      src/node/options.go
  39. 38
      src/protocol/constants.go
  40. 123
      src/protocol/headers.go
  41. 134
      src/protocol/packet.go
  42. 103
      src/protocol/packetConstruct.go
  43. 189
      src/protocol/packetDecode.go
  44. 101
      src/protocol/protocol_test.go
  45. 89
      src/protocol/recv.go
  46. 244
      src/protocol/send.go
  47. 0
      src/testfiles/testDownload/testfile.txt
  48. 9
      src/testfiles/testdir/testdir2/testfile3.txt
  49. 9
      src/testfiles/testdir/testfile2.txt
  50. 1
      src/testfiles/testdir/testsymlink2.txt
  51. 1
      src/testfiles/testdir3/nested1/nested2/testfilen.txt
  52. 3
      src/testfiles/testdir3/testfile4
  53. 11
      src/testfiles/testfile.txt
  54. 1
      src/testfiles/testsymlink.txt

2
.gitignore vendored

@ -1,4 +1,6 @@
FTU
FTU.exe
ftu
ftu.exe
release/
downloads/

219
COPYING

@ -0,0 +1,219 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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 <https://www.gnu.org/licenses/why-not-lgpl.html>.

9
LICENSE

@ -1,9 +0,0 @@
The MIT License (MIT)
Copyright © 2021 Unbewohne | Nikolay Kasyanov
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

49
Makefile

@ -0,0 +1,49 @@
.DEFAULT_GOAL := all
SRC_DIR := src/
EXE_NAME := ftu
INSTALLATION_DIR := /usr/local/bin/
RELEASE_DIR := release
LICENSE_FILE := COPYING
INSTALLATION_SCRIPT := install.sh
all:
cd $(SRC_DIR) && go build && mv $(EXE_NAME) ..
release:
rm -rf $(RELEASE_DIR)
mkdir $(RELEASE_DIR)
mkdir $(RELEASE_DIR)/ftu_linux_amd64
mkdir $(RELEASE_DIR)/ftu_darwin_amd64
mkdir $(RELEASE_DIR)/ftu_windows_amd64
cd $(SRC_DIR) && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o ftu && mv ftu ../$(RELEASE_DIR)/ftu_linux_amd64
cd $(SRC_DIR) && CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -o ftu && mv ftu ../$(RELEASE_DIR)/ftu_darwin_amd64
cd $(SRC_DIR) && CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o ftu.exe && mv ftu.exe ../$(RELEASE_DIR)/ftu_windows_amd64
cp $(LICENSE_FILE) $(RELEASE_DIR)/ftu_linux_amd64
cp $(INSTALLATION_SCRIPT) $(RELEASE_DIR)/ftu_linux_amd64
cp $(LICENSE_FILE) $(RELEASE_DIR)/ftu_darwin_amd64
cp $(LICENSE_FILE) $(RELEASE_DIR)/ftu_windows_amd64
cd $(RELEASE_DIR) && zip -r ftu_linux_amd64 ftu_linux_amd64/
cd $(RELEASE_DIR) && zip -r ftu_darwin_amd64 ftu_darwin_amd64/
cd $(RELEASE_DIR) && zip -r ftu_windows_amd64 ftu_windows_amd64/
rm -rf $(RELEASE_DIR)/ftu_linux_amd64
rm -rf $(RELEASE_DIR)/ftu_darwin_amd64
rm -rf $(RELEASE_DIR)/ftu_windows_amd64
race:
cd $(SRC_DIR) && go build -race && mv $(EXE_NAME) ..
install: all
cp $(EXE_NAME) $(INSTALLATION_DIR)
test:
cd $(SRC_DIR) && go test ./...
clean:
rm -rf $(EXE_NAME) $(RELEASE_DIR)

99
README.md

@ -1,25 +1,22 @@
# FTU (FileTransferringUtility)
# ftu (FileTransferringUtility)
## Send files through the Net !
---
## What is that ?
This application is like an FTP server, but overcomplicated and probably overengineered monstrosity. (basically a file server, but P2P).
## What is that ?
A P2P (decentralized) file sharing program, overcomplicated and an overengineered one.
---
## Why ?
## ● Why ?
Learning
---
## How does this work ?
## How does this work ?
In order to transfer one file on one computer to another - they need to establish a connection.
In order to establish a connection - there needs to be a 1) sender (server) (the owner of the file), waiting for connections, and a 2) receiver (client), who will try to connect to a sender (server). If the requirements are met - a client will connect to a server and the packet exchange will begin.
In order to establish a connection - there needs to be a 1) sender (server) (the owner of the file), waiting for connections, and a 2) receiver (client), who will try to connect to a sender (server). If the requirements are met - client will connect to server and the packet exchange will begin.
The server and the client needs to communicate with packets according to certain rules, given by a [protocol](https://github.com/Unbewohnte/FTU/tree/main/protocol).
The server and the client needs to communicate with packets according to certain rules, given by a [protocol](http://unbewohnte.xyz:3000/Unbewohnte/ftu/src/branch/main/src/protocol).
The packet has its header and body. They are divided into several groups of use by headers, this way we can specify what kind of data is stored inside packet`s body and react accordingly.
@ -28,71 +25,63 @@ Thus, with a connection and a way of communication, the sender will send some pa
---
## Known issues|problems|lack of features|reasons why it`s bad
- **VERY** slow; somewhat FIXED - [x], now **faster** than before
- **VERY** expensive on resources; somewhat FIXED - [x], no more **json manipulations**, only **raw bytes**`s wizardry !
- If `MAXFILEDATASIZE` is bigger than appr. 1024 - the packets on the other end will not be unmarshalled due to error ??; FIXED - [x], unnecessary, wrong, deprecated, **destroyed !!!**
- Lack of proper error-handling; somewhat FIXED - [x]
- Lack of information about the process of transferring (ETA, lost packets, etc.); FIXED - [ ]
- No way to verify if the transferred file is not corrupted; FIXED via checksum- [x]
- No encryption; FIXED via AES encryption of packets` body - [x]
- Messy and hard to follow code && file structure; FIXED? - [x]
- No way to stop the download/upload and resume it later or even during the next connection; FIXED - [ ]
- No tests; FIXED - [ ]
## ● Installation
## Good points
- It works.
---
## Installation
### From release (Pre-compiled)
- Proceed to [releases page](https://github.com/Unbewohnte/FTU/releases)
### ● From release (Pre-compiled)
- Proceed to [releases page](http://unbewohnte.xyz:3000/Unbewohnte/ftu/releases)
- Choose a version/architecture you have and download an archive
- Unpack an archive
- If on GNU/Linux - run `chmod +x install.sh && sudo ./install.sh`
### From source (Compile it yourself) (You need [Go](https://golang.org/dl/) and [git](https://git-scm.com/) to be installed on your machine)
- `git clone https://github.com/Unbewohnte/FTU.git`
### ● From source (Compile it yourself) (You need [Go](https://golang.org/dl/) and [git](https://git-scm.com/) to be installed on your machine)
- `git clone http://unbewohnte.xyz:3000/Unbewohnte/ftu`
- `cd` into the folder
- `go build` - to simply compile for your OS/ARCHITECTURE || `CGO_ENABLED=0 GOOS=os_here GOARCH=arch_here go build` - to cross-compile a static executable for the OS/ARCHITECTURE of your choice (`go tool dist list` - to view the available ones)
- If on GNU/Linux - run `make && sudo make install` or `make && chmod +x install.sh && sudo ./install`
- else - cd into src/ folder and simply run `go build`; after that you`re free to put the binary wherever you desire
### After installation
- You probably want to put the executable in some folder and in order not to use it directly from there all the time - add it to the **$PATH** variable
Now you have ftu installed !
---
## Usage
`./FTU [FLAGS_HERE]` or `FTU [FLAGS_HERE]`
## Usage
`ftu -h` - to print a usage message
### Flags
`./FTU --help` - to get all flags` description
`ftu [FLAGs]`
- `-port` (int) - specifies a working port (if sending - listens on this port, else - tries to connect to this port);
- `-addr` (string) - specifies an address to connect to;
- `-sharefile` (string) - specifies path to a file you want to share, if given a valid path - sender will offer to download this file to receiver;
- `-downloadto` (string) - specifies path to a folder where the receiver wants to store downloaded file;
### ● FLAGs
- -p [uint] for port
- -r [true|false] for recursive sending of a directory
- -a [ip_address|domain_name] address to connect to (cannot be used with -s)
- -d [path_to_directory] where the files will be downloaded to (cannot be used with -s)
- -s [path_to_file|directory] to send it (cannot be used with -a)
- -? [true|false] to turn on|off verbose output
- -v print version text
- -l print license
### Examples
### Examples
- `./FTU -sharefile="/home/some_path_here/FILETOSHARE.zip"` - creates a server that will share `FILETOSHARE.zip` on port `8080`
- `./FTU -sharefile="/home/some_path_here/FILETOSHARE.zip" - port=727` - same as before, but on port `727`
- `./FTU -downloadto="/home/some_path_here/Downloads/" -addr="192.168.1.104"` - creates a client (receiver) that will try to connect to `192.168.1.104` (local device) on port `8080` and if successful - downloads a file to given path
- `./FTU -downloadto="/home/some_path_here/Downloads/" -addr=145.125.53.212 -port=8888` - same as before, but will try to connect to `145.125.53.212` on port `8888`
`ftu -p 89898 -s /home/user/Downloads/someVideo.mp4`
creates a node on a non-default port 89898 that will send "someVideo.mp4" to the other node that connects to you
`ftu -p 7277 -a 192.168.1.104 -d .`
creates a node that will connect to 192.168.1.104:7277 and download served file|directory to the working directory
---
`ftu -p 7277 -a 192.168.1.104 -d /home/user/Downloads/`
creates a node that will connect to 192.168.1.104:7277 and download served file|directory to "/home/user/Downloads/"
## IMPORTANT NOTE
This is NOT intended to be a serious application. I'm learning and this is a product of my curiosity. If you're a beginner too, please don't try to find something useful in my code, I am not an expert.
`ftu -s /home/user/homework`
creates a node that will send every file in the directory
Also, this utility only works if both the server and the client have a port-forwarding|virtual server enabled and configured. Fortunatelly, locally it works without any port-forwarding|virtual servers.
`ftu -r -s /home/user/homework/`
creates a node that will send every file in the directory !RECUSRIVELY!
---
## Inspired by [croc](https://github.com/schollz/croc)
## ● Testing
`make test` or in "src" directory `go test ./...`
---
## License
MIT
## License
GPLv3 license

104
checksum/checksum.go

@ -1,104 +0,0 @@
package checksum
import (
"crypto/sha256"
"fmt"
"io"
"os"
)
const CHECKSUMLEN uint = 32
type CheckSum [CHECKSUMLEN]byte
// returns a checksum of given file. NOTE, that it creates checksum
// not of a full file (from all file bytes), but from separate byte blocks.
// This is done as an optimisation because the file can be very large in size.
// The general idea:
// BOF... CHUNK -> STEP -> CHUNK... EOF
// checksum := sha256.Sum256(ALLCHUNKS)
// GetPartialCheckSum is default method used to get a file checksum by sender and receiver
func GetPartialCheckSum(file *os.File) (CheckSum, error) {
// "capturing" CHUNKSIZE bytes and then skipping STEP bytes before the next chunk until the last one
const CHUNKS uint = 100
const CHUNKSIZE uint = 100
const STEP uint = 250
fileStats, err := file.Stat()
if err != nil {
return [CHECKSUMLEN]byte{}, fmt.Errorf("could not get the stats: %s", err)
}
fileSize := fileStats.Size()
if fileSize < int64(CHUNKS*CHUNKSIZE+STEP*(CHUNKS-1)) {
// file is too small, doing full checksum
checksum, err := getFullCheckSum(file)
if err != nil {
return [CHECKSUMLEN]byte{}, err
}
return checksum, nil
}
var capturedChunks string
var read uint64 = 0
for i := 0; uint(i) < CHUNKS; i++ {
buffer := make([]byte, CHUNKSIZE)
r, _ := file.ReadAt(buffer, int64(read))
capturedChunks += string(buffer)
read += uint64(r)
read += uint64(STEP)
}
checksum := sha256.Sum256([]byte(capturedChunks))
return checksum, nil
}
// Returns a sha256 checksum of given file
func getFullCheckSum(file *os.File) (CheckSum, error) {
filebytes, err := io.ReadAll(file)
if err != nil {
return [CHECKSUMLEN]byte{}, fmt.Errorf("could not read the file: %s", err)
}
checksum := sha256.Sum256(filebytes)
return checksum, nil
}
// Simply compares 2 given checksums. If they are equal - returns true
func AreEqual(checksum1, checksum2 CheckSum) bool {
var i int = 0
for _, checksum1Byte := range checksum1 {
checksum2Byte := checksum2[i]
if checksum1Byte != checksum2Byte {
return false
}
i++
}
return true
}
// Tries to convert given bytes into CheckSum type
func BytesToChecksum(bytes []byte) (CheckSum, error) {
if uint(len(bytes)) > CHECKSUMLEN {
return CheckSum{}, fmt.Errorf("provided bytes` length is bigger than the checksum`s")
}
var checksum [CHECKSUMLEN]byte
for index, b := range bytes {
checksum[index] = b
}
return CheckSum(checksum), nil
}
// Converts given checksum into []byte
func ChecksumToBytes(checksum CheckSum) []byte {
var checksumBytes []byte
for _, b := range checksum {
checksumBytes = append(checksumBytes, b)
}
return checksumBytes
}

30
encryption/decrypt.go

@ -1,30 +0,0 @@
package encryption
import (
"crypto/aes"
"crypto/cipher"
"fmt"
)
// Decrypts encrypted aes data with given key.
// https://www.melvinvivas.com/how-to-encrypt-and-decrypt-data-using-aes/ - very grateful to the author, THANK YOU.
func Decrypt(key, dataToDecrypt []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("could not create new AES cipher: %s", err)
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("could not create new GCM: %s", err)
}
nonce, encryptedBytes := dataToDecrypt[:aesGCM.NonceSize()], dataToDecrypt[aesGCM.NonceSize():]
decryptedData, err := aesGCM.Open(nil, nonce, encryptedBytes, nil)
if err != nil {
return nil, fmt.Errorf("could not decrypt given data: %s", err)
}
return decryptedData, nil
}

24
encryption/encrypt.go

@ -1,24 +0,0 @@
package encryption
import (
"crypto/aes"
"crypto/cipher"
"fmt"
)
// Encrypts given data using aes encryption.
// https://www.melvinvivas.com/how-to-encrypt-and-decrypt-data-using-aes/ - very grateful to the author, THANK YOU.
func Encrypt(key, dataToEncrypt []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("could not create new AES cipher: %s", err)
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("could not create new GCM: %s", err)
}
nonce := make([]byte, aesGCM.NonceSize())
encryptedData := aesGCM.Seal(nonce, nonce, dataToEncrypt, nil)
return encryptedData, nil
}

27
encryption/key.go

@ -1,27 +0,0 @@
package encryption
import (
"math/rand"
"time"
)
// using aes256, so 32 bytes-long key
const KEYLEN uint = 32
const CHARS string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
// Generates 32 pseudo-random bytes to use as a key
func Generate32AESkey() []byte {
var generatedKey []byte
rand.Seed(time.Now().UTC().UnixNano())
// choosing "random" 32 bytes from CHARS
for {
if len(generatedKey) == int(KEYLEN) {
break
}
randomIndex := rand.Intn(len(CHARS))
generatedKey = append(generatedKey, CHARS[randomIndex])
}
return generatedKey
}

3
go.mod

@ -1,3 +0,0 @@
module github.com/Unbewohnte/FTU
go 1.16

11
install.sh

@ -0,0 +1,11 @@
#!/bin/bash
EXE_NAME=ftu
INSTALLATION_DIR=/usr/local/bin/
if [ -f $EXE_NAME ]; then
cp $EXE_NAME $INSTALLATION_DIR
else
echo "No $EXE_NAME found in current directory"
fi

72
main.go

@ -1,72 +0,0 @@
package main
import (
"flag"
"fmt"
"os"
"strings"
"github.com/Unbewohnte/FTU/receiver"
"github.com/Unbewohnte/FTU/sender"
)
// flags
var PORT *int = flag.Int("port", 8080, "Specifies a port for a sender|port to connect to")
var SENDERADDR *string = flag.String("addr", "", "Specifies an address to connect to")
var DOWNLOADSFOLDER *string = flag.String("downloadto", "", "Specifies where the receiver will store downloaded file")
var SHAREDFILE *string = flag.String("sharefile", "", "Specifies what file sender will send")
var SENDING bool
// Input-validation
func processFlags() {
if *PORT < 0 {
fmt.Println("Invalid port !")
os.Exit(-1)
}
// going to send file -> sending
if strings.TrimSpace(*SHAREDFILE) != "" {
SENDING = true
}
// specifying address to connect to -> receiving
if strings.TrimSpace(*SENDERADDR) != "" {
if SENDING {
fmt.Println("Cannot specify an address when sharing !")
os.Exit(-1)
}
SENDING = false
}
// specifying path to download to -> receiving
if strings.TrimSpace(*DOWNLOADSFOLDER) != "" {
if SENDING {
fmt.Println("Cannot specify a downloads directory when sharing !")
os.Exit(-1)
}
SENDING = false
}
}
// parse flags, validate given values
func init() {
flag.Parse()
processFlags()
}
func main() {
if SENDING {
// 1) create sender -> 2) wait for a connection ->|
// 3) send info about the file -> 4) if accepted - upload file
sender := sender.NewSender(*PORT, *SHAREDFILE)
sender.WaitForConnection()
sender.MainLoop()
} else {
// 1) create receiver -> 2) try to connect to a sender -> 3) wait for an info on the file ->|
// 4) accept or refuse -> 5) download|don`t_download file
receiver := receiver.NewReceiver(*DOWNLOADSFOLDER)
receiver.Connect(fmt.Sprintf("%s:%d", *SENDERADDR, *PORT))
receiver.MainLoop()
}
}

17
protocol/constants.go

@ -1,17 +0,0 @@
// This file contains global constants of the protocol
package protocol
// MAXPACKETSIZE.
// How many bytes can contain one packet (header + body) at maximum
// (packets with size bigger than MAXPACKETSIZE are invalid and will not be sent)
const MAXPACKETSIZE uint = 51200 // 50 kilobytes
// PACKETSIZEDELIMETER.
// Character that delimits one and the other sides of the next incoming packet.
// ie: |packet_size_here|packet_here, where "|" is PACKETSIZEDELIMETER
const PACKETSIZEDELIMETER string = "|"
// HEADERDELIMETER.
// Character that delimits header of the packet from the body of the packet.
// ie: FILEINFO~img.png
const HEADERDELIMETER string = "~"

83
protocol/headers.go

@ -1,83 +0,0 @@
// This file describes various headers of the protocol and how to use them
package protocol
type Header string
// Headers
//// In the following below examples "|" is PACKETSIZEDELIMETER and "~" is HEADERDELIMETER
// ENCRKEY.
// The FIRST header to be sent. Sent immediately after the connection has been established
// by sender. Body contains randomly generated by sender aes encryption key.
// ie: |40|ENCRKEY~SUPER_SECURE_ENCRYPTION_KEY_YESS
const HeaderEncryptionKey Header = "ENCRKEY"
// FILENAME.
// This header is sent only by sender. The packet with this header
// must contain a name of the transported file in BODY.
// ie: |18|FILENAME~image.png
const HeaderFilename Header = "FILENAME"
// FILESIZE.
// This header is sent only by sender. The packet with this header
// must contain a size of the transported file in its BODY.
// ie: |15|FILESIZE~512442
const HeaderFileSize Header = "FILESIZE"
// CHECKSUM.
// Just like before, this header must be sent in a packet only by sender,
// BODY must contain a checksum of the transported file.
// ie: |74|CHECKSUM~1673f585148148d0c105af0d55646d6cbbf37e33a7366d3b72d8c5caca13434a
const HeaderChecksum Header = "CHECKSUM"
// DOYOACCEPT.
// Sent by sender after all the information about the transfered file has been sent.
// Receiving a packet with this header means that there will be no more additional information about the
// file and the sender is waiting for response (acceptance or rejection of the file).
// ie: |13|DOYOUACCEPT?~
const HeaderAcceptance Header = "DOYOUACCEPT?"
// FILEBYTES.
// Sent only by sender. The packet`s body must contain
// a portion of transported file`s bytes.
// ie: |70|FILEBYTES~fj2pgfjek;hjg02yg082qyuhg83hvuahjvlhsaoughuihgp9earhguhergh\n
const HeaderFileBytes Header = "FILEBYTES"
// FILEREJECT.
// Sent only by receiver if the user has decided to not download the file.
// The BODY may or may not be empty (preferably empty, of course), in any way, it will not be
// used in any way.
// ie: |11|FILEREJECT~
const HeaderReject Header = "FILEREJECT"
// FILEACCEPT.
// The opposite of the previous FILEREJECT. Send by receiver when
// the user has agreed to download the file.
// ie: |11|FILEACCEPT~
const HeaderAccept Header = "FILEACCEPT"
// DONE.
// Sent by sender. Warns the receiver that the file transfer has been done and
// there is no more information to give.
// ie: |5|DONE~
// Usually after the packet with this header has been sent, the receiver will send
// another packet back with header BYE!, telling that it`s going to disconnect
const HeaderDone Header = "DONE"
// READY.
// Sent by receiver when it hass read and processed the last
// FILEBYTES packet. The sender does not allowed to "spam" FILEBYTES
// packets without the permission of receiver.
// ie: |7|READY!~
const HeaderReady Header = "READY"
// BYE!.
// Packet with this header can be sent both by receiver and sender.
// It`s used when the sender or the receiver are going to disconnect
// and will not be able to communicate.
// (Usually it`s when the error has happened, OR, in a good situation, after the DONE header
// has been sent by sender, warning receiver that there is no data to send)
// The BODY is better to be empty.
// ie: |5|BYE!~
const HeaderDisconnecting Header = "BYE!"

162
protocol/packet.go

@ -1,162 +0,0 @@
// This file describes the general packet structure and provides methods to work with them before|after the transportation
// Examples of packets, ready for transportation in pseudo-code:
// []byte(|34|FILEDATA~fe2[gkr3j930f]fwpglkrt[o])
// []byte(|57|FILENAME~theBestFileNameEver_Existed_in'''theUniverse.txt)
// general structure:
// PACKETSIZEDELIMETER packetsize PACKETSIZEDELIMETER packet.Header HEADERDELIMETER packet.Body (without spaces between)
package protocol
import (
"bytes"
"fmt"
"net"
"strconv"
"github.com/Unbewohnte/FTU/encryption"
)
// Internal representation of packet before|after the transportation
type Packet struct {
Header Header
Body []byte
}
// Returns a size of the given packet as if it would be sent and presented in bytes.
// ie: FILESIZE~[49 49 56 55 56 53 50 49 54]
// DOES COUNT THE PACKETSIZEDELIMETER
func MeasurePacketSize(packet Packet) uint64 {
packetBytes := new(bytes.Buffer)
packetBytes.Write([]byte(packet.Header))
packetBytes.Write([]byte(HEADERDELIMETER))
packetBytes.Write(packet.Body)
return uint64(packetBytes.Len())
}
// Converts packet bytes into Packet struct
func BytesToPacket(packetbytes []byte) Packet {
var header Header
var body []byte
for counter, b := range packetbytes {
if string(b) == HEADERDELIMETER {
header = Header(packetbytes[0:counter])
body = packetbytes[counter+1:]
break
}
}
return Packet{
Header: header,
Body: body,
}
}
// Sends given packet to connection, following all the protocol`s rules.
// ALL packets MUST be sent by this method
func SendPacket(connection net.Conn, packetToSend Packet) error {
packetSize := MeasurePacketSize(packetToSend)
if packetSize > uint64(MAXPACKETSIZE) {
return fmt.Errorf("invalid packet!: EXCEEDED MAX PACKETSIZE")
}
// packetsize between delimeters (ie: |17|)
packetSizeBytes := []byte(strconv.Itoa(int(packetSize)))
// creating a buffer and writing the whole packet into it
packet := new(bytes.Buffer)
packet.Write([]byte(PACKETSIZEDELIMETER))
packet.Write(packetSizeBytes)
packet.Write([]byte(PACKETSIZEDELIMETER))
packet.Write([]byte(packetToSend.Header))
packet.Write([]byte(HEADERDELIMETER))
packet.Write(packetToSend.Body)
// write the result (ie: |17|FILENAME~file.png)
connection.Write(packet.Bytes())
// for debug purposes (ᗜˬᗜ)
// fmt.Printf("SENDING PACKET: %s%s%s%s%s%s\n",
// []byte(PACKETSIZEDELIMETER), packetSizeBytes, []byte(PACKETSIZEDELIMETER),
// []byte(packetToSend.Header), []byte(HEADERDELIMETER), packetToSend.Body)
return nil
}
// Sends given packet to connection, as the normal `SendPacket` method, but
// encodes given packet`s BODY with AES encryption
func SendEncryptedPacket(connection net.Conn, packetToSend Packet, key []byte) error {
// encrypting packet`s body
encryptedBody, err := encryption.Encrypt(key, packetToSend.Body)
if err != nil {
return fmt.Errorf("could not encrypt packet`s body: %s", err)
}
packetToSend.Body = encryptedBody
// sending the encrypted packet
err = SendPacket(connection, packetToSend)
if err != nil {
return fmt.Errorf("could not send packet: %s", err)
}
return nil
}
// Reads a packet from given connection, returns its bytes.
// ASSUMING THAT THE PACKETS ARE SENT BY `SendPacket` function !!!!
func ReadFromConn(connection net.Conn) ([]byte, error) {
var err error
var delimeterCounter int = 0
var packetSizeStrBuffer string = ""
var packetSize int = 0
for {
buffer := make([]byte, 1)
connection.Read(buffer)
if string(buffer) == PACKETSIZEDELIMETER {
delimeterCounter++
// the first delimeter has been found, skipping the rest of the loop
if delimeterCounter == 1 {
continue
}
}
// the last delimeter, the next read will be the packet itself, so breaking
if delimeterCounter == 2 {
break
}
packetSizeStrBuffer += string(buffer)
}
packetSize, err = strconv.Atoi(packetSizeStrBuffer)
if err != nil {
return nil, fmt.Errorf("could not convert packetsizeStr into int: %s", err)
}
// have a packetsize, now reading the whole packet
packetBuffer := new(bytes.Buffer)
// splitting big-sized packet into chunks and constructing it from pieces
left := packetSize
for {
if left == 0 {
break
}
buff := make([]byte, 1024)
if left < len(buff) {
buff = make([]byte, left)
}
read, _ := connection.Read(buff)
left -= read
packetBuffer.Write(buff[:read])
}
return packetBuffer.Bytes(), nil
}

30
receiver/file.go

@ -1,30 +0,0 @@
package receiver
import (
"fmt"
"os"
"github.com/Unbewohnte/FTU/checksum"
)
// Receiver`s file struct. Used internally by receiver
type File struct {
Filename string
Filesize uint64
CheckSum checksum.CheckSum
}
// Goes through all files in the downloads directory and compares their
// names with the name of the file that is about to be downloaded
func (r *Receiver) CheckIfFileAlreadyExists() (bool, error) {
contents, err := os.ReadDir(r.DownloadsFolder)
if err != nil {
return false, fmt.Errorf("could not get contents of the downloads` directory: %s", err)
}
for _, file := range contents {
if file.Name() == r.FileToDownload.Filename {
return true, nil
}
}
return false, nil
}

315
receiver/receiver.go

@ -1,315 +0,0 @@
package receiver
import (
"fmt"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/Unbewohnte/FTU/checksum"
"github.com/Unbewohnte/FTU/encryption"
"github.com/Unbewohnte/FTU/protocol"
)
// Representation of a receiver
type Receiver struct {
DownloadsFolder string
Connection net.Conn
IncomingPackets chan protocol.Packet
FileToDownload *File
EncryptionKey []byte
ReadyToReceive bool
Stopped bool
FileBytesPacketCounter uint64
}
// Creates a new client with default fields
func NewReceiver(downloadsFolder string) *Receiver {
os.MkdirAll(downloadsFolder, os.ModePerm)
downloadsFolderInfo, err := os.Stat(downloadsFolder)
if err != nil {
panic(err)
}
if !downloadsFolderInfo.IsDir() {
panic("Downloads folder is not a directory")
}
incomingPacketsChan := make(chan protocol.Packet, 5000)
var PacketCounter uint64 = 0
fmt.Println("Created a new receiver")
return &Receiver{
DownloadsFolder: downloadsFolder,
Connection: nil,
IncomingPackets: incomingPacketsChan,
Stopped: false,
ReadyToReceive: false,
FileToDownload: &File{
Filename: "",
Filesize: 0,
},
FileBytesPacketCounter: PacketCounter,
}
}
// Closes the connection
func (r *Receiver) Disconnect() {
r.Connection.Close()
}
// Closes the connection, warns the sender and exits the mainloop
func (r *Receiver) Stop() {
disconnectionPacket := protocol.Packet{
Header: protocol.HeaderDisconnecting,
}
protocol.SendEncryptedPacket(r.Connection, disconnectionPacket, r.EncryptionKey)
r.Stopped = true
r.Disconnect()
}
// Connects to a given address over tcp. Sets a connection to a corresponding field in receiver
func (r *Receiver) Connect(addr string) error {
fmt.Printf("Trying to connect to %s...\n", addr)
connection, err := net.Dial("tcp", addr)
if err != nil {
return fmt.Errorf("could not connect to %s: %s", addr, err)
}
r.Connection = connection
fmt.Println("Connected to ", r.Connection.RemoteAddr())
return nil
}
// Prints known information about the file that is about to be transported.
// Handles the input from the user after the sender sent "DOYOUACCEPT?" packet.
// The choice of acceptance is given to the user
func (r *Receiver) HandleFileOffer() error {
// inform the user about the file
fmt.Printf(`
Incoming fileinfo packet:
| Filename: %s
| Filesize: %.3fMB
| Checksum: %x
|
| Download ? [Y/N]: `,
r.FileToDownload.Filename, float32(r.FileToDownload.Filesize)/1024/1024, r.FileToDownload.CheckSum,
)
// get and process the input
var input string
fmt.Scanln(&input)
input = strings.TrimSpace(input)
input = strings.ToLower(input)
// reject the file
if input != "y" {
rejectionPacket := protocol.Packet{
Header: protocol.HeaderReject,
}
err := protocol.SendEncryptedPacket(r.Connection, rejectionPacket, r.EncryptionKey)
if err != nil {
return fmt.Errorf("could not send a rejection packet: %s", err)
}
return nil
}
// accept the file
// check if the file with the same name is present
doesExist, err := r.CheckIfFileAlreadyExists()
if err != nil {
return fmt.Errorf("could not check if the file with the same name alredy exists: %s", err)
}
if doesExist {
fmt.Printf(`
| Looks like that there is a file with the same name in your downloads directory, do you want to overwrite it ? [Y/N]: `)
fmt.Scanln(&input)
input = strings.TrimSpace(input)
input = strings.ToLower(input)
if input == "y" {
err = os.Remove(filepath.Join(r.DownloadsFolder, r.FileToDownload.Filename))
if err != nil {
return fmt.Errorf("could not remove the file: %s", err)
}
} else {
// user did not agree to overwrite, adding checksum to the name
r.FileToDownload.Filename = fmt.Sprint(time.Now().Unix()) + r.FileToDownload.Filename
}
}
acceptancePacket := protocol.Packet{
Header: protocol.HeaderAccept,
}
err = protocol.SendEncryptedPacket(r.Connection, acceptancePacket, r.EncryptionKey)
if err != nil {
return fmt.Errorf("could not send an acceptance packet: %s", err)
}
return nil
}
// Handles the download by writing incoming bytes into the file
func (r *Receiver) WritePieceOfFile(filePacket protocol.Packet) error {
if filePacket.Header != protocol.HeaderFileBytes {
return fmt.Errorf("packet with given header should not contain filebytes !: %v", filePacket)
}
// open|create a file with the same name as the filepacket`s file name
file, err := os.OpenFile(filepath.Join(r.DownloadsFolder, r.FileToDownload.Filename), os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModePerm)
if err != nil {
return err
}
// just write the bytes
file.Write(filePacket.Body)
file.Close()
r.FileBytesPacketCounter++
return nil
}
// Listens in an endless loop; reads incoming packets, decrypts their BODY and puts into channel
func (r *Receiver) ReceivePackets() {
for {
incomingPacketBytes, err := protocol.ReadFromConn(r.Connection)
if err != nil {
fmt.Printf("Error reading a packet: %s\nExiting...", err)
r.Stop()
os.Exit(-1)
}
incomingPacket := protocol.BytesToPacket(incomingPacketBytes)
// if this is the FIRST packet - it has HeaderEncryptionKey, so no need to decrypt
if incomingPacket.Header == protocol.HeaderEncryptionKey {
r.IncomingPackets <- incomingPacket
continue
}
decryptedBody, err := encryption.Decrypt(r.EncryptionKey, incomingPacket.Body)
if err != nil {
fmt.Printf("Error decrypring incoming packet`s BODY: %s\nExiting...", err)
r.Stop()
os.Exit(-1)
}
incomingPacket.Body = decryptedBody
r.IncomingPackets <- incomingPacket
}
}
// The "head" of the receiver. Similarly as in server`s logic "glues" everything together.
// Current structure allows the receiver to receive any type of packet
// in any order and react correspondingly
func (r *Receiver) MainLoop() {
go r.ReceivePackets()
// r.Stop()
for {
if r.Stopped {
break
}
if r.ReadyToReceive {
readyPacket := protocol.Packet{
Header: protocol.HeaderReady,
}
err := protocol.SendEncryptedPacket(r.Connection, readyPacket, r.EncryptionKey)
if err != nil {
fmt.Printf("Could not send the packet: %s\nExiting...", err)
r.Stop()
}
r.ReadyToReceive = false
}
// no incoming packets ? Skipping the packet handling part
if len(r.IncomingPackets) == 0 {
continue
}
incomingPacket := <-r.IncomingPackets
// handling each packet header differently
switch incomingPacket.Header {
case protocol.HeaderEncryptionKey:
r.EncryptionKey = incomingPacket.Body
fmt.Println("Got the encryption key: ", string(incomingPacket.Body))
case protocol.HeaderFilename:
r.FileToDownload.Filename = string(incomingPacket.Body)
case protocol.HeaderFileSize:
filesize, err := strconv.Atoi(string(incomingPacket.Body))
if err != nil {
fmt.Printf("could not convert a filesize: %s\n", err)
r.Stop()
}
r.FileToDownload.Filesize = uint64(filesize)
case protocol.HeaderChecksum:
checksum, err := checksum.BytesToChecksum(incomingPacket.Body)
if err != nil {
fmt.Printf("could not get file`s checksum: %s\n", err)
r.Stop()
}
r.FileToDownload.CheckSum = checksum
case protocol.HeaderDone:
if r.FileToDownload.Filename != "" && r.FileToDownload.Filesize != 0 && r.FileToDownload.CheckSum != [32]byte{} {
err := r.HandleFileOffer()
if err != nil {
fmt.Printf("Could not handle a file download confirmation: %s\nExiting...", err)
r.Stop()
}
r.ReadyToReceive = true
} else {
fmt.Println("Not enough data about the file was sent. Exiting...")
r.Stop()
}
case protocol.HeaderFileBytes:
err := r.WritePieceOfFile(incomingPacket)
if err != nil {
fmt.Printf("Could not write a piece of file: %s\nExiting...", err)
r.Stop()
}
r.ReadyToReceive = true
case protocol.HeaderDisconnecting:
// the sender has completed its mission,
// checking hashes and exiting
fmt.Println("Got ", r.FileBytesPacketCounter, " file packets in total")
fmt.Println("Checking checksums...")
file, err := os.Open(filepath.Join(r.DownloadsFolder, r.FileToDownload.Filename))
if err != nil {
fmt.Printf("error while opening downloaded file for checking: %s\n", err)
os.Exit(-1)
}
realCheckSum, err := checksum.GetPartialCheckSum(file)
if err != nil {
fmt.Printf("error perfoming partial checksum: %s\n", err)
os.Exit(-1)
}
fmt.Printf("\n%x ----- %x\n", r.FileToDownload.CheckSum, realCheckSum)
if !checksum.AreEqual(realCheckSum, r.FileToDownload.CheckSum) {
fmt.Println("Downloaded file is corrupted !")
}
r.Stop()
}
}
}

45
sender/file.go

@ -1,45 +0,0 @@
package sender
import (
"fmt"
"os"
"github.com/Unbewohnte/FTU/checksum"
)
// Struct that represents the served file. Used internally in the sender
type File struct {
path string
Filename string
Filesize uint64
SentBytes uint64
LeftBytes uint64
Handler *os.File
CheckSum checksum.CheckSum
}
// Prepares a file for serving. Used for preparing info before sending a fileinfo packet by sender
func getFile(path string) (*File, error) {
info, err := os.Stat(path)
if err != nil {
return nil, fmt.Errorf("could not get a fileinfo: %s", err)
}
handler, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("wasn`t able to open the file: %s", err)
}
checksum, err := checksum.GetPartialCheckSum(handler)
if err != nil {
return nil, fmt.Errorf("could not get a partial file checksum: %s", err)
}
return &File{
path: path,
Filename: info.Name(),
Filesize: uint64(info.Size()),
SentBytes: 0,
LeftBytes: uint64(info.Size()),
Handler: handler,
CheckSum: checksum,
}, nil
}

35
sender/ip.go

@ -1,35 +0,0 @@
package sender
import (
"fmt"
"io"
"net"
"net/http"
)
// gets a local ip. Borrowed from StackOverflow, thank you, whoever I brought it from
func GetLocalIP() (string, error) {
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
return "", err
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP.String(), nil
}
// gets a remote ip. Borrowed from StackOverflow, thank you, whoever I brought it from
func GetRemoteIP() (string, error) {
resp, err := http.Get("https://api.ipify.org?format=text")
if err != nil {
return "", fmt.Errorf("could not make a request to get your remote IP: %s", err)
}
defer resp.Body.Close()
ip, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("could not read a response: %s", err)
}
return string(ip), nil
}

297
sender/sender.go

@ -1,297 +0,0 @@
package sender
import (
"fmt"
"net"
"os"
"strconv"
"github.com/Unbewohnte/FTU/checksum"
"github.com/Unbewohnte/FTU/encryption"
"github.com/Unbewohnte/FTU/protocol"
)
// The main sender struct
type Sender struct {
Port int
FileToTransfer *File
Listener net.Listener
Connection net.Conn
IncomingPackets chan protocol.Packet
EncryptionKey []byte
SentFileBytesPackets uint64
TransferAllowed bool
ReceiverIsReady bool
Stopped bool
}
// Creates a new sender with default|necessary fields
func NewSender(port int, filepath string) *Sender {
fileToTransfer, err := getFile(filepath)
if err != nil {
panic(err)
}
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
panic(err)
}
incomingPacketsChan := make(chan protocol.Packet, 5000)
remoteIP, err := GetRemoteIP()
if err != nil {
panic(err)
}
localIP, err := GetLocalIP()
if err != nil {
panic(err)
}
// !!!
key := encryption.Generate32AESkey()
fmt.Printf("GENERATED ENCRYPTION KEY: %s\n", key)
var filepacketCounter uint64
fmt.Printf("Created a new sender at %s:%d (remote)\n%s:%d (local)\n", remoteIP, port, localIP, port)
return &Sender{
Port: port,
FileToTransfer: fileToTransfer,
Listener: listener,
Connection: nil,
IncomingPackets: incomingPacketsChan,
SentFileBytesPackets: filepacketCounter,
EncryptionKey: key,
TransferAllowed: false,
ReceiverIsReady: false,
Stopped: false,
}
}
// Closes the connection, warns about it the receiver and exits the mainloop
func (s *Sender) Stop() {
disconnectionPacket := protocol.Packet{
Header: protocol.HeaderDisconnecting,
}
err := protocol.SendEncryptedPacket(s.Connection, disconnectionPacket, s.EncryptionKey)
if err != nil {
panic(fmt.Sprintf("could not send a disconnection packet: %s", err))
}
s.Stopped = true
s.Disconnect()
}
// Closes current connection
func (s *Sender) Disconnect() {
s.Connection.Close()
}
// Accepts one connection
func (s *Sender) WaitForConnection() {
connection, err := s.Listener.Accept()
if err != nil {
fmt.Printf("Could not accept a connection: %s", err)
os.Exit(-1)
}
s.Connection = connection
fmt.Println("New connection from ", s.Connection.RemoteAddr())
}
// Closes the listener. Used only when there is still no connection from `AcceptConnections`
func (s *Sender) StopListening() {
s.Listener.Close()
}
// Sends generated earlier eas encryption key to receiver
func (s *Sender) SendEncryptionKey() error {
keyPacket := protocol.Packet{
Header: protocol.HeaderEncryptionKey,
Body: s.EncryptionKey,
}
err := protocol.SendPacket(s.Connection, keyPacket)
if err != nil {
return fmt.Errorf("could not send a packet: %s", err)
}
return nil
}
// Sends multiple packets with all information about the file to receiver
// (filename, filesize, checksum)
func (s *Sender) SendOffer() error {
// filename
filenamePacket := protocol.Packet{
Header: protocol.HeaderFilename,
Body: []byte(s.FileToTransfer.Filename),
}
err := protocol.SendEncryptedPacket(s.Connection, filenamePacket, s.EncryptionKey)
if err != nil {
return fmt.Errorf("could not send an information about the file: %s", err)
}
// filesize
filesizePacket := protocol.Packet{
Header: protocol.HeaderFileSize,
Body: []byte(strconv.Itoa(int(s.FileToTransfer.Filesize))),
}
err = protocol.SendEncryptedPacket(s.Connection, filesizePacket, s.EncryptionKey)
if err != nil {
return fmt.Errorf("could not send an information about the file: %s", err)
}
// checksum
checksumPacket := protocol.Packet{
Header: protocol.HeaderChecksum,
Body: checksum.ChecksumToBytes(s.FileToTransfer.CheckSum),
}
err = protocol.SendEncryptedPacket(s.Connection, checksumPacket, s.EncryptionKey)
if err != nil {
return fmt.Errorf("could not send an information about the file: %s", err)
}
// indicate that we`ve sent everything we needed to send
donePacket := protocol.Packet{
Header: protocol.HeaderDone,
}
err = protocol.SendEncryptedPacket(s.Connection, donePacket, s.EncryptionKey)
if err != nil {
return fmt.Errorf("could not send an information about the file: %s", err)
}
return nil
}
// Sends one packet that contains a piece of file to the receiver
func (s *Sender) SendPiece() error {
// if no data to send - exit
if s.FileToTransfer.LeftBytes == 0 {
fmt.Printf("Done. Sent %d file packets\n", s.SentFileBytesPackets)
s.Stop()
}
// empty body
fileBytesPacket := protocol.Packet{
Header: protocol.HeaderFileBytes,
}
// how many bytes we can send at maximum (including some little space for padding)
maxFileBytes := protocol.MAXPACKETSIZE - (uint(protocol.MeasurePacketSize(fileBytesPacket)) + 90)
fileBytes := make([]byte, maxFileBytes)
// if there is less data to send than the limit - create a buffer of needed size
if s.FileToTransfer.LeftBytes < uint64(maxFileBytes) {
fileBytes = make([]byte, uint64(maxFileBytes)-(uint64(maxFileBytes)-s.FileToTransfer.LeftBytes))
}
// reading bytes from the point where we left
read, err := s.FileToTransfer.Handler.ReadAt(fileBytes, int64(s.FileToTransfer.SentBytes))
if err != nil {
return fmt.Errorf("could not read from a file: %s", err)
}
// filling BODY with bytes
fileBytesPacket.Body = fileBytes
err = protocol.SendEncryptedPacket(s.Connection, fileBytesPacket, s.EncryptionKey)
if err != nil {
return fmt.Errorf("could not send a file packet : %s", err)
}
// doing a "logging" for the next time
s.FileToTransfer.LeftBytes -= uint64(read)
s.FileToTransfer.SentBytes += uint64(read)
s.SentFileBytesPackets++
return nil
}
// Listens in an endless loop; reads incoming packets, decrypts their BODY and puts into channel
func (s *Sender) ReceivePackets() {
for {
incomingPacketBytes, err := protocol.ReadFromConn(s.Connection)
if err != nil {
fmt.Printf("Error reading a packet: %s\nExiting...", err)
s.Stop()
os.Exit(-1)
}
incomingPacket := protocol.BytesToPacket(incomingPacketBytes)
decryptedBody, err := encryption.Decrypt(s.EncryptionKey, incomingPacket.Body)
if err != nil {
fmt.Printf("Error decrypting an incoming packet: %s\nExiting...", err)
s.Stop()
os.Exit(-1)
}
incomingPacket.Body = decryptedBody
s.IncomingPackets <- incomingPacket
}
}
// The "head" of the sender. "Glues" all things together.
// Current structure allows the sender to receive any type of packet
// in any order and react correspondingly
func (s *Sender) MainLoop() {
go s.ReceivePackets()
// instantly sending an encryption key, following the protocol`s rule
err := s.SendEncryptionKey()
if err != nil {
fmt.Printf("Could not send an encryption key: %s\nExiting...", err)
s.Stop()
}
// send an information about the shared file to the receiver
err = s.SendOffer()
if err != nil {
fmt.Printf("Could not send an info about the file: %s\nExiting...", err)
s.Stop()
}
for {
if s.Stopped {
break
}
if s.TransferAllowed && s.ReceiverIsReady {
err := s.SendPiece()
if err != nil {
fmt.Printf("could not send a piece of file: %s", err)
s.Stop()
}
s.ReceiverIsReady = false
}
// no incoming packets ? Skipping the packet handling part
if len(s.IncomingPackets) == 0 {
continue
}
incomingPacket := <-s.IncomingPackets
// handling each packet header differently
switch incomingPacket.Header {
case protocol.HeaderAccept:
// allowed to send file packets
fmt.Println("The transfer has been accepted !")
s.TransferAllowed = true
case protocol.HeaderReject:
fmt.Println("The transfer has been rejected")
s.Stop()
case protocol.HeaderReady:
s.ReceiverIsReady = true
case protocol.HeaderDisconnecting:
// receiver is dropping the file transfer ?
fmt.Println("Receiver has disconnected")
s.Stop()
}
}
}

219
src/COPYING

@ -0,0 +1,219 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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 <https://www.gnu.org/licenses/why-not-lgpl.html>.

38
src/addr/local.go

@ -0,0 +1,38 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
package addr
import (
"net"
)
// Get local IP address
func GetLocal() (string, error) {
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
return "", err
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP.String(), nil
}

101
src/checksum/checksum.go

@ -0,0 +1,101 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
package checksum
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"io"
"os"
)
// returns a checksum of given file. NOTE, that it creates checksum
// not of a full file (from all file bytes), but from separate byte blocks.
// This is done as an optimisation because the file can be very large in size.
// The general idea:
// BOF... CHUNK -> STEP -> CHUNK... EOF
// checksum := sha256.Sum256(ALLCHUNKS)
// GetPartialCheckSum is default method used to get a file checksum by sender and receiver
func GetPartialCheckSum(file *os.File) (string, error) {
// "capturing" CHUNKSIZE bytes and then skipping STEP bytes before the next chunk until the last one
const CHUNKS uint = 50
const CHUNKSIZE uint = 50
const STEP uint = 250
fileStats, err := file.Stat()
if err != nil {
return "", err
}
fileSize := fileStats.Size()
if fileSize < int64(CHUNKS*CHUNKSIZE+STEP*(CHUNKS-1)) {
// file is too small to chop it in chunks, so just get the full checksum
checksum, err := getFullCheckSum(file)
if err != nil {
return "", err
}
return checksum, nil
}
_, err = file.Seek(0, io.SeekStart)
if err != nil {
return "", err
}
// var capturedChunks string
var capturedChunks bytes.Buffer
var read uint64 = 0
for i := 0; uint(i) < CHUNKS; i++ {
buffer := make([]byte, CHUNKSIZE)
r, _ := file.ReadAt(buffer, int64(read))
capturedChunks.Write(buffer)
read += uint64(r)
read += uint64(STEP)
}
checksumBytes := sha256.Sum256(capturedChunks.Bytes())
checksum := hex.EncodeToString(checksumBytes[:])
return checksum, nil
}
// Returns a sha256 checksum of given file
func getFullCheckSum(file *os.File) (string, error) {
_, err := file.Seek(0, io.SeekStart)
if err != nil {
return "", err
}
filebytes, err := io.ReadAll(file)
if err != nil {
return "", err
}
checksumBytes := sha256.Sum256(filebytes)
checksum := hex.EncodeToString(checksumBytes[:])
return checksum, nil
}

45
src/checksum/checksum_test.go

@ -0,0 +1,45 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
package checksum
import (
"os"
"strings"
"testing"
)
func Test_GetPartialCheckSum(t *testing.T) {
tesfilePath := "../testfiles/testfile.txt"
file, err := os.Open(tesfilePath)
if err != nil {
t.Fatalf("%s", err)
}
checksum, err := GetPartialCheckSum(file)
if err != nil {
t.Fatalf("GetPartialCheckSum error: %s", err)
}
if !strings.EqualFold("fa6d92493ac0c73c9fa85d10c92b41569017454c5b4387d315f3d2c4ad1d6766", checksum) {
t.Fatalf("GetPartialCheckSum error: hashes of a testfile.txt do not match")
}
}

51
src/encryption/decrypt.go

@ -0,0 +1,51 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
package encryption
import (
"crypto/aes"
"crypto/cipher"
"fmt"
)
// Thanks to https://www.melvinvivas.com/how-to-encrypt-and-decrypt-data-using-aes/
// Decrypts encrypted aes data with given key.
func Decrypt(key, dataToDecrypt []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("could not create new AES cipher: %s", err)
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("could not create new GCM: %s", err)
}
nonce, encryptedBytes := dataToDecrypt[:aesGCM.NonceSize()], dataToDecrypt[aesGCM.NonceSize():]
decryptedData, err := aesGCM.Open(nil, nonce, encryptedBytes, nil)
if err != nil {
return nil, fmt.Errorf("could not decrypt given data: %s", err)
}
return decryptedData, nil
}

45
src/encryption/encrypt.go

@ -0,0 +1,45 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
package encryption
import (
"crypto/aes"
"crypto/cipher"
"fmt"
)
// Thanks to https://www.melvinvivas.com/how-to-encrypt-and-decrypt-data-using-aes/
// Encrypts given data using aes encryption.
func Encrypt(key, dataToEncrypt []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("could not create new AES cipher: %s", err)
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("could not create new GCM: %s", err)
}
nonce := make([]byte, aesGCM.NonceSize())
encryptedData := aesGCM.Seal(nonce, nonce, dataToEncrypt, nil)
return encryptedData, nil
}

31
src/encryption/encryption_test.go

@ -0,0 +1,31 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
package encryption
import "testing"
func TestGenerate32AESkey(t *testing.T) {
generatedKey := Generate32AESkey()
if len(generatedKey) != int(KEYLEN) {
t.Errorf("Generate32AESkey failed: generated key`s length does not equal KEYLEN const (32)")
}
}

47
src/encryption/key.go

@ -0,0 +1,47 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
package encryption
import (
"math/rand"
"time"
)
// using aes256, so 32 bytes-long key
const KEYLEN uint = 32
const CHARS string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
// Generates 32 pseudo-random bytes to use as a key
func Generate32AESkey() []byte {
var generatedKey []byte
rand.Seed(time.Now().UTC().UnixNano())
// choosing "random" 32 bytes from CHARS
for {
if len(generatedKey) == int(KEYLEN) {
break
}
randomIndex := rand.Intn(len(CHARS))
generatedKey = append(generatedKey, CHARS[randomIndex])
}
return generatedKey
}

211
src/fsys/dir.go

@ -0,0 +1,211 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
package fsys
import (
"fmt"
"io/fs"
"os"
"path/filepath"
)
// A struct that represents the main information about a directory
type Directory struct {
Name string
Path string
Size uint64
RelativeParentPath string // Relative path to the directory, where the highest point in the hierarchy is the upmost parent dir. Set manually
Symlinks []*Symlink
Files []*File
Directories []*Directory
}
var ErrorNotDirectory error = fmt.Errorf("not a directory")
func GetDir(path string, recursive bool) (*Directory, error) {
absPath, err := filepath.Abs(path)
if err != nil {
return nil, err
}
stats, err := os.Stat(absPath)
if err != nil {
return nil, err
}
// check if it is a directory for real
if !stats.IsDir() {
return nil, ErrorNotDirectory
}
directory := Directory{
Name: stats.Name(),
Path: absPath,
Directories: nil,
Files: nil,
}
// loop through each entry in the directory
entries, err := os.ReadDir(absPath)
if err != nil && err != fs.ErrPermission {
return nil, err
}
var innerDirs []*Directory
var innerFiles []*File
var innerSymlinks []*Symlink
for _, entry := range entries {
entryInfo, err := entry.Info()
if err != nil {
return nil, err
}
if entryInfo.IsDir() {
if recursive {
// do the recursive magic
innerDirPath := filepath.Join(absPath, entry.Name())
innerDir, err := GetDir(innerDirPath, true)
if err != nil {
return nil, err
}
directory.Size += innerDir.Size
innerDirs = append(innerDirs, innerDir)
}
// if not - skip the directory and only work with the files
} else {
// not a directory
switch entryInfo.Mode()&os.ModeSymlink != 0 {
case true:
// it is a symlink
innerSymlinkPath := filepath.Join(absPath, entryInfo.Name())
symlink, err := GetSymlink(innerSymlinkPath, false)
if err != nil {
// skip this symlink
continue
}
innerSymlinks = append(innerSymlinks, symlink)
case false:
// it is a usual file
innerFilePath := filepath.Join(absPath, entryInfo.Name())
innerFile, err := GetFile(innerFilePath)
if err != nil {
// skip this file
continue
}
directory.Size += innerFile.Size
innerFiles = append(innerFiles, innerFile)
}
}
}
directory.Directories = innerDirs
directory.Files = innerFiles
directory.Symlinks = innerSymlinks
return &directory, nil
}
// Returns every file in that directory
func (dir *Directory) GetAllFiles(recursive bool) []*File {
var files []*File = dir.Files
if recursive {
if len(dir.Directories) == 0 {
return files
}
for _, innerDir := range dir.Directories {
innerFiles := innerDir.GetAllFiles(recursive)
files = append(files, innerFiles...)
}
} else {
files = dir.Files
}
return files
}
// Returns every symlink in that directory
func (dir *Directory) GetAllSymlinks(recursive bool) []*Symlink {
var symlinks []*Symlink = dir.Symlinks
if recursive {
if len(dir.Directories) == 0 {
return symlinks
}
for _, innerDir := range dir.Directories {
innerSymlinks := innerDir.GetAllSymlinks(recursive)
symlinks = append(symlinks, innerSymlinks...)
}
} else {
symlinks = dir.Symlinks
}
return symlinks
}
// Sets `RelativeParentPath` relative to the given base path for files and `Path`, `TargetPath` for symlinks so the
// file with such path:
// /home/user/directory/somefile.txt
// had a relative path like that:
// /directory/somefile.txt
// (where base path is /home/user/directory)
func (dir *Directory) SetRelativePaths(base string, recursive bool) error {
for _, file := range dir.GetAllFiles(recursive) {
relPath, err := filepath.Rel(base, file.Path)
if err != nil {
return err
}
file.RelativeParentPath = relPath
}
for _, symlink := range dir.GetAllSymlinks(recursive) {
symRelPath, err := filepath.Rel(base, symlink.Path)
if err != nil {
return err
}
symlink.Path = symRelPath
symRelTargetPath, err := filepath.Rel(base, symlink.TargetPath)
if err != nil {
return err
}
symlink.TargetPath = symRelTargetPath
}
return nil
}

103
src/fsys/dir_test.go

@ -0,0 +1,103 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
package fsys
import (
"os"
"path/filepath"
"testing"
)
func Test_GetDir(t *testing.T) {
dirpath := "../testfiles/"
_, err := GetDir(dirpath, false)
if err != nil {
t.Fatalf("%s", err)
}
}
func Test_GetDirRecursive(t *testing.T) {
dirpath := "../testfiles/"
dir, err := GetDir(dirpath, true)
if err != nil {
t.Fatalf("%s", err)
}
expectedAmountOfUpperDirectories := 3
if len(dir.Directories) != expectedAmountOfUpperDirectories {
t.Fatalf("expected to have %d inner directories; got %d", expectedAmountOfUpperDirectories, len(dir.Directories))
}
for _, innerDir := range dir.Directories {
if innerDir.Size > dir.Size {
t.Fatalf("inner dir cannot have a bigger size (%d B) than its parent`s total size (%d B)", innerDir.Size, dir.Size)
}
}
}
func Test_GetFiles(t *testing.T) {
dirpath := "../testfiles/"
dir, err := GetDir(dirpath, true)
if err != nil {
t.Fatalf("%s", err)
}
// recursive
files := dir.GetAllFiles(true)
fileCount := 6
if len(files) != fileCount {
t.Fatalf("expected to get %d files; got %d\n", fileCount, len(files))
}
// not recursive
files = dir.GetAllFiles(false)
fileCount = 1
if len(files) != fileCount {
t.Fatalf("expected to get %d files; got %d\n", fileCount, len(files))
}
}
func Test_GetSymlinks(t *testing.T) {
dirpath := "../testfiles/"
os.Symlink(filepath.Join(dirpath, "testfile.txt"), filepath.Join(dirpath, "testsymlink.txt"))
os.Symlink(filepath.Join(dirpath, "testdir", "testfile2.txt"), filepath.Join(dirpath, "testdir", "testsymlink2.txt"))
dir, err := GetDir(dirpath, true)
if err != nil {
t.Fatalf("%s", err)
}
// recursive
symlinks := dir.GetAllSymlinks(true)
symlinkCount := 2
if len(symlinks) != symlinkCount {
t.Fatalf("expected to get %d symlinks; got %d\n", symlinkCount, len(symlinks))
}
}

115
src/fsys/file.go

@ -0,0 +1,115 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
package fsys
import (
"fmt"
"os"
"path/filepath"
"unbewohnte/ftu/checksum"
)
// A struct that represents the necessary file information for transportation through node
type File struct {
ID uint64 // Set manually
Name string
Path string
RelativeParentPath string // Relative path to the file, where the highest directory in the hierarchy is the upmost parent dir. Set manually
Size uint64
Checksum string
Handler *os.File // Set when .Open() is called
SentBytes uint64 // Set manually during transportation
}
var ErrorNotFile error = fmt.Errorf("not a file")
// Get general information about a file with the
// future ability to open it.
// NOTE that Handler field is nil BY DEFAULT until you
// manually call (file *File).Open() to open it !
func GetFile(path string) (*File, error) {
absPath, err := filepath.Abs(path)
if err != nil {
return nil, err
}
stats, err := os.Stat(absPath)
if err != nil {
return nil, err
}
// check if it is a directory
if stats.IsDir() {
return nil, ErrorNotFile
}
file := File{
Name: stats.Name(),
Path: absPath,
Size: uint64(stats.Size()),
Handler: nil,
}
// get checksum
err = file.Open()
if err != nil {
return nil, err
}
defer file.Close()
checksum, err := checksum.GetPartialCheckSum(file.Handler)
if err != nil {
return nil, err
}
file.Checksum = checksum
return &file, nil
}
// Opens file for read/write operations
func (file *File) Open() error {
if file.Handler != nil {
file.Close()
}
handler, err := os.OpenFile(file.Path, os.O_CREATE|os.O_RDWR, os.ModePerm)
if err != nil {
return err
}
file.Handler = handler
return nil
}
// file.Handler.Close wrapper
func (file *File) Close() error {
if file.Handler != nil {
err := file.Handler.Close()
if err != nil {
return err
}
file.Handler = nil
}
return nil
}

59
src/fsys/file_test.go

@ -0,0 +1,59 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
package fsys
import (
"io"
"testing"
)
func Test_GetFile(t *testing.T) {
filepath := "../testfiles/testfile.txt"
file, err := GetFile(filepath)
if err != nil {
t.Fatalf("GetFile error: %s", err)
}
expectedFilename := "testfile.txt"
if file.Name != expectedFilename {
t.Fatalf("GetFile error: filenames do not match: expected filename to be %s; got %s", expectedFilename, file.Name)
}
}
func Test_GetFileOpen(t *testing.T) {
filepath := "../testfiles/testfile.txt"
file, err := GetFile(filepath)
if err != nil {
t.Fatalf("GetFile error: %s", err)
}
err = file.Open()
if err != nil {
t.Fatalf("GetFile error: could not open file: %s", err)
}
_, err = io.ReadAll(file.Handler)
if err != nil {
t.Fatalf("GetFile error: could not read from file: %s", err)
}
}

70
src/fsys/symlink.go

@ -0,0 +1,70 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
package fsys
import (
"fmt"
"os"
)
type Symlink struct {
TargetPath string
Path string
}
// Checks whether path is referring to a symlink or not
func IsSymlink(path string) (bool, error) {
stats, err := os.Lstat(path)
if err != nil {
return false, err
}
isSymlink := stats.Mode()&os.ModeSymlink != 0
return isSymlink, nil
}
var ErrorNotSymlink error = fmt.Errorf("not a symlink")
// get necessary information about a symlink in a filesystem. If check is false -
// does not check if path REALLY refers to a symlink
func GetSymlink(path string, check bool) (*Symlink, error) {
if check {
isSymlink, err := IsSymlink(path)
if err != nil {
return nil, err
}
if !isSymlink {
return nil, ErrorNotSymlink
}
}
target, err := os.Readlink(path)
if err != nil {
return nil, err
}
symlink := Symlink{
TargetPath: target,
Path: path,
}
return &symlink, nil
}

42
src/fsys/symlink_test.go

@ -0,0 +1,42 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
package fsys
import (
"os"
"path/filepath"
"testing"
)
func Test_IsSymlink(t *testing.T) {
dirpath := "../testfiles/"
symlinkPath := filepath.Join(dirpath, "testsymlink.txt")
os.Symlink(filepath.Join(dirpath, "testfile.txt"), symlinkPath)
isSymlink, err := IsSymlink(symlinkPath)
if err != nil {
t.Fatalf("%s\n", err)
}
if !isSymlink {
t.Fatalf("%s expected to be a symlink\n", symlinkPath)
}
}

3
src/go.mod

@ -0,0 +1,3 @@
module unbewohnte/ftu
go 1.18

142
src/main.go

@ -0,0 +1,142 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte (https://unbewohnte.xyz/))
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
package main
import (
_ "embed"
"flag"
"fmt"
"os"
"unbewohnte/ftu/node"
)
var (
VERSION string = "v2.3.3"
versionInformation string = fmt.Sprintf("ftu %s\nfile transferring utility\n\nCopyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)\nThis program comes with ABSOLUTELY NO WARRANTY.\nThis is free software, and you are welcome to redistribute it under certain conditions; type \"ftu -l\" for details.\n", VERSION)
//go:embed COPYING
licenseInformation string
// flags
PORT *uint = flag.Uint("p", 7270, "Specifies a port to work with")
RECUSRIVE *bool = flag.Bool("r", false, "Recursively send a directory")
ADDRESS *string = flag.String("a", "", "Specifies an address to connect to")
DOWNLOADS_DIR *string = flag.String("d", ".", "Downloads folder")
SEND *string = flag.String("s", "", "Specify a file|directory to send")
VERBOSE *bool = flag.Bool("?", false, "Turn on/off verbose output")
PRINT_VERSION *bool = flag.Bool("v", false, "Print version information")
PRINT_LICENSE *bool = flag.Bool("l", false, "Print license information")
isSending bool
)
func init() {
flag.Usage = func() {
fmt.Printf("ftu -[FLAGs]\n\n")
fmt.Printf("[FLAGs]\n\n")
fmt.Printf("| -p [integer] for port\n")
fmt.Printf("| -r [true|false] send recursively or not\n")
fmt.Printf("| -a [ip_address|domain_name] address to connect to (cannot be used with -s)\n")
fmt.Printf("| -d [path_to_directory] where the files will be downloaded to (cannot be used with -s)\n")
fmt.Printf("| -s [path_to_file|directory] send it (cannot be used with -a)\n")
fmt.Printf("| -? [true|false] turn on|off verbose output\n")
fmt.Printf("| -l print license information\n")
fmt.Printf("| -v print version information\n\n\n")
fmt.Printf("[Examples]\n\n")
fmt.Printf("| ftu -p 89898 -s /home/user/Downloads/someVideo.mp4\n")
fmt.Printf("| creates a node on a non-default port 89898 that will send \"someVideo.mp4\" to the other node that connects to you\n\n")
fmt.Printf("| ftu -p 7277 -a 192.168.1.104 -d .\n")
fmt.Printf("| creates a node that will connect to 192.168.1.104:7277 and download served file|directory to the working directory\n\n")
fmt.Printf("| ftu -p 7277 -a 87.117.55.229 -d .\n")
fmt.Printf("| creates a node that will connect to 87.117.55.229:7277 and download served file|directory to the working directory\n\n")
fmt.Printf("| ftu -p 7277 -a 192.168.1.104 -d /home/user/Downloads/\n")
fmt.Printf("| creates a node that will connect to 192.168.1.104:7277 and download served file|directory to \"/home/user/Downloads/\"\n\n")
fmt.Printf("| ftu -s /home/user/homework\n")
fmt.Printf("| creates a node that will send every file in the directory\n\n")
fmt.Printf("| ftu -r -s /home/user/homework/\n")
fmt.Printf("| creates a node that will send every file in the directory !RECUSRIVELY!\n\n\n")
}
flag.Parse()
if *PRINT_VERSION {
fmt.Println(versionInformation)
os.Exit(0)
}
if *PRINT_LICENSE {
fmt.Println(licenseInformation)
os.Exit(0)
}
// validate flags
if *SEND == "" && *ADDRESS == "" {
fmt.Printf("[ERROR] Neither sending nor receiving flag was specified. Run ftu -h for help\n")
os.Exit(-1)
}
if *SEND != "" && *ADDRESS != "" {
fmt.Printf("[ERROR] Can't send and receive at the same time. Specify either -s or -a\n")
os.Exit(-1)
}
// sending or receiving
if *SEND != "" {
// sending
isSending = true
} else if *ADDRESS != "" {
// receiving
isSending = false
}
}
func main() {
nodeOptions := node.NodeOptions{
VerboseOutput: *VERBOSE,
IsSending: isSending,
WorkingPort: *PORT,
SenderSide: &node.SenderNodeOptions{
ServingPath: *SEND,
Recursive: *RECUSRIVE,
},
ReceiverSide: &node.ReceiverNodeOptions{
ConnectionAddr: *ADDRESS,
DownloadsFolderPath: *DOWNLOADS_DIR,
},
}
node, err := node.NewNode(&nodeOptions)
if err != nil {
fmt.Printf("[ERROR] Error constructing a new node: %s\n", err)
os.Exit(-1)
}
node.Start()
}

927
src/node/node.go

@ -0,0 +1,927 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
package node
import (
"bytes"
"encoding/binary"
"net"
"os"
"path/filepath"
"strings"
"sync"
"time"
"fmt"
"unbewohnte/ftu/addr"
"unbewohnte/ftu/checksum"
"unbewohnte/ftu/encryption"
"unbewohnte/ftu/fsys"
"unbewohnte/ftu/protocol"
)
// netInfowork specific settings
type netInfo struct {
ConnAddr string // address to connect to. Does not include port
Conn net.Conn // the core TCP connection of the node. Self-explanatory
Port uint // a port to connect to/listen on
EncryptionKey []byte // if != nil - incoming packets will be decrypted with it and outcoming packets will be encrypted
}
// Sending-side node information
type sending struct {
ServingPath string // path to the thing that will be sent
IsDirectory bool // is ServingPath a directory
Recursive bool // recursively send directory
CanSendBytes bool // is the other node ready to receive another piece
AllowedToTransfer bool // the way to notify the mainloop of a sending node to start sending pieces of files
InTransfer bool // already transferring|receiving files
FilesToSend []*fsys.File
SymlinksToSend []*fsys.Symlink
CurrentFileID uint64 // an id of a file that is currently being transported
SentBytes uint64 // how many bytes sent already
TotalTransferSize uint64 // how many bytes will be sent in total
CurrentSymlinkIndex uint64 // current index of a symlink that is
}
// Receiving-side node information
type receiving struct {
AcceptedFiles []*fsys.File // files that`ve been accepted to be received
DownloadsPath string // where to download
TotalDownloadSize uint64 // how many bytes will be received in total
ReceivedBytes uint64 // how many bytes downloaded so far
}
// Both sending-side and receiving-side information
type transferInfo struct {
Receiving *receiving
Sending *sending
}
// Sender and receiver in one type !
type Node struct {
verboseOutput bool
mutex *sync.Mutex
packetPipe chan *protocol.Packet // a way to receive incoming packets from another goroutine
isSending bool // sending or a receiving node
stopped bool // the way to exit the mainloop in case of an external error or a successful end of a transfer
netInfo *netInfo
transferInfo *transferInfo
}
// Creates a new either a sending or receiving node with specified options
func NewNode(options *NodeOptions) (*Node, error) {
var isDir bool
if options.IsSending {
// sending node preparation
sendingPathStats, err := os.Stat(options.SenderSide.ServingPath)
if err != nil {
return nil, err
}
switch sendingPathStats.IsDir() {
case true:
isDir = true
case false:
isDir = false
}
} else {
// receiving node preparation
var err error
options.ReceiverSide.DownloadsFolderPath, err = filepath.Abs(options.ReceiverSide.DownloadsFolderPath)
if err != nil {
return nil, err
}
err = os.MkdirAll(options.ReceiverSide.DownloadsFolderPath, os.ModePerm)
if err != nil {
return nil, err
}
}
node := Node{
verboseOutput: options.VerboseOutput,
mutex: &sync.Mutex{},
packetPipe: make(chan *protocol.Packet, 100),
isSending: options.IsSending,
netInfo: &netInfo{
Port: options.WorkingPort,
ConnAddr: options.ReceiverSide.ConnectionAddr,
EncryptionKey: nil,
Conn: nil,
},
stopped: false,
transferInfo: &transferInfo{
Sending: &sending{
ServingPath: options.SenderSide.ServingPath,
Recursive: options.SenderSide.Recursive,
IsDirectory: isDir,
TotalTransferSize: 0,
SentBytes: 0,
},
Receiving: &receiving{
AcceptedFiles: nil,
DownloadsPath: options.ReceiverSide.DownloadsFolderPath,
ReceivedBytes: 0,
TotalDownloadSize: 0,
},
},
}
return &node, nil
}
// Connect node to another listening one with a pre-defined address&&port
func (node *Node) connect() error {
if node.netInfo.Port == 0 {
node.netInfo.Port = 7270
}
fmt.Printf("\nConnecting to %s:%d...", node.netInfo.ConnAddr, node.netInfo.Port)
conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", node.netInfo.ConnAddr, node.netInfo.Port), time.Second*5)
if err != nil {
return err
}
fmt.Printf("\nConnected")
node.netInfo.Conn = conn
return nil
}
// Notify the other node and close the connection
func (node *Node) disconnect() error {
if node.netInfo.Conn != nil {
// notify the other node and close the connection
err := protocol.SendPacket(node.netInfo.Conn, protocol.Packet{
Header: protocol.HeaderDisconnecting,
})
if err != nil {
return err
}
err = node.netInfo.Conn.Close()
if err != nil {
return err
}
node.stopped = true
}
return nil
}
// Wait for a connection on a pre-defined port
func (node *Node) waitForConnection() error {
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", node.netInfo.Port))
if err != nil {
return err
}
// accept only one conneciton
connection, err := listener.Accept()
if err != nil {
return err
}
fmt.Printf("\nNew connection from %s", connection.RemoteAddr().String())
node.netInfo.Conn = connection
return nil
}
// Prints information about the transfer after defined delay
func (node *Node) printTransferInfo(delay time.Duration) error {
time.Sleep(delay)
switch node.isSending {
case true:
if !node.transferInfo.Sending.AllowedToTransfer {
// do not print if the transfer has not been accepted yet
break
}
fmt.Printf("\r| (%.2f/%.2f MB)",
float32(node.transferInfo.Sending.SentBytes)/1024/1024,
float32(node.transferInfo.Sending.TotalTransferSize)/1024/1024,
)
case false:
fmt.Printf("\r| (%.2f/%.2f MB)",
float32(node.transferInfo.Receiving.ReceivedBytes)/1024/1024,
float32(node.transferInfo.Receiving.TotalDownloadSize)/1024/1024,
)
}
return nil
}
func (node *Node) send() {
// SENDER NODE
localIP, err := addr.GetLocal()
if err != nil {
panic(err)
}
// retrieve information about the file|directory
var FILETOSEND *fsys.File
var DIRTOSEND *fsys.Directory
switch node.transferInfo.Sending.IsDirectory {
case true:
DIRTOSEND, err = fsys.GetDir(node.transferInfo.Sending.ServingPath, node.transferInfo.Sending.Recursive)
if err != nil {
panic(err)
}
case false:
FILETOSEND, err = fsys.GetFile(node.transferInfo.Sending.ServingPath)
if err != nil {
panic(err)
}
}
if DIRTOSEND != nil {
node.transferInfo.Sending.TotalTransferSize = DIRTOSEND.Size
displaySize := float32(DIRTOSEND.Size) / 1024 / 1024
sizeLevel := "MiB"
if displaySize >= 1024 {
// GiB
displaySize = displaySize / 1024
sizeLevel = "GiB"
}
fmt.Printf("\nSending \"%s\" (%.3f %s) locally on %s:%d and remotely (if configured)", DIRTOSEND.Name, displaySize, sizeLevel, localIP, node.netInfo.Port)
} else {
node.transferInfo.Sending.TotalTransferSize = FILETOSEND.Size
displaySize := float32(FILETOSEND.Size) / 1024 / 1024
sizeLevel := "MiB"
if displaySize >= 1024 {
// GiB
displaySize = displaySize / 1024
sizeLevel = "GiB"
}
fmt.Printf("\nSending \"%s\" (%.3f %s) locally on %s:%d and remotely (if configured)", FILETOSEND.Name, displaySize, sizeLevel, localIP, node.netInfo.Port)
}
// wain for another node to connect
err = node.waitForConnection()
if err != nil {
panic(err)
}
// generate and send encryption key
encrKey := encryption.Generate32AESkey()
node.netInfo.EncryptionKey = encrKey
fmt.Printf("\nGenerated encryption key: %s\n", encrKey)
err = protocol.SendEncryptionKey(node.netInfo.Conn, encrKey)
if err != nil {
panic(err)
}
// listen for incoming packets
go protocol.ReceivePackets(node.netInfo.Conn, node.packetPipe)
// send info about file/directory
go protocol.SendTransferOffer(node.netInfo.Conn, FILETOSEND, DIRTOSEND, node.netInfo.EncryptionKey)
// mainloop
for {
if node.stopped {
fmt.Printf("\n")
node.disconnect()
break
}
if !node.verboseOutput {
go node.printTransferInfo(time.Second)
}
// receive incoming packets and decrypt them if necessary
incomingPacket, ok := <-node.packetPipe
if !ok {
fmt.Printf("\nThe connection has been closed unexpectedly\n")
os.Exit(-1)
}
// if encryption key is set - decrypt packet on the spot
if node.netInfo.EncryptionKey != nil {
err = incomingPacket.DecryptBody(node.netInfo.EncryptionKey)
if err != nil {
panic(err)
}
}
// react based on a header of a received packet
switch incomingPacket.Header {
case protocol.HeaderReady:
// the other node is ready to receive file data
node.transferInfo.Sending.CanSendBytes = true
case protocol.HeaderAccept:
// the receiving node has accepted the transfer
node.transferInfo.Sending.AllowedToTransfer = true
// prepare files to send
switch node.transferInfo.Sending.IsDirectory {
case true:
// send file packets for the files in the directory
err = DIRTOSEND.SetRelativePaths(DIRTOSEND.Path, node.transferInfo.Sending.Recursive)
if err != nil {
panic(err)
}
filesToSend := DIRTOSEND.GetAllFiles(node.transferInfo.Sending.Recursive)
symlinksToSend := DIRTOSEND.GetAllSymlinks(node.transferInfo.Sending.Recursive)
node.transferInfo.Sending.SymlinksToSend = symlinksToSend
for counter, file := range filesToSend {
// assign ID and add it to the node sendlist
file.ID = uint64(counter)
node.transferInfo.Sending.FilesToSend = append(node.transferInfo.Sending.FilesToSend, file)
}
// set current file id to the first file
node.transferInfo.Sending.CurrentFileID = 0
case false:
FILETOSEND.ID = 0
node.transferInfo.Sending.FilesToSend = append(node.transferInfo.Sending.FilesToSend, FILETOSEND)
// set current file index to the first and only file
node.transferInfo.Sending.CurrentFileID = 0
}
fmt.Printf("\n")
case protocol.HeaderReject:
node.stopped = true
fmt.Printf("\nTransfer rejected. Disconnecting...")
case protocol.HeaderDisconnecting:
node.stopped = true
fmt.Printf("\n%s disconnected", node.netInfo.Conn.RemoteAddr())
case protocol.HeaderAlreadyHave:
// the other node already has a file with such ID.
// do not send it
fileIDReader := bytes.NewReader(incomingPacket.Body)
var fileID uint64
binary.Read(fileIDReader, binary.BigEndian, &fileID)
for index, fileToSend := range node.transferInfo.Sending.FilesToSend {
if fileToSend.ID == fileID {
node.transferInfo.Sending.FilesToSend = append(node.transferInfo.Sending.FilesToSend[:index], node.transferInfo.Sending.FilesToSend[index+1:]...)
node.transferInfo.Sending.CurrentFileID++
node.transferInfo.Sending.SentBytes += fileToSend.Size
node.transferInfo.Sending.InTransfer = false
if node.verboseOutput {
fmt.Printf("\n[File] receiver already has \"%s\"", fileToSend.Name)
}
}
}
}
// Transfer section
// if all files have been sent -> send symlinks
if len(node.transferInfo.Sending.FilesToSend) == 0 && node.transferInfo.Sending.CurrentSymlinkIndex < uint64(len(node.transferInfo.Sending.SymlinksToSend)) {
protocol.SendSymlink(node.transferInfo.Sending.SymlinksToSend[node.transferInfo.Sending.CurrentSymlinkIndex], node.netInfo.Conn, encrKey)
node.transferInfo.Sending.CurrentSymlinkIndex++
continue
}
if len(node.transferInfo.Sending.FilesToSend) == 0 && node.transferInfo.Sending.CurrentSymlinkIndex == uint64(len(node.transferInfo.Sending.SymlinksToSend)) {
// if there`s nothing else to send - create and send DONE packet
protocol.SendPacket(node.netInfo.Conn, protocol.Packet{
Header: protocol.HeaderDone,
})
node.stopped = true
continue
}
if node.transferInfo.Sending.AllowedToTransfer && !node.transferInfo.Sending.InTransfer {
// notify the node about the next file to be sent
// determine an index of a file with current ID
var currentFileIndex uint64 = 0
for index, fileToSend := range node.transferInfo.Sending.FilesToSend {
if fileToSend.ID == node.transferInfo.Sending.CurrentFileID {
currentFileIndex = uint64(index)
break
}
}
fpacket, err := protocol.CreateFilePacket(node.transferInfo.Sending.FilesToSend[currentFileIndex])
if err != nil {
panic(err)
}
if node.netInfo.EncryptionKey != nil {
err = fpacket.EncryptBody(node.netInfo.EncryptionKey)
if err != nil {
panic(err)
}
}
err = protocol.SendPacket(node.netInfo.Conn, *fpacket)
if err != nil {
panic(err)
}
// initiate the transfer for this file on the next iteration
node.transferInfo.Sending.InTransfer = true
continue
}
// if allowed to transfer and the other node is ready to receive packets - send one piece
// and wait for it to be ready again
if node.transferInfo.Sending.AllowedToTransfer && node.transferInfo.Sending.CanSendBytes && node.transferInfo.Sending.InTransfer {
// sending a piece of a single file
// determine an index of a file with current ID
var currentFileIndex uint64 = 0
for index, fileToSend := range node.transferInfo.Sending.FilesToSend {
if fileToSend.ID == node.transferInfo.Sending.CurrentFileID {
currentFileIndex = uint64(index)
break
}
}
sentBytes, err := protocol.SendPiece(node.transferInfo.Sending.FilesToSend[currentFileIndex], node.netInfo.Conn, node.netInfo.EncryptionKey)
node.transferInfo.Sending.SentBytes += sentBytes
switch err {
case protocol.ErrorSentAll:
// the file has been sent fully
if node.verboseOutput {
fmt.Printf("\n[File] fully sent \"%s\" -- %d bytes", node.transferInfo.Sending.FilesToSend[currentFileIndex].Name, node.transferInfo.Sending.FilesToSend[currentFileIndex].Size)
}
fileIDBuff := new(bytes.Buffer)
err = binary.Write(fileIDBuff, binary.BigEndian, node.transferInfo.Sending.FilesToSend[currentFileIndex].ID)
if err != nil {
panic(err)
}
endFilePacket := protocol.Packet{
Header: protocol.HeaderEndfile,
Body: fileIDBuff.Bytes(),
}
if node.netInfo.EncryptionKey != nil {
err = endFilePacket.EncryptBody(node.netInfo.EncryptionKey)
if err != nil {
panic(err)
}
}
protocol.SendPacket(node.netInfo.Conn, endFilePacket)
// remove this file from the queue
node.transferInfo.Sending.FilesToSend = append(node.transferInfo.Sending.FilesToSend[:currentFileIndex], node.transferInfo.Sending.FilesToSend[currentFileIndex+1:]...)
// set counter to the next file ID
node.transferInfo.Sending.CurrentFileID++
node.transferInfo.Sending.InTransfer = false
case nil:
node.transferInfo.Sending.CanSendBytes = false
default:
node.stopped = true
fmt.Printf("\n[ERROR] An error occured while sending a piece of \"%s\": %s", node.transferInfo.Sending.FilesToSend[currentFileIndex].Name, err)
panic(err)
}
}
}
}
func (node *Node) receive() {
// RECEIVER NODE
// connect to the sending node
err := node.connect()
if err != nil {
fmt.Printf("\n[ERROR] Could not connect to %s:%d\n", node.netInfo.ConnAddr, node.netInfo.Port)
os.Exit(-1)
}
// listen for incoming packets
go protocol.ReceivePackets(node.netInfo.Conn, node.packetPipe)
// mainloop
for {
node.mutex.Lock()
stopped := node.stopped
node.mutex.Unlock()
if stopped {
fmt.Printf("\n")
node.disconnect()
break
}
if !node.verboseOutput && node.transferInfo.Receiving.ReceivedBytes != 0 {
go node.printTransferInfo(time.Second)
}
// receive incoming packets and decrypt them if necessary
incomingPacket, ok := <-node.packetPipe
if !ok {
fmt.Printf("\nConnection has been closed unexpectedly\n")
os.Exit(-1)
}
// if encryption key is set - decrypt packet on the spot
if node.netInfo.EncryptionKey != nil {
err = incomingPacket.DecryptBody(node.netInfo.EncryptionKey)
if err != nil {
panic(err)
}
}
// react based on a header of a received packet
switch incomingPacket.Header {
case protocol.HeaderTransferOffer:
// accept of reject offer
go func() {
file, dir, err := protocol.DecodeTransferPacket(incomingPacket)
if err != nil {
panic(err)
}
if file != nil {
node.transferInfo.Receiving.TotalDownloadSize = file.Size
size := float32(file.Size) / 1024 / 1024
sizeLevel := "MiB"
if size >= 1024 {
// GiB
size = size / 1024
sizeLevel = "GiB"
}
fmt.Printf("\n| Filename: %s\n| Size: %.3f %s\n| Checksum: %s\n", file.Name, size, sizeLevel, file.Checksum)
} else if dir != nil {
node.transferInfo.Receiving.TotalDownloadSize = dir.Size
size := float32(dir.Size) / 1024 / 1024
sizeLevel := "MiB"
if size >= 1024 {
// GiB
size = size / 1024
sizeLevel = "GiB"
}
fmt.Printf("\n| Directory name: %s\n| Size: %.3f %s\n", dir.Name, size, sizeLevel)
}
var answer string
fmt.Printf("| Download ? [Y/n]: ")
fmt.Scanln(&answer)
fmt.Printf("\n\n")
if strings.EqualFold(answer, "y") || answer == "" {
// yes
// in case it`s a directory - create it now
if dir != nil {
err = os.MkdirAll(filepath.Join(node.transferInfo.Receiving.DownloadsPath, dir.Name), os.ModePerm)
if err != nil {
// well, just download all files in the default downloads folder then
fmt.Printf("\n[ERROR] could not create a directory, downloading directly to the specified location")
} else {
// also download everything in a newly created directory
node.transferInfo.Receiving.DownloadsPath = filepath.Join(node.transferInfo.Receiving.DownloadsPath, dir.Name)
}
}
// send aceptance packet
acceptancePacket := protocol.Packet{
Header: protocol.HeaderAccept,
}
err = protocol.SendPacket(node.netInfo.Conn, acceptancePacket)
if err != nil {
panic(err)
}
} else {
// no
rejectionPacket := protocol.Packet{
Header: protocol.HeaderReject,
}
err = protocol.SendPacket(node.netInfo.Conn, rejectionPacket)
if err != nil {
panic(err)
}
node.mutex.Lock()
node.stopped = true
node.mutex.Unlock()
}
}()
case protocol.HeaderFile:
// add file to the accepted files;
file, err := protocol.DecodeFilePacket(incomingPacket)
if err != nil {
panic(err)
}
if node.verboseOutput {
fmt.Printf("\n[File] Received info on \"%s\" - %d bytes", file.Name, file.Size)
}
if strings.TrimSpace(file.RelativeParentPath) == "" {
// does not have a parent dir
file.Path = filepath.Join(node.transferInfo.Receiving.DownloadsPath, file.Name)
} else {
file.Path = filepath.Join(node.transferInfo.Receiving.DownloadsPath, file.RelativeParentPath)
}
// create all underlying directories right ahead
err = os.MkdirAll(filepath.Dir(file.Path), os.ModePerm)
if err != nil {
panic(err)
}
// check if the file already exists
_, err = os.Stat(file.Path)
if err == nil {
// exists
// check if it is the exact file
existingFileHandler, err := os.Open(file.Path)
if err != nil {
panic(err)
}
existingFileChecksum, err := checksum.GetPartialCheckSum(existingFileHandler)
if err != nil {
panic(err)
}
if existingFileChecksum == file.Checksum {
// it`s the exact same file. No need to receive it again
// notify the other node
alreadyHavePacketBodyBuffer := new(bytes.Buffer)
binary.Write(alreadyHavePacketBodyBuffer, binary.BigEndian, file.ID)
alreadyHavePacket := protocol.Packet{
Header: protocol.HeaderAlreadyHave,
Body: alreadyHavePacketBodyBuffer.Bytes(),
}
if node.netInfo.EncryptionKey != nil {
encryptedBody, err := encryption.Encrypt(node.netInfo.EncryptionKey, alreadyHavePacket.Body)
if err != nil {
panic(err)
}
alreadyHavePacket.Body = encryptedBody
}
protocol.SendPacket(node.netInfo.Conn, alreadyHavePacket)
node.transferInfo.Receiving.ReceivedBytes += file.Size
if node.verboseOutput {
fmt.Printf("\n[File] already have \"%s\"", file.Name)
}
} else {
// not the same file. Remove it and await new bytes
os.Remove(file.Path)
node.mutex.Lock()
node.transferInfo.Receiving.AcceptedFiles = append(node.transferInfo.Receiving.AcceptedFiles, file)
node.mutex.Unlock()
err = protocol.SendPacket(node.netInfo.Conn, protocol.Packet{
Header: protocol.HeaderReady,
})
if err != nil {
panic(err)
}
}
existingFileHandler.Close()
} else {
// does not exist
node.mutex.Lock()
node.transferInfo.Receiving.AcceptedFiles = append(node.transferInfo.Receiving.AcceptedFiles, file)
node.mutex.Unlock()
err = protocol.SendPacket(node.netInfo.Conn, protocol.Packet{
Header: protocol.HeaderReady,
})
if err != nil {
panic(err)
}
}
case protocol.HeaderFileBytes:
// check if this file has been accepted to receive
fileBytesBuffer := bytes.NewBuffer(incomingPacket.Body)
var fileID uint64
err := binary.Read(fileBytesBuffer, binary.BigEndian, &fileID)
if err != nil {
panic(err)
}
for _, acceptedFile := range node.transferInfo.Receiving.AcceptedFiles {
if acceptedFile.ID == fileID {
// accepted
// append provided bytes to the file
if acceptedFile.Handler == nil {
err = acceptedFile.Open()
if err != nil {
panic(err)
}
}
fileBytes := fileBytesBuffer.Bytes()
wrote, err := acceptedFile.Handler.WriteAt(fileBytes, int64(acceptedFile.SentBytes))
if err != nil {
panic(err)
}
acceptedFile.SentBytes += uint64(wrote)
node.transferInfo.Receiving.ReceivedBytes += uint64(wrote)
}
}
readyPacket := protocol.Packet{
Header: protocol.HeaderReady,
}
protocol.SendPacket(node.netInfo.Conn, readyPacket)
case protocol.HeaderEndfile:
// one of the files has been received completely
fileIDReader := bytes.NewReader(incomingPacket.Body)
var fileID uint64
err := binary.Read(fileIDReader, binary.BigEndian, &fileID)
if err != nil {
panic(err)
}
for index, acceptedFile := range node.transferInfo.Receiving.AcceptedFiles {
if acceptedFile.ID == fileID {
// accepted
if node.verboseOutput {
fmt.Printf("\n[File] fully received \"%s\" -- %d bytes", acceptedFile.Name, acceptedFile.Size)
}
if acceptedFile.Handler == nil {
err = acceptedFile.Open()
if err != nil {
panic(err)
}
}
// remove this file from the pool
node.transferInfo.Receiving.AcceptedFiles = append(node.transferInfo.Receiving.AcceptedFiles[:index], node.transferInfo.Receiving.AcceptedFiles[index+1:]...)
// compare checksums
realChecksum, err := checksum.GetPartialCheckSum(acceptedFile.Handler)
if err != nil {
panic(err)
}
if realChecksum != acceptedFile.Checksum {
if node.verboseOutput {
fmt.Printf("\n[ERROR] \"%s\" is corrupted", acceptedFile.Name)
}
acceptedFile.Close()
break
} else {
acceptedFile.Close()
break
}
}
}
err = protocol.SendPacket(node.netInfo.Conn, protocol.Packet{
Header: protocol.HeaderReady,
})
if err != nil {
panic(err)
}
case protocol.HeaderEncryptionKey:
// retrieve the key
packetReader := bytes.NewReader(incomingPacket.Body)
var keySize uint64
binary.Read(packetReader, binary.BigEndian, &keySize)
encrKey := make([]byte, keySize)
packetReader.Read(encrKey)
node.netInfo.EncryptionKey = encrKey
fmt.Printf("\nGot an encryption key: %s", encrKey)
case protocol.HeaderSymlink:
// SYMLINK~(string size in binary)(location in the filesystem)(string size in binary)(location of a target)
packetReader := bytes.NewReader(incomingPacket.Body)
// extract the location of the symlink
var locationSize uint64
binary.Read(packetReader, binary.BigEndian, &locationSize)
symlinkLocationBytes := make([]byte, locationSize)
packetReader.Read(symlinkLocationBytes)
// extract the target of a symlink
var targetSize uint64
binary.Read(packetReader, binary.BigEndian, &targetSize)
symlinkTargetLocationBytes := make([]byte, targetSize)
packetReader.Read(symlinkTargetLocationBytes)
symlinkLocation := string(symlinkLocationBytes)
symlinkTargetLocation := string(symlinkTargetLocationBytes)
// create a symlink
// should be already downloaded
symlinkDir := filepath.Join(node.transferInfo.Receiving.DownloadsPath, filepath.Dir(symlinkLocation))
os.MkdirAll(symlinkDir, os.ModePerm)
os.Symlink(
filepath.Join(node.transferInfo.Receiving.DownloadsPath, symlinkTargetLocation),
filepath.Join(node.transferInfo.Receiving.DownloadsPath, symlinkLocation))
protocol.SendPacket(node.netInfo.Conn, protocol.Packet{
Header: protocol.HeaderReady,
})
case protocol.HeaderDone:
node.mutex.Lock()
node.stopped = true
node.mutex.Unlock()
case protocol.HeaderDisconnecting:
node.mutex.Lock()
node.stopped = true
node.mutex.Unlock()
fmt.Printf("\n%s disconnected", node.netInfo.Conn.RemoteAddr())
}
}
}
// Starts the node in either sending or receiving state and performs the transfer
func (node *Node) Start() {
switch node.isSending {
case true:
node.send()
case false:
node.receive()
}
}

40
src/node/options.go

@ -0,0 +1,40 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
package node
type SenderNodeOptions struct {
ServingPath string
Recursive bool
}
type ReceiverNodeOptions struct {
ConnectionAddr string
DownloadsFolderPath string
}
// Options to configure the node
type NodeOptions struct {
IsSending bool
WorkingPort uint
VerboseOutput bool
SenderSide *SenderNodeOptions
ReceiverSide *ReceiverNodeOptions
}

38
src/protocol/constants.go

@ -0,0 +1,38 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
// global constants of the protocol
package protocol
// MAXPACKETSIZE.
// How many bytes can contain one packet (header + body) at maximum
// (packets with size bigger than MAXPACKETSIZE are invalid and will not be sent)
const MAXPACKETSIZE uint = 131072 // 128 KiB
// HEADERDELIMETER.
// Character that delimits header of the packet from the body of the packet.
// ie: (packet header)~(packet body)
const HEADERDELIMETER string = "~"
// FILECODE.
const FILECODE string = "f"
// DIRCODE.
const DIRCODE string = "d"

123
src/protocol/headers.go

@ -0,0 +1,123 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
// This file describes various headers of the protocol and how to use them
package protocol
type Header string
// Headers
//// In the following examples "~" is the HEADERDELIMETER
//// and (size) is 8 bytes long big-endian binary encoded uint64
// ENCRKEY.
// The FIRST header to be sent if you`re going to encrypt the transfer. Sent immediately after the connection has been established
// by sender. Body contains a size of a key and the key itself.
// ie: ENCRKEY~(size)(encryption key)
const HeaderEncryptionKey Header = "ENCRKEY"
// REJECT.
// Sent only by receiver if the receiver has decided to not download the contents.
// ie: REJECT~
const HeaderReject Header = "REJECT"
// ACCEPT.
// The opposite of the previous REJECT. Sent by receiver when
// it has agreed to download the file|directory.
// ie: ACCEPT~
const HeaderAccept Header = "ACCEPT"
// DONE.
// Sent by sender. Warns the receiver that the transfer has been done and
// there is no more information to give.
// ie: DONE~
// Usually after the packet with this header has been sent, the receiver will send
// another packet back with header BYE!, telling that it`s going to disconnect
const HeaderDone Header = "DONE"
// READY.
// Sent by receiver when it has read and processed the last
// FILEBYTES or FILE packet. The sender is not allowed to "spam" FILEBYTES or FILE
// packets without the permission (packet with this header) from receiver.
// ie: READY!~
const HeaderReady Header = "READY"
// BYE!.
// Packet with this header can be sent both by receiver and sender.
// It`s used when the sender or the receiver are going to disconnect
// and will not be able to communicate.
// (Usually it`s when the error has happened OR after the DONE header
// has been sent by sender, warning receiver that there is no data to send)
// The BODY is better to be empty.
// ie: BYE!~
const HeaderDisconnecting Header = "BYE!"
// TRANSFEROFFER.
// Sent by sender AFTER ENCRKEY packet if present and BEFORE any other transfer-specific
// packet ONLY ONCE. Asks the receiving node whether it accepts or rejects the transfer of
// offered single file or a directory.
// The body must contain a file or directory code that tells whether
// a file or a directory will be sent in case of acceptance. The rest must be identical either to the FILE or DIRECTORY packet.
// e for directory: TRANSFER~(dircode)(dirname size in binary)(dirname)(dirsize)
// e for a single file: TRANSFER~(filecode)(id in binary)(filename length in binary)(filename)(filesize)(checksum length in binary)(checksum)
// dircode and filecode are pre-declared in the constants of the protocol (d) and (f).
// The actual transfer must start only after the other node has accepted the dir/file with ACCEPT packet.
const HeaderTransferOffer Header = "TRANSFEROFFER"
// FILE.
// Sent by sender, indicating that the file is going to be sent.
// The body structure must follow such structure:
// FILE~(id in binary)(filename length in binary)(filename)(filesize)(checksum length in binary)(checksum)(relative path to the upper directory size in binary if present)(relative path)
// relative path is not needed when the file is already in the root of the initial directory, but must be included when
// the whole directory is being sent recursively
const HeaderFile Header = "FILE"
// FILEBYTES.
// Sent only by sender. The packet`s body must contain
// a file`s Identifier and a portion of its bytes.
// ie: FILEBYTES~(file ID in binary)(file`s binary data)
const HeaderFileBytes Header = "FILEBYTES"
// ENDFILE
// Sent by sender when the file`s contents fully has been sent.
// The body must contain a file ID.
// ie: ENDFILE~(file ID in binary)
const HeaderEndfile Header = "ENDFILE"
// DIRECTORY
// Sent by sender. Used in TRANSFEROFFER packet to tell the difference
// between a file and a directory.
// ie: DIRECTORY~(dirname size in binary)(dirname)(dirsize)
const HeaderDirectory Header = "DIRECTORY"
// ALREADYHAVE
// Sent by receiver in case there is the same file that already exists.
// Sender upon receiving such packet with specified file ID must not send it.
// Body must contain a file ID.
// ie: ALREADYHAVE~(file ID in binary)
const HeaderAlreadyHave Header = "ALREADYHAVE"
// SYMLINK
// Sent by sender AFTER ALL FILES has been sent already. Indicates that there
// is a symlink in some place that points to some other already received file.
// Body must contain information where the symlink is and the target file.
// ie: SYMLINK~(string size in binary)(location in the filesystem)(string size in binary)(location of a target)
const HeaderSymlink Header = "SYMLINK"

134
src/protocol/packet.go

@ -0,0 +1,134 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
// General packet structure and methods to work with them before|after the transportation
// Packet structure during transportation:
// (size of the whole packet in binary (big endian uint64))(packet header)(header delimeter (~))(packet contents)
package protocol
import (
"bytes"
"encoding/binary"
"fmt"
"strings"
"unbewohnte/ftu/encryption"
)
// Internal representation of packet before|after the transportation
type Packet struct {
Header Header
Body []byte
}
var ErrorInvalidPacket error = fmt.Errorf("invalid packet header or body")
// Returns a size of the given packet as if it would be sent and presented in bytes.
// ie: FILE~bytes_here
func (packet *Packet) Size() uint64 {
packetBytes := new(bytes.Buffer)
packetBytes.Write([]byte(packet.Header))
packetBytes.Write([]byte(HEADERDELIMETER))
packetBytes.Write(packet.Body)
return uint64(packetBytes.Len())
}
// Converts packet bytes into Packet struct
func BytesToPacket(packetbytes []byte) (*Packet, error) {
// check if there`s a header delimiter present
pString := string(packetbytes)
if !strings.Contains(pString, HEADERDELIMETER) {
return nil, ErrorInvalidPacket
}
var header Header
var body []byte
for counter, b := range packetbytes {
if string(b) == HEADERDELIMETER {
header = Header(packetbytes[0:counter])
body = packetbytes[counter+1:]
break
}
}
return &Packet{
Header: header,
Body: body,
}, nil
}
var ErrorExceededMaxPacketsize error = fmt.Errorf("packet is too big")
// Converts given packet struct into ready-to-transfer bytes, constructed by following the protocol
func (packet *Packet) ToBytes() ([]byte, error) {
packetSize := packet.Size()
if packetSize > uint64(MAXPACKETSIZE) {
return nil, ErrorExceededMaxPacketsize
}
// creating a buffer and writing the whole packet into it
packetBuffer := new(bytes.Buffer)
// packet size bytes
err := binary.Write(packetBuffer, binary.BigEndian, &packetSize)
if err != nil {
return nil, err
}
// header, delimeter and body ie: FILENAME~file.txt
packetBuffer.Write([]byte(packet.Header))
packetBuffer.Write([]byte(HEADERDELIMETER))
packetBuffer.Write(packet.Body)
return packetBuffer.Bytes(), nil
}
// Encrypts packet`s BODY with AES encryption
func (packet *Packet) EncryptBody(key []byte) error {
// encrypting packet`s body
encryptedBody, err := encryption.Encrypt(key, packet.Body)
if err != nil {
return err
}
packet.Body = encryptedBody
return nil
}
// Decrypts packet`s BODY with AES decryption
func (packet *Packet) DecryptBody(key []byte) error {
if len(packet.Body) == 0 {
return nil
}
decryptedBody, err := encryption.Decrypt(key, packet.Body)
if err != nil {
return err
}
packet.Body = decryptedBody
return nil
}

103
src/protocol/packetConstruct.go

@ -0,0 +1,103 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
// Methods to construct various packets defined in a protocol
package protocol
import (
"bytes"
"encoding/binary"
"unbewohnte/ftu/fsys"
)
// constructs a ready to send FILE packet
func CreateFilePacket(file *fsys.File) (*Packet, error) {
err := file.Open()
if err != nil {
return nil, err
}
defer file.Close()
//(id in binary)(filename length in binary)(filename)(filesize)(checksum length in binary)(checksum)(relative path to the upper directory size in binary if present)(relative path)
filePacket := Packet{
Header: HeaderFile,
}
fPacketBodyBuff := new(bytes.Buffer)
// file id
binary.Write(fPacketBodyBuff, binary.BigEndian, &file.ID)
// filename
filenameLen := uint64(len([]byte(file.Name)))
binary.Write(fPacketBodyBuff, binary.BigEndian, &filenameLen)
fPacketBodyBuff.Write([]byte(file.Name))
// size
binary.Write(fPacketBodyBuff, binary.BigEndian, &file.Size)
// checksum
checksumLen := uint64(len([]byte(file.Checksum)))
binary.Write(fPacketBodyBuff, binary.BigEndian, &checksumLen)
fPacketBodyBuff.Write([]byte(file.Checksum))
// relative path
relPathLen := uint64(len([]byte(file.RelativeParentPath)))
binary.Write(fPacketBodyBuff, binary.BigEndian, &relPathLen)
fPacketBodyBuff.Write([]byte(file.RelativeParentPath))
filePacket.Body = fPacketBodyBuff.Bytes()
// we do not check for packet size because there is no way that it`ll exceed current
// maximum of 128 KiB
return &filePacket, nil
}
// constructs a ready to send DIRECTORY packet
func CreateDirectoryPacket(dir *fsys.Directory) (*Packet, error) {
dirPacket := Packet{
Header: HeaderDirectory,
}
// DIRECTORY~(dirname size in binary)(dirname)(dirsize)(checksumLengthInBinary)(checksum)
dirPacketBuffer := new(bytes.Buffer)
// dirname
dirnameLength := uint64(len(dir.Name))
err := binary.Write(dirPacketBuffer, binary.BigEndian, &dirnameLength)
if err != nil {
return nil, err
}
dirPacketBuffer.Write([]byte(dir.Name))
// dirsize
err = binary.Write(dirPacketBuffer, binary.BigEndian, dir.Size)
if err != nil {
return nil, err
}
dirPacket.Body = dirPacketBuffer.Bytes()
// we do not check for packet size because there is no way that it`ll exceed current
// maximum of 128 KiB
return &dirPacket, nil
}

189
src/protocol/packetDecode.go

@ -0,0 +1,189 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
// Methods to decode read from connection packets defined in protocol
package protocol
import (
"bytes"
"encoding/binary"
"fmt"
"unbewohnte/ftu/fsys"
)
var ErrorWrongPacket error = fmt.Errorf("wrong type of packet header")
// decodes packet with the header FILE into the fsys.File struct
func DecodeFilePacket(filePacket *Packet) (*fsys.File, error) {
if filePacket.Header != HeaderFile {
return nil, ErrorWrongPacket
}
//(id in binary)(filename length in binary)(filename)(filesize)(checksum length in binary)(checksum)(relative path to the upper directory size in binary if present)(relative path)
// retrieve data from packet body
// id
packetReader := bytes.NewBuffer(filePacket.Body)
var fileID uint64
err := binary.Read(packetReader, binary.BigEndian, &fileID)
if err != nil {
return nil, err
}
// filename
var filenameLength uint64
err = binary.Read(packetReader, binary.BigEndian, &filenameLength)
if err != nil {
return nil, err
}
filenameBytes := make([]byte, filenameLength)
_, err = packetReader.Read(filenameBytes)
if err != nil {
return nil, err
}
filename := string(filenameBytes)
// filesize
var filesize uint64
err = binary.Read(packetReader, binary.BigEndian, &filesize)
if err != nil {
return nil, err
}
// checksum
var checksumLength uint64
err = binary.Read(packetReader, binary.BigEndian, &checksumLength)
if err != nil {
return nil, err
}
checksumBytes := make([]byte, checksumLength)
_, err = packetReader.Read(checksumBytes)
if err != nil {
return nil, err
}
checksum := string(checksumBytes)
// relative path
var relPathLength uint64
err = binary.Read(packetReader, binary.BigEndian, &relPathLength)
if err != nil {
return nil, err
}
relPathBytes := make([]byte, relPathLength)
_, err = packetReader.Read(relPathBytes)
if err != nil {
return nil, err
}
relPath := string(relPathBytes)
return &fsys.File{
ID: fileID,
Name: filename,
Size: filesize,
Checksum: checksum,
RelativeParentPath: relPath,
Handler: nil,
}, nil
}
// decodes DIRECTORY packet into fsys.Directory struct
func DecodeDirectoryPacket(dirPacket *Packet) (*fsys.Directory, error) {
if dirPacket.Header != HeaderDirectory {
return nil, ErrorWrongPacket
}
// DIRECTORY~(dirname size in binary)(dirname)(dirsize)
packetReader := bytes.NewReader(dirPacket.Body)
// name
var dirNameSize uint64
err := binary.Read(packetReader, binary.BigEndian, &dirNameSize)
if err != nil {
return nil, err
}
dirName := make([]byte, dirNameSize)
_, err = packetReader.Read(dirName)
if err != nil {
return nil, err
}
// size
var dirSize uint64
err = binary.Read(packetReader, binary.BigEndian, &dirSize)
if err != nil {
return nil, err
}
dir := fsys.Directory{
Name: string(dirName),
Size: dirSize,
}
return &dir, nil
}
// decodes TRANSFERINFO packet into either fsys.File or fsys.Directory struct.
// decodeTransferPacket cannot return 2 nils or both non-nils as 2 first return values in case
// of a successfull decoding
func DecodeTransferPacket(transferPacket *Packet) (*fsys.File, *fsys.Directory, error) {
if transferPacket.Header != HeaderTransferOffer {
return nil, nil, ErrorWrongPacket
}
var file *fsys.File = nil
var dir *fsys.Directory = nil
var err error
// determine if it`s a file or a directory
switch string(transferPacket.Body[0]) {
case FILECODE:
filePacket := Packet{
Header: HeaderFile,
Body: transferPacket.Body[1:],
}
file, err = DecodeFilePacket(&filePacket)
if err != nil {
return nil, nil, err
}
case DIRCODE:
dirPacket := Packet{
Header: HeaderDirectory,
Body: transferPacket.Body[1:],
}
dir, err = DecodeDirectoryPacket(&dirPacket)
if err != nil {
return nil, nil, err
}
default:
return nil, nil, ErrorInvalidPacket
}
return file, dir, nil
}

101
src/protocol/protocol_test.go

@ -0,0 +1,101 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
package protocol
import (
"bytes"
"net"
"testing"
)
func Test_WriteRead(t *testing.T) {
packet := Packet{
Header: "randomheader",
Body: []byte("fIlEnAmE.txt"),
}
// a valid representation of received packet`s bytes
packetBytes, err := packet.ToBytes()
if err != nil {
t.Fatalf("%s", err)
}
// imitating a connection
l, err := net.Listen("tcp", ":9999")
if err != nil {
t.Fatalf("%s", err)
}
c, err := net.Dial("tcp", "localhost:9999")
if err != nil {
t.Fatalf("%s", err)
}
cc, err := l.Accept()
if err != nil {
t.Fatalf("%s", err)
}
defer c.Close()
defer cc.Close()
// sending packet
err = SendPacket(cc, packet)
if err != nil {
t.Fatalf("SendPacket failed: %s", err)
}
// reading it from c
receivedPacket, err := ReadFromConn(c)
if err != nil {
t.Fatalf("ReadFromConn failed: %s", err)
}
// drop packetsize for valid packet bytes because they are also dropped in ReadFromConn
packetBytes = packetBytes[8:]
for index, b := range receivedPacket {
if b != packetBytes[index] {
t.Fatalf("Error: packet bytes do not match: expected %v, got: %v; valid packet: %v; received packet: %v", string(packetBytes[index]), string(b), packetBytes, receivedPacket)
}
}
}
func Test_BytesToPacket(t *testing.T) {
packet := Packet{
Header: HeaderFileBytes,
Body: []byte("fIlEnAmE.txt"),
}
packetBuffer := new(bytes.Buffer)
packetBuffer.Write([]byte(packet.Header))
packetBuffer.Write([]byte(HEADERDELIMETER))
packetBuffer.Write(packet.Body)
// a valid representation of received packet`s bytes
packetBytes := packetBuffer.Bytes()
convertedPacket, err := BytesToPacket(packetBytes)
if err != nil {
t.Fatalf("BytesToPacket error: %s", err)
}
if convertedPacket.Header != packet.Header || string(convertedPacket.Body) != string(packet.Body) {
t.Fatalf("BytesToPacket error: header or body of converted packet does not match with the original")
}
}

89
src/protocol/recv.go

@ -0,0 +1,89 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
// Methods allowing to receive and preprocess packets from connection
package protocol
import (
"bytes"
"encoding/binary"
"fmt"
"net"
)
// Reads a packet from given connection, returns its bytes.
// ASSUMING THAT THE PACKETS ARE SENT BY `SendPacket` function !!!!
func ReadFromConn(connection net.Conn) ([]byte, error) {
var packetSize uint64
err := binary.Read(connection, binary.BigEndian, &packetSize)
if err != nil {
return nil, err
}
// have a packetsize, now reading the whole packet
packetBuffer := new(bytes.Buffer)
// splitting a big-sized packet into chunks and constructing it from pieces
left := packetSize
for {
if left == 0 {
break
}
buff := make([]byte, 8192)
if left < uint64(len(buff)) {
buff = make([]byte, left)
}
read, _ := connection.Read(buff)
left -= uint64(read)
packetBuffer.Write(buff[:read])
}
// fmt.Printf("[RECV] read from connection: %s; length: %d\n", packetBuffer.Bytes()[:30], packetBuffer.Len())
return packetBuffer.Bytes(), nil
}
var ErrorNotConnected error = fmt.Errorf("not connected")
// Reads packets from connection in an endless loop, sends them to the channel
func ReceivePackets(connection net.Conn, packetPipe chan *Packet) error {
for {
if connection == nil {
return ErrorNotConnected
}
packetBytes, err := ReadFromConn(connection)
if err != nil {
close(packetPipe)
return err
}
incomingPacket, err := BytesToPacket(packetBytes)
if err != nil {
close(packetPipe)
return err
}
packetPipe <- incomingPacket
}
}

244
src/protocol/send.go

@ -0,0 +1,244 @@
/*
ftu - file transferring utility.
Copyright (C) 2021,2022 Kasyanov Nikolay Alexeyevich (Unbewohnte)
This file is a part of ftu
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 <https://www.gnu.org/licenses/>.
*/
// Methonds to send packets in various ways defined in protocol
package protocol
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"net"
"unbewohnte/ftu/encryption"
"unbewohnte/ftu/fsys"
)
// Sends given packet to connection.
// ALL packets MUST be sent by this method
func SendPacket(connection net.Conn, packet Packet) error {
packetBytes, err := packet.ToBytes()
if err != nil {
return err
}
// fmt.Printf("[SEND] packet %+s; len: %d\n", packetBytes[:30], len(packetBytes))
// write the result (ie: (packetsize)(header)~(bodybytes))
connection.Write(packetBytes)
return nil
}
// sends an encryption key to the other side
func SendEncryptionKey(connection net.Conn, encrKey []byte) error {
encrKeyPacketBuffer := new(bytes.Buffer)
encrKeyLength := uint64(len(encrKey))
err := binary.Write(encrKeyPacketBuffer, binary.BigEndian, &encrKeyLength)
if err != nil {
return err
}
encrKeyPacketBuffer.Write(encrKey)
err = SendPacket(connection, Packet{
Header: HeaderEncryptionKey,
Body: encrKeyPacketBuffer.Bytes(),
})
if err != nil {
return err
}
return nil
}
// sends a TRANSFEROFFER packet to connection with information about either file or directory.
// If file is the only thing that the sender is going to send - leave dir arg as nil, the same
// applies if directory is the only thing that the sender is going to send - leave file as nil.
// sendTransferOffer PANICS if both file and dir are present or nil. If encrKey != nil - encrypts
// constructed packet
func SendTransferOffer(connection net.Conn, file *fsys.File, dir *fsys.Directory, encrKey []byte) error {
if file == nil && dir == nil {
panic("either file or dir must be specified")
} else if file != nil && dir != nil {
panic("only one either file or dir must be specified")
}
transferOfferPacket := Packet{
Header: HeaderTransferOffer,
}
if file != nil {
filePacket, err := CreateFilePacket(file)
if err != nil {
return err
}
transferOfferBody := append([]byte(FILECODE), filePacket.Body...)
// if encrKey is present - encrypt
if encrKey != nil {
encryptedBody, err := encryption.Encrypt(encrKey, transferOfferBody)
if err != nil {
return err
}
transferOfferBody = encryptedBody
}
transferOfferPacket.Body = transferOfferBody
} else if dir != nil {
dirPacket, err := CreateDirectoryPacket(dir)
if err != nil {
return err
}
transferOfferBody := append([]byte(DIRCODE), dirPacket.Body...)
// if encrKey is present - encrypt
if encrKey != nil {
encryptedBody, err := encryption.Encrypt(encrKey, transferOfferBody)
if err != nil {
return err
}
transferOfferBody = encryptedBody
}
transferOfferPacket.Body = transferOfferBody
}
// send packet
err := SendPacket(connection, transferOfferPacket)
if err != nil {
return err
}
return nil
}
var ErrorSentAll error = fmt.Errorf("sent the whole file")
// Sends a piece of file to the connection; The next calls will send
// another piece util the file has been fully sent. If encrKey is not nil - encrypts each packet with
// this key. Returns amount of filebytes written to the connection
func SendPiece(file *fsys.File, connection net.Conn, encrKey []byte) (uint64, error) {
var sentBytes uint64 = 0
err := file.Open()
if err != nil {
return sentBytes, err
}
defer file.Close()
if file.SentBytes == 0 {
file.Handler.Seek(0, io.SeekStart)
}
if file.Size == file.SentBytes {
return sentBytes, ErrorSentAll
}
fileBytesPacket := Packet{
Header: HeaderFileBytes,
}
packetBodyBuff := new(bytes.Buffer)
// write file ID first
err = binary.Write(packetBodyBuff, binary.BigEndian, file.ID)
if err != nil {
return sentBytes, err
}
// fill the remaining space of packet with the contents of a file
canSendBytes := uint64(MAXPACKETSIZE) - fileBytesPacket.Size() - uint64(packetBodyBuff.Len())
if encrKey != nil {
// account for padding
canSendBytes -= 48
}
if (file.Size - file.SentBytes) < canSendBytes {
canSendBytes = (file.Size - file.SentBytes)
}
fileBytes := make([]byte, canSendBytes)
read, err := file.Handler.ReadAt(fileBytes, int64(file.SentBytes))
if err != nil {
return sentBytes, err
}
file.SentBytes += uint64(read)
sentBytes += uint64(canSendBytes)
packetBodyBuff.Write(fileBytes)
fileBytesPacket.Body = packetBodyBuff.Bytes()
if encrKey != nil {
err = fileBytesPacket.EncryptBody(encrKey)
if err != nil {
return sentBytes, err
}
}
// send it to the other side
err = SendPacket(connection, fileBytesPacket)
if err != nil {
return 0, err
}
return sentBytes, nil
}
// Sends a symlink to the other side. If encrKey is not nil - encrypts the packet with this key
func SendSymlink(symlink *fsys.Symlink, connection net.Conn, encrKey []byte) error {
symlinkPacket := Packet{
Header: HeaderSymlink,
}
symlinkPacketBodyBuff := new(bytes.Buffer)
// SYMLINK~(string size in binary)(location in the filesystem)(string size in binary)(location of a target)
binary.Write(symlinkPacketBodyBuff, binary.BigEndian, uint64(len(symlink.Path)))
symlinkPacketBodyBuff.Write([]byte(symlink.Path))
binary.Write(symlinkPacketBodyBuff, binary.BigEndian, uint64(len(symlink.TargetPath)))
symlinkPacketBodyBuff.Write([]byte(symlink.TargetPath))
symlinkPacket.Body = symlinkPacketBodyBuff.Bytes()
if encrKey != nil {
err := symlinkPacket.EncryptBody(encrKey)
if err != nil {
return err
}
}
err := SendPacket(connection, symlinkPacket)
if err != nil {
return err
}
return nil
}

0
src/testfiles/testDownload/testfile.txt

9
src/testfiles/testdir/testdir2/testfile3.txt

@ -0,0 +1,9 @@
testfile3
SAMPLE TEXT
lCtrl + Lshift + u
15dc 2ec 15dc
not on Windows tho AFAIK

9
src/testfiles/testdir/testfile2.txt

@ -0,0 +1,9 @@
testfile2
there are no buses
in Gensokyo btw (9)
yeah...

1
src/testfiles/testdir/testsymlink2.txt

@ -0,0 +1 @@
../testfiles/testdir/testfile2.txt

1
src/testfiles/testdir3/nested1/nested2/testfilen.txt

@ -0,0 +1 @@
test

3
src/testfiles/testdir3/testfile4

@ -0,0 +1,3 @@
testfile4
*something smart and philosophic*

11
src/testfiles/testfile.txt

@ -0,0 +1,11 @@
727 WYSI Airman Badeu square
doable
FCeeeeeeeeeeeeeeeeeeeeeeeee
testfile it is

1
src/testfiles/testsymlink.txt

@ -0,0 +1 @@
../testfiles/testfile.txt
Loading…
Cancel
Save