From: Ramakrishnan Muthukrishnan Date: Sun, 17 Jul 2016 04:08:50 +0000 (+0530) Subject: starting with a clean slate X-Git-Url: https://git.rkrishnan.org/Site/Content/Exhibitors/module-simplejson._speedups.html?a=commitdiff_plain;h=ad1587e61564e6a677fa9000daaf209b0c95a5b4;p=functorrent.git starting with a clean slate --- diff --git a/AUTHORS b/AUTHORS deleted file mode 100644 index 4dc8f3b..0000000 --- a/AUTHORS +++ /dev/null @@ -1,5 +0,0 @@ -In alphabetic order of the first name: - -Abhiranjan Kumar -Jaseem Abid -Ramakrishnan Muthukrishnan diff --git a/COPYING b/COPYING deleted file mode 100644 index 45644ff..0000000 --- a/COPYING +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/README.md b/README.md deleted file mode 100644 index 457a754..0000000 --- a/README.md +++ /dev/null @@ -1,67 +0,0 @@ -# A command line BitTorrent client. - -I started writing a BitTorrent client because it seemed like fun -and I am learning Haskell and wanted to see if I can write something -real with Haskell than just heat the room. It is turning out to be a -lot of fun. - -### Building - -You need to install [Stack](https://github.com/commercialhaskell/stack), either via -the OS package manager or via `cabal` (`cabal install stack`). - - $ git clone https://github.com/vu3rdd/functorrent && cd functorrent - $ cabal install stack # or install stack by other means - $ stack build # binaries in $(pwd)/.stack-work/install/x86..../lts-2.16/7.8.4/bin/functorrent - -### Usage - -If you invoke functorrent without any options, it expects the contents of a torrent file -to be given in stdin. So - - $ cat ubuntu-14.10-desktop-amd64.iso.torrent | functorrent - [....] - -Or one can explicitly specify the torrent file as input. - - $ functorrent ubuntu-14.10-desktop-amd64.iso.torrent - [...] - -### Goals - -- [Optimized for Fun](http://www.slideshare.net/autang/ofun-optimizing-for-fun). - (should have called it "funtorrent") -- Become more profient with Haskell. -- Implement something non-trivial with Haskell (crypto, file operations, network - operations, concurrency, bit twiddling, DHT). -- Follow the spec ([official spec](http://bittorrent.org/beps/bep_0003.html), [unofficial spec](https://wiki.theory.org/BitTorrentSpecification)) -- Easy for newbies like me to read and understand alongside the spec. -- doctest and quickcheck tests. -- Follow Haskell Style Guide - https://github.com/tibbe/haskell-style-guide/blob/master/haskell-style.md - -### WARNING - -This client is not usable as your daily BitTorrent client yet. You may get -corrupted files and end up wasting a lot of bandwidth. So, until we achieve -some robustness, consider this as a programmer-friendly project to learn -about a bunch of stuff. - -### Current Status - -- most of the peer wire protocol works. -- talks only to one peer at the moment. -- can download files. But needs every piece to be served by the peer it connected to. -- can talk to http/udp trackers. - -### TODO - -- Test suite. -- Talk to multiple peers concurrently. -- Piece download algorithms. -- Multifile torrent support. -- Magnet link support. -- other advanced features of BitTorrent (like DHT). - -### Misc - -The Bangalore Haskell group forked an early version of this code and started to develop it as a group. My code has diverged a lot from it. Both are calling it functorrent. Perhaps that needs to be fixed. diff --git a/Setup.hs b/Setup.hs deleted file mode 100644 index 9a994af..0000000 --- a/Setup.hs +++ /dev/null @@ -1,2 +0,0 @@ -import Distribution.Simple -main = defaultMain diff --git a/data/The.Flash.2014.S01E14.HDTV.x264-LOL.mp4.127fc6b23a3dc168.torrent b/data/The.Flash.2014.S01E14.HDTV.x264-LOL.mp4.127fc6b23a3dc168.torrent deleted file mode 100644 index fac643a..0000000 Binary files a/data/The.Flash.2014.S01E14.HDTV.x264-LOL.mp4.127fc6b23a3dc168.torrent and /dev/null differ diff --git a/data/debian-7.8.0-amd64-CD-1.iso.cache b/data/debian-7.8.0-amd64-CD-1.iso.cache deleted file mode 100644 index 9086a9d..0000000 --- a/data/debian-7.8.0-amd64-CD-1.iso.cache +++ /dev/null @@ -1,3 +0,0 @@ -d8:intervali900e5:peers300:UÉeÈÕ%;ìVÎL•+ʚ·!Í©ËÕÒxVkXÕïØÍ[À£˜.:>ÒðAWTúg¡%XÃñÀÈÕX¥=ßáVêóè¿Õ)‰òÈÕ[ -T÷]@8ù·oÊ>Gê+~záØD©…HÄ.߇a±å½¦]vûËȔmÈÕmâì ­œN:‹šY"¼ô/ºšÛËVÌoÌ»Pn(bD»ŽÙãðGs‹´öYF©#­ÈÕ¹‡º*‰XÆàÊÈÕ·AÙ#ÛWû½–¶XWrÊ®0i]:ÈÓYf E'<^ŸÞ=§_1°åªÙr:‡áO¢&‹Þˆ©2H֏»C¼—ÈÕOoÚ2ф>K‰ÈÕÌœ-PO¢"_ÓRÀöèÔ"ç -PÌ_áöÝÈÕ|)ífa*6:peers60:e \ No newline at end of file diff --git a/data/debian-7.8.0-amd64-CD-1.iso.error b/data/debian-7.8.0-amd64-CD-1.iso.error deleted file mode 100644 index c19b09a..0000000 --- a/data/debian-7.8.0-amd64-CD-1.iso.error +++ /dev/null @@ -1 +0,0 @@ -d14:failure reason17:torrent not founde \ No newline at end of file diff --git a/data/debian-7.8.0-amd64-CD-1.iso.torrent b/data/debian-7.8.0-amd64-CD-1.iso.torrent deleted file mode 100644 index 7a3c0a0..0000000 Binary files a/data/debian-7.8.0-amd64-CD-1.iso.torrent and /dev/null differ diff --git a/data/debian-8.2.0-amd64-CD-1.iso.torrent b/data/debian-8.2.0-amd64-CD-1.iso.torrent deleted file mode 100644 index ea0ab8c..0000000 Binary files a/data/debian-8.2.0-amd64-CD-1.iso.torrent and /dev/null differ diff --git a/data/hello.txt b/data/hello.txt deleted file mode 100644 index 3b18e51..0000000 --- a/data/hello.txt +++ /dev/null @@ -1 +0,0 @@ -hello world diff --git a/data/hello.txt.cache b/data/hello.txt.cache deleted file mode 100644 index 8b51ab7..0000000 --- a/data/hello.txt.cache +++ /dev/null @@ -1 +0,0 @@ -d8:completei0e10:incompletei0e8:intervali130e12:min intervali130e5:peers0:e diff --git a/data/hello.txt.torrent b/data/hello.txt.torrent deleted file mode 100644 index f9c4bdd..0000000 --- a/data/hello.txt.torrent +++ /dev/null @@ -1 +0,0 @@ -d8:announce32:http://9.rarbg.com:2710/announce7:comment11:hello world10:created by11:Jaseem Abid13:creation datei1428717851e8:encoding5:UTF-84:infod6:lengthi12e4:name9:hello.txt12:piece lengthi32768e6:pieces20:"Ycc³Þ@°o˜¸]‚1.ŒÕ7:privatei0eee \ No newline at end of file diff --git a/data/ubuntu-14.10-desktop-amd64.iso.torrent b/data/ubuntu-14.10-desktop-amd64.iso.torrent deleted file mode 100644 index d38a2f6..0000000 Binary files a/data/ubuntu-14.10-desktop-amd64.iso.torrent and /dev/null differ diff --git a/data/ubuntu-14.10-desktop-i386.iso.torrent b/data/ubuntu-14.10-desktop-i386.iso.torrent deleted file mode 100644 index 7e453ce..0000000 Binary files a/data/ubuntu-14.10-desktop-i386.iso.torrent and /dev/null differ diff --git a/data/ubuntu-15.10-desktop-amd64.iso.torrent b/data/ubuntu-15.10-desktop-amd64.iso.torrent deleted file mode 100644 index 5a006d1..0000000 Binary files a/data/ubuntu-15.10-desktop-amd64.iso.torrent and /dev/null differ diff --git a/data/ubuntu-16.04-desktop-amd64.iso.torrent b/data/ubuntu-16.04-desktop-amd64.iso.torrent deleted file mode 100644 index 1d2e0cb..0000000 Binary files a/data/ubuntu-16.04-desktop-amd64.iso.torrent and /dev/null differ diff --git a/doc/design.md b/doc/design.md deleted file mode 100644 index e5dbd9d..0000000 --- a/doc/design.md +++ /dev/null @@ -1,53 +0,0 @@ -2016-03-10: - -A rough sketch of the design of the program. - -In the Unix tradition, FuncTorrent takes either a .torrent file as input or one -can `cat' the .torrent file and pipe the output into the program: - -$ cat foo.torrent | ./functorrent - -As of 10/Mar/2016, FuncTorrent supports only HTTP tracker. - -Each module starts up as a thread, so we have FileSystem thread, we have a Tracker -Client thread. We have a main client thread, that receives pieces. We also have a -Server thread that serves pieces. - -The messages themselves are not exposed outside the module. Instead, a function that -create a message passing channel is exposed and also helper functions that talk via -the channel to the module are also exposed. So, it is the duty of the Module to expose -relevant functions that sends/receives messages. - -Tracker -------- - -Tracker module has two submodules: one for Http and another for Udp. UDP one is not -ready yet. So, let us talk about http. The tracker module would take care of dispatching -to the apropriate module (udp or http) depending on the tracker server url that we -decode from the .torrent file. The Tracker currently takes two messages: one to get the -tracker status (tracker url could be defunct and could time out or the tracker server -may return a genuine error response, which is captured in a bytestring). The module -has an 'newTracker' function, that just creates a new channel. It also has a 'runTracker' -function that takes the above created channel and a bunch of parameters including the -FileSystem channel (since FileSystem module is the 'owner' of the bytes read/write -statistics). It then spawns a thread that talks to the tracker server and the rest of -the function is a loop which is looking for and handling messages on the msg channel. - -Tracker messages are defined in Tracker/Types.hs - -data TrackerMsg = GetStatusMsg TrackerEventState - | GetConnectedPeersMsg (MVar [Peer]) - -i.e. There are two messages. GetStatusMsg is to get the current state of the TrackerClient (us) -to Tracker Server communication. TrackerEventState is also defined in Tracker/Types.hs as - -data TrackerEventState = None - | Started - | Completed - | Error ByteString - deriving (Show, Eq) - -In particular, the Error EventState signifies any possible error signalled by the -server, based on which, the user of the Tracker module can take some action. - -So, once started, diff --git a/functorrent.cabal b/functorrent.cabal deleted file mode 100644 index 3de1ebf..0000000 --- a/functorrent.cabal +++ /dev/null @@ -1,94 +0,0 @@ --- Initial functorrent.cabal generated by cabal init. For further documentation, --- see http://haskell.org/cabal/users-guide/ - -name: functorrent -version: 0.2.0 -synopsis: A Bit-torrent client -description: A bittorrent client -license: GPL-3 -license-file: COPYING -author: Ramakrishnan Muthukrishnan -maintainer: ram@rkrishnan.org --- copyright: -category: Network -build-type: Simple -extra-source-files: README.md -cabal-version: >=1.18 - -library - exposed-modules: FuncTorrent.Bencode, - FuncTorrent.FileSystem, - FuncTorrent.Logger, - FuncTorrent.Metainfo, - FuncTorrent.Network - FuncTorrent.Peer, - FuncTorrent.PeerMsgs, - FuncTorrent.PieceManager, - FuncTorrent.Server, - FuncTorrent.Tracker, - FuncTorrent.Tracker.Http, - FuncTorrent.Tracker.Types, - FuncTorrent.Tracker.Udp, - FuncTorrent.Utils - - other-extensions: OverloadedStrings - hs-source-dirs: src - ghc-options: -Wall -fwarn-incomplete-patterns -fno-warn-orphans - default-language: Haskell2010 - build-depends: base, - base16-bytestring, - binary, - bytestring, - containers, - cryptohash, - directory, - HTTP, - mtl, - network, - network-uri, - parsec, - QuickCheck, - random, - safe, - transformers - -executable functorrent - main-is: Main.hs - other-extensions: OverloadedStrings - hs-source-dirs: src/main - ghc-options: -Wall -fwarn-incomplete-patterns -optc-Os -fno-warn-orphans - default-language: Haskell2010 - build-depends: base, - base16-bytestring, - binary, - bytestring, - containers, - cryptohash, - directory, - functorrent, - HTTP, - mtl, - network, - network-uri, - QuickCheck, - random, - safe - -test-suite functorrent-test - type: exitcode-stdio-1.0 - default-language: Haskell2010 - hs-source-dirs: test - main-is: Test.hs - other-modules: BencodeTests - build-depends: base, - functorrent, - bytestring, - containers, - directory, - doctest, - QuickCheck, - tasty, - tasty-hunit, - QuickCheck, - tasty-quickcheck, - test-framework-quickcheck2 diff --git a/src/FuncTorrent/Bencode.hs b/src/FuncTorrent/Bencode.hs deleted file mode 100644 index f359465..0000000 --- a/src/FuncTorrent/Bencode.hs +++ /dev/null @@ -1,198 +0,0 @@ -{- - - Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan - - - - This file is part of FuncTorrent. - - - - FuncTorrent 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. - - - - FuncTorrent 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 FuncTorrent; if not, see - -} - -{-# LANGUAGE OverloadedStrings #-} -module FuncTorrent.Bencode - (BVal(..) - , bValToBList - , bValToBytestr - , bValToInfoDict - , bValToInteger - , bstrToString - , decode - , encode - ) where - -import Prelude hiding (length, concat) - -import Data.ByteString (ByteString, length, concat) -import Data.ByteString.Char8 (unpack, pack) -import Data.Map.Strict (Map, fromList, toList) -import Text.ParserCombinators.Parsec -import qualified Text.Parsec.ByteString as ParsecBS -import Test.QuickCheck - -data BVal = Bint Integer - | Bstr ByteString - | Blist [BVal] - | Bdict (Map String BVal) - deriving (Ord, Eq, Show) - -instance Arbitrary ByteString where - arbitrary = pack <$> arbitrary - -instance Arbitrary BVal where - arbitrary = sized bval - where - bval :: Int -> Gen BVal - bval 0 = oneof [ Bint <$> arbitrary - , Bstr <$> arbitrary] - bval n = oneof [ Bint <$> arbitrary - , Bstr <$> arbitrary - , Blist <$> vectorOf n (bval (n `div` 4)) - , do keys <- vectorOf n arbitrary - vals <- vectorOf n (bval (n `div` 4)) - return $ Bdict $ fromList $ zip keys vals ] - --- getters -bValToInteger :: BVal -> Maybe Integer -bValToInteger (Bint x) = Just x -bValToInteger _ = Nothing - -bValToBytestr :: BVal -> Maybe ByteString -bValToBytestr (Bstr bs) = Just bs -bValToBytestr _ = Nothing - -bValToBList :: BVal -> Maybe [BVal] -bValToBList (Blist lst) = Just lst -bValToBList _ = Nothing - -bValToInfoDict :: BVal -> Maybe (Map String BVal) -bValToInfoDict (Bdict dict) = Just dict -bValToInfoDict _ = Nothing - -bstrToString :: BVal -> Maybe String -bstrToString bval = unpack <$> bValToBytestr bval - --- $setup --- >>> import Data.Either - --- | parse strings --- --- >>> parse bencStr "Bstr" (pack "4:spam") --- Right "spam" --- >>> parse bencStr "Bstr" (pack "0:") --- Right "" --- >>> parse bencStr "Bstr" (pack "0:hello") --- Right "" --- -bencStr :: ParsecBS.Parser ByteString -bencStr = do ds <- many1 digit <* char ':' - s <- count (read ds) anyChar - return (pack s) - --- | parse integers --- --- >>> parse bencInt "Bint" (pack "i42e") --- Right 42 --- >>> parse bencInt "Bint" (pack "i123e") --- Right 123 --- >>> parse bencInt "Bint" (pack "i1e") --- Right 1 --- >>> parse bencInt "Bint" (pack "i0e") --- Right 0 --- >>> parse bencInt "Bint" (pack "i-1e") --- Right (-1) --- >>> isLeft $ parse bencInt "Bint" (pack "i01e") --- True --- >>> isLeft $ parse bencInt "Bint" (pack "i00e") --- True --- >>> isLeft $ parse bencInt "Bint" (pack "i002e") --- True -bencInt :: ParsecBS.Parser Integer -bencInt = do ds <- between (char 'i') (char 'e') numbers - return (read ds) - where numbers = do d' <- char '-' <|> digit - ds' <- many digit - parseNumber d' ds' - parseNumber '0' [] = return "0" - parseNumber '0' _ = unexpected "numbers cannot be left-padded with zeros" - parseNumber '-' [] = unexpected "sign without any digits" - parseNumber '-' (d'':_) | d'' == '0' = unexpected "numbers cannot be left-padded with zeros" - parseNumber d'' ds'' = return (d'':ds'') - --- | parse lists --- --- >>> parse bencList "Blist" (pack "le") --- Right [] --- >>> parse bencList "Blist" (pack "l4:spam4:eggse") --- Right [Bstr "spam",Bstr "eggs"] --- >>> parse bencList "Blist" (pack "l4:spami42ee") --- Right [Bstr "spam",Bint 42] --- >>> parse bencList "Blist" (pack "l4:spam4:eggsli42eee") --- Right [Bstr "spam",Bstr "eggs",Blist [Bint 42]] -bencList :: ParsecBS.Parser [BVal] -bencList = between (char 'l') (char 'e') (many bencVal) - --- | parse dict --- --- >>> parse bencDict "Bdict" (pack "de") --- Right (fromList []) --- >>> parse bencDict "Bdict" (pack "d3:cow3:moo4:spam4:eggse") --- Right (fromList [("cow",Bstr "moo"),("spam",Bstr "eggs")]) --- >>> parse bencDict "Bdict" (pack "d4:spaml1:a1:bee") --- Right (fromList [("spam",Blist [Bstr "a",Bstr "b"])]) --- >>> parse bencDict "Bdict" (pack "d9:publisher3:bob17:publisher-webpage15:www.example.com18:publisher.location4:homee") --- Right (fromList [("publisher",Bstr "bob"),("publisher-webpage",Bstr "www.example.com"),("publisher.location",Bstr "home")]) -bencDict :: ParsecBS.Parser (Map String BVal) -bencDict = between (char 'd') (char 'e') $ fromList <$> many kvpair - where kvpair = do k <- bencStr - v <- bencVal - return (unpack k, v) - -bencVal :: ParsecBS.Parser BVal -bencVal = Bstr <$> bencStr <|> - Bint <$> bencInt <|> - Blist <$> bencList <|> - Bdict <$> bencDict - -decode :: ByteString -> Either ParseError BVal -decode = parse bencVal "BVal" - --- Encode BVal into a bencoded ByteString. Inverse of decode - --- TODO: Use builders and lazy byte string to get O(1) concatenation over O(n) --- provided by lists. - --- TODO: encode . decode pair might be a good candidate for Quickcheck. --- | encode bencoded-values --- --- >>> encode (Bstr (pack "")) --- "0:" --- >>> encode (Bstr (pack "spam")) --- "4:spam" --- >>> encode (Bint 0) --- "i0e" --- >>> encode (Bint 42) --- "i42e" --- >>> encode (Blist [(Bstr (pack "spam")), (Bstr (pack "eggs"))]) --- "l4:spam4:eggse" --- >>> encode (Blist []) --- "le" --- >>> encode (Bdict (fromList [("spam", Bstr $ pack "eggs")])) --- "d4:spam4:eggse" -encode :: BVal -> ByteString -encode (Bstr bs) = pack $ show (length bs) ++ ":" ++ unpack bs -encode (Bint i) = pack $ "i" ++ show i ++ "e" -encode (Blist xs) = concat ["l", concat $ map encode xs, "e"] -encode (Bdict d) = concat ["d", concat kvlist, "e"] - where - kvlist :: [ByteString] - kvlist = [encPair kv | kv <- toList d] - encPair (k, v) = concat [encode . Bstr . pack $ k, encode v] diff --git a/src/FuncTorrent/FileSystem.hs b/src/FuncTorrent/FileSystem.hs deleted file mode 100644 index 7c95c1e..0000000 --- a/src/FuncTorrent/FileSystem.hs +++ /dev/null @@ -1,131 +0,0 @@ -{- - - Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan - - - - This file is part of FuncTorrent. - - - - FuncTorrent 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. - - - - FuncTorrent 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 FuncTorrent; if not, see - -} - -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE FlexibleContexts #-} - -module FuncTorrent.FileSystem - (run, - MsgChannel, - createMsgChannel, - writePieceToDisk, - Piece(..), - pieceMapFromFile, - Stats(..), - getStats - ) - where - -import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan) -import Control.Concurrent.MVar (MVar, newEmptyMVar, putMVar) -import Control.Monad (forever) -import Control.Monad.State (StateT, liftIO, get, runStateT, modify) -import qualified Data.ByteString as BS -import Data.Map (traverseWithKey, (!)) -import System.IO (Handle, IOMode (ReadWriteMode), withFile) -import System.Directory (doesFileExist) - -import FuncTorrent.PieceManager (PieceDlState(..), PieceData(..), PieceMap, pieceNumToOffset) -import FuncTorrent.Utils (createDummyFile, readFileAtOffset, writeFileAtOffset, verifyHash) - -type PieceNum = Integer -data Piece = Piece PieceNum BS.ByteString - -data Msg = ReadPiece PieceNum Integer (MVar Piece) - | WritePiece Piece - | VerifyPiece PieceNum (MVar Bool) - | GetStats (MVar Stats) - -type MsgChannel = Chan Msg - -data Stats = Stats { bytesRead :: Integer - , bytesWritten :: Integer - } - -createMsgChannel :: IO (Chan Msg) -createMsgChannel = newChan - -run :: PieceMap -> MsgChannel -> Handle -> IO () -run pieceMap c handle = forever $ do - _ <- runStateT (run' pieceMap c handle) initialStats - return () - where initialStats = Stats { bytesRead = 0 - , bytesWritten = 0 } - -run' :: PieceMap -> MsgChannel -> Handle -> StateT Stats IO () -run' pieceMap c handle = do - stats <- get - msg <- liftIO recvMsg - liftIO $ sendResponse msg stats - updateStats msg - where - recvMsg = readChan c - sendResponse msg stats = - case msg of - ReadPiece n len' var -> do - bs <- readPiece n len' - putMVar var (Piece n bs) - WritePiece (Piece n bs) -> - writePiece n bs - VerifyPiece n var -> do - isHashValid <- verifyPiece n - putMVar var isHashValid - GetStats var -> - putMVar var stats - readPiece n len' = do - let offset = pieceNumToOffset pieceMap n - readFileAtOffset handle offset len' - writePiece n piece = do - let offset = pieceNumToOffset pieceMap n - writeFileAtOffset handle offset piece - verifyPiece n = do - let offset = pieceNumToOffset pieceMap n - hash' = hash (pieceMap ! n) - len' = len (pieceMap ! n) - bs' <- readFileAtOffset handle offset len' - return $ verifyHash bs' hash' - updateStats (ReadPiece _ l _) = - modify (\st -> st {bytesRead = bytesRead st + l}) - updateStats (WritePiece (Piece _ bs)) = - modify (\st -> st {bytesWritten = bytesWritten st + fromIntegral (BS.length bs)}) - updateStats _ = modify id - -pieceMapFromFile :: FilePath -> Integer -> PieceMap -> IO PieceMap -pieceMapFromFile filePath fileLen pieceMap = do - dfe <- doesFileExist filePath - if dfe - then traverseWithKey f pieceMap - else createDummyFile filePath (fromIntegral fileLen) >> return pieceMap - where - f k v = do - let offset = pieceNumToOffset pieceMap k - isHashValid <- flip verifyHash (hash v) <$> withFile filePath ReadWriteMode (\handle -> readFileAtOffset handle offset (len v)) - if isHashValid - then return $ v { dlstate = Have } - else return v - -writePieceToDisk :: MsgChannel -> PieceNum -> BS.ByteString -> IO () -writePieceToDisk c pieceNum bs = - writeChan c $ WritePiece (Piece pieceNum bs) - -getStats :: MsgChannel -> IO (MVar Stats) -getStats c = do - v <- newEmptyMVar - writeChan c $ GetStats v - return v diff --git a/src/FuncTorrent/Logger.hs b/src/FuncTorrent/Logger.hs deleted file mode 100644 index 431a96c..0000000 --- a/src/FuncTorrent/Logger.hs +++ /dev/null @@ -1,72 +0,0 @@ -{- - - Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan - - - - This file is part of FuncTorrent. - - - - FuncTorrent 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. - - - - FuncTorrent 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 FuncTorrent; if not, see - -} - -module FuncTorrent.Logger ( - initLogger - , logMessage - , logStop - ) where - -import Control.Concurrent - --- The below logger implementation has been taken from --- Parallel and Concurrent Programming in Haskell, Chapter 7 --- The logger is implemented in a concurrent thread. - --- Here the (MVar LogCommand) is used for actual thread communication --- So if multiple threads try to log, then the logger will be thread-safe --- Also the 'loop' in logger will wait for the message to come. --- --- The MVar in stop is just to ensure the logger thread executes completely --- Before exiting the main application. -data Logger = Logger (MVar LogCommand) -data LogCommand = Message String | Stop (MVar ()) - -initLogger :: IO Logger -initLogger = do - m <- newEmptyMVar - let l = Logger m - _ <- forkIO (logger l) - return l - -logger :: Logger -> IO () -logger (Logger m) = loop - where - loop = do - cmd <- takeMVar m - case cmd of - Message msg -> do - -- We can alternatively put the message to a file - putStrLn msg - -- Recursive - loop - Stop s -> do - putStrLn "FuncTorrent: Exit succesfully" - putMVar s () - --- Send log message to logger -logMessage :: Logger -> String -> IO () -logMessage (Logger m) s = putMVar m (Message s) - -logStop :: Logger -> IO () -logStop (Logger m) = do - s <- newEmptyMVar - putMVar m (Stop s) - -- Wait for logger to complete the logging - takeMVar s diff --git a/src/FuncTorrent/Metainfo.hs b/src/FuncTorrent/Metainfo.hs deleted file mode 100644 index 898cc54..0000000 --- a/src/FuncTorrent/Metainfo.hs +++ /dev/null @@ -1,104 +0,0 @@ -{- - - Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan - - - - This file is part of FuncTorrent. - - - - FuncTorrent 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. - - - - FuncTorrent 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 FuncTorrent; if not, see - -} - -module FuncTorrent.Metainfo - (Info(..), - Metainfo(..), - torrentToMetainfo - ) where - -import Prelude hiding (lookup) -import Data.ByteString.Char8 (ByteString, unpack) -import Data.Map as M ((!), lookup) -import Crypto.Hash.SHA1 (hash) -import Data.Maybe (maybeToList) - -import FuncTorrent.Bencode (BVal(..), encode, decode, bstrToString, bValToInteger) - --- only single file mode supported for the time being. -data Info = Info { pieceLength :: !Integer - , pieces :: !ByteString - , private :: !(Maybe Integer) - , name :: !String - , lengthInBytes :: !Integer - , md5sum :: !(Maybe String) - } deriving (Eq, Show) - -data Metainfo = Metainfo { info :: !Info - , announceList :: ![String] - , creationDate :: !(Maybe Integer) - , comment :: !(Maybe String) - , createdBy :: !(Maybe String) - , encoding :: !(Maybe String) - , infoHash :: !ByteString - } deriving (Eq, Show) - -mkInfo :: BVal -> Maybe Info -mkInfo (Bdict m) = let (Bint pieceLength') = m ! "piece length" - (Bstr pieces') = m ! "pieces" - private' = Nothing - (Bstr name') = m ! "name" - (Bint length') = m ! "length" - md5sum' = Nothing - in Just Info { pieceLength = pieceLength' - , pieces = pieces' - , private = private' - , name = unpack name' - , lengthInBytes = length' - , md5sum = md5sum'} -mkInfo _ = Nothing - -mkMetaInfo :: BVal -> Either String Metainfo -mkMetaInfo (Bdict m) = - let (Just info') = mkInfo $ m ! "info" - announce' = lookup "announce" m - announceList' = lookup "announce-list" m - creationDate' = lookup "creation date" m - comment' = lookup "comment" m - createdBy' = lookup "created by" m - encoding' = lookup "encoding" m - in Right Metainfo { - info = info' - , announceList = maybeToList (announce' >>= bstrToString) - ++ getAnnounceList announceList' - , creationDate = bValToInteger =<< creationDate' - , comment = bstrToString =<< comment' - , createdBy = bstrToString =<< createdBy' - , encoding = bstrToString =<< encoding' - , infoHash = hash . encode $ (m ! "info") - } -mkMetaInfo _ = Left "mkMetaInfo: expect an input dict" - -getAnnounceList :: Maybe BVal -> [String] -getAnnounceList Nothing = [] -getAnnounceList (Just (Bint _)) = [] -getAnnounceList (Just (Bstr _)) = [] -getAnnounceList (Just (Blist l)) = map (\s -> case s of - (Bstr s') -> unpack s' - (Blist s') -> case s' of - [Bstr s''] -> unpack s'' - _ -> "" - _ -> "") l -getAnnounceList (Just (Bdict _)) = [] - -torrentToMetainfo :: ByteString -> Either String Metainfo -torrentToMetainfo s = - case decode s of - Right d -> mkMetaInfo d - Left e -> Left $ show e diff --git a/src/FuncTorrent/Network.hs b/src/FuncTorrent/Network.hs deleted file mode 100644 index 99243f6..0000000 --- a/src/FuncTorrent/Network.hs +++ /dev/null @@ -1,45 +0,0 @@ -{- - - Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan - - - - This file is part of FuncTorrent. - - - - FuncTorrent 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. - - - - FuncTorrent 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 FuncTorrent; if not, see - -} - -{-# LANGUAGE OverloadedStrings #-} - -module FuncTorrent.Network - (sendGetRequest - , mkParams - ) where - -import Prelude hiding (concat) - -import Data.ByteString (ByteString) -import Data.ByteString.Char8 as BC (pack, unpack, concat, intercalate) -import Network.HTTP (simpleHTTP, defaultGETRequest_, getResponseBody) -import Network.URI (parseURI) - --- | Make a query string from a alist of k, v --- TODO: Url encode each argument -mkParams :: [(String, ByteString)] -> ByteString -mkParams params = BC.intercalate "&" [concat [pack f, "=", s] | (f,s) <- params] - -sendGetRequest :: String -> [(String, ByteString)] -> IO ByteString -sendGetRequest url args = simpleHTTP (defaultGETRequest_ url') >>= getResponseBody - where url' = case parseURI url'' of - Just x -> x - _ -> error $ "Bad tracker URL: " ++ show url'' - qstr = mkParams args - url'' = unpack $ concat [pack url, "?", qstr] diff --git a/src/FuncTorrent/Peer.hs b/src/FuncTorrent/Peer.hs deleted file mode 100644 index bf1153b..0000000 --- a/src/FuncTorrent/Peer.hs +++ /dev/null @@ -1,201 +0,0 @@ -{- - - Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan - - - - This file is part of FuncTorrent. - - - - FuncTorrent 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. - - - - FuncTorrent 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 FuncTorrent; if not, see - -} - -{-# LANGUAGE OverloadedStrings #-} - -module FuncTorrent.Peer - (handlePeerMsgs - ) where - -import Prelude hiding (lookup, concat, replicate, splitAt, take, drop) - -import Control.Monad.State -import Data.ByteString (ByteString, unpack, concat, hGet, hPut, take, drop, empty) -import Data.Bits -import Data.Word (Word8) -import Data.Map ((!), adjust) -import Network (connectTo, PortID(..)) -import System.IO (Handle, BufferMode(..), hSetBuffering, hClose) - -import FuncTorrent.Metainfo (Metainfo(..)) -import FuncTorrent.PeerMsgs (Peer(..), PeerMsg(..), sendMsg, getMsg, genHandshakeMsg) -import FuncTorrent.Utils (splitNum, verifyHash) -import FuncTorrent.PieceManager (PieceDlState(..), PieceData(..), PieceMap, pickPiece, updatePieceAvailability) -import qualified FuncTorrent.FileSystem as FS (MsgChannel, writePieceToDisk) - -data PState = PState { handle :: Handle - , peer :: Peer - , meChoking :: Bool - , meInterested :: Bool - , heChoking :: Bool - , heInterested :: Bool} - -havePiece :: PieceMap -> Integer -> Bool -havePiece pm index = - dlstate (pm ! index) == Have - -connectToPeer :: Peer -> IO Handle -connectToPeer (Peer ip port) = do - h <- connectTo ip (PortNumber (fromIntegral port)) - hSetBuffering h LineBuffering - return h - -doHandshake :: Bool -> Handle -> Peer -> ByteString -> String -> IO () -doHandshake True h p infohash peerid = do - let hs = genHandshakeMsg infohash peerid - hPut h hs - putStrLn $ "--> handhake to peer: " ++ show p - _ <- hGet h (length (unpack hs)) - putStrLn $ "<-- handshake from peer: " ++ show p - return () -doHandshake False h p infohash peerid = do - let hs = genHandshakeMsg infohash peerid - putStrLn "waiting for a handshake" - hsMsg <- hGet h (length (unpack hs)) - putStrLn $ "<-- handshake from peer: " ++ show p - let rxInfoHash = take 20 $ drop 28 hsMsg - if rxInfoHash /= infohash - then do - putStrLn "infoHashes does not match" - hClose h - return () - else do - _ <- hPut h hs - putStrLn $ "--> handhake to peer: " ++ show p - return () - -bitfieldToList :: [Word8] -> [Integer] -bitfieldToList bs = go bs 0 - where go [] _ = [] - go (b:bs') pos = - let setBits = [pos*8 + toInteger i | i <- [0..8], testBit b i] - in - setBits ++ go bs' (pos + 1) - --- helper functions to manipulate PeerState -toPeerState :: Handle - -> Peer - -> Bool -- ^ meChoking - -> Bool -- ^ meInterested - -> Bool -- ^ heChoking - -> Bool -- ^ heInterested - -> PState -toPeerState h p meCh meIn heCh heIn = - PState { handle = h - , peer = p - , heChoking = heCh - , heInterested = heIn - , meChoking = meCh - , meInterested = meIn } - -handlePeerMsgs :: Peer -> String -> Metainfo -> PieceMap -> Bool -> FS.MsgChannel -> IO () -handlePeerMsgs p peerId m pieceMap isClient c = do - h <- connectToPeer p - doHandshake isClient h p (infoHash m) peerId - let pstate = toPeerState h p False False True True - _ <- runStateT (msgLoop pieceMap c) pstate - return () - -msgLoop :: PieceMap -> FS.MsgChannel -> StateT PState IO () -msgLoop pieceStatus msgchannel = do - h <- gets handle - st <- get - case st of - PState { meInterested = False, heChoking = True } -> do - liftIO $ sendMsg h InterestedMsg - gets peer >>= (\p -> liftIO $ putStrLn $ "--> InterestedMsg to peer: " ++ show p) - modify (\st' -> st' { meInterested = True }) - msgLoop pieceStatus msgchannel - PState { meInterested = True, heChoking = False } -> - case pickPiece pieceStatus of - Nothing -> liftIO $ putStrLn "Nothing to download" - Just workPiece -> do - let pLen = len (pieceStatus ! workPiece) - liftIO $ putStrLn $ "piece length = " ++ show pLen - pBS <- liftIO $ downloadPiece h workPiece pLen - if not $ verifyHash pBS (hash (pieceStatus ! workPiece)) - then - liftIO $ putStrLn "Hash mismatch" - else do - liftIO $ putStrLn $ "Write piece: " ++ show workPiece - liftIO $ FS.writePieceToDisk msgchannel workPiece pBS - msgLoop (adjust (\pieceData -> pieceData { dlstate = Have }) workPiece pieceStatus) msgchannel - _ -> do - msg <- liftIO $ getMsg h - gets peer >>= (\p -> liftIO $ putStrLn $ "<-- " ++ show msg ++ " from peer: " ++ show p) - case msg of - KeepAliveMsg -> do - liftIO $ sendMsg h KeepAliveMsg - gets peer >>= (\p -> liftIO $ putStrLn $ "--> " ++ "KeepAliveMsg to peer: " ++ show p) - msgLoop pieceStatus msgchannel - BitFieldMsg bss -> do - p <- gets peer - let pieceList = bitfieldToList (unpack bss) - pieceStatus' = updatePieceAvailability pieceStatus p pieceList - liftIO $ putStrLn $ show (length pieceList) ++ " Pieces" - -- for each pieceIndex in pieceList, make an entry in the pieceStatus - -- map with pieceIndex as the key and modify the value to add the peer. - -- download each of the piece in order - msgLoop pieceStatus' msgchannel - UnChokeMsg -> do - modify (\st' -> st' {heChoking = False }) - msgLoop pieceStatus msgchannel - ChokeMsg -> do - modify (\st' -> st' {heChoking = True }) - msgLoop pieceStatus msgchannel - InterestedMsg -> do - modify (\st' -> st' {heInterested = True}) - msgLoop pieceStatus msgchannel - NotInterestedMsg -> do - modify (\st' -> st' {heInterested = False}) - msgLoop pieceStatus msgchannel - CancelMsg {} -> -- check if valid index, begin, length - msgLoop pieceStatus msgchannel - PortMsg _ -> - msgLoop pieceStatus msgchannel - HaveMsg idx -> do - p <- gets peer - let pieceStatus' = updatePieceAvailability pieceStatus p [idx] - msgLoop pieceStatus' msgchannel - _ -> do - liftIO $ putStrLn ".. not doing anything with the msg" - msgLoop pieceStatus msgchannel - -- No need to handle PieceMsg and RequestMsg here. - - -downloadPiece :: Handle -> Integer -> Integer -> IO ByteString -downloadPiece h index pieceLength = do - let chunks = splitNum pieceLength 16384 - concat `liftM` forM (zip [0..] chunks) (\(i, pLen) -> do - sendMsg h (RequestMsg index (i*pLen) pLen) - putStrLn $ "--> " ++ "RequestMsg for Piece " - ++ show index ++ ", part: " ++ show i ++ " of length: " - ++ show pLen - msg <- getMsg h - case msg of - PieceMsg index begin block -> do - putStrLn $ " <-- PieceMsg for Piece: " - ++ show index - ++ ", offset: " - ++ show begin - return block - _ -> do - putStrLn $ "ignoring irrelevant msg: " ++ show msg - return empty) - diff --git a/src/FuncTorrent/PeerMsgs.hs b/src/FuncTorrent/PeerMsgs.hs deleted file mode 100644 index f597ed8..0000000 --- a/src/FuncTorrent/PeerMsgs.hs +++ /dev/null @@ -1,153 +0,0 @@ -{- - - Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan - - - - This file is part of FuncTorrent. - - - - FuncTorrent 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. - - - - FuncTorrent 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 FuncTorrent; if not, see - -} - -{-# LANGUAGE OverloadedStrings #-} - -module FuncTorrent.PeerMsgs - (genHandshakeMsg, - sendMsg, - getMsg, - Peer(..), - makePeer, - PeerMsg(..) - ) where - -import Prelude hiding (lookup, concat, replicate, splitAt, take) - -import System.IO (Handle) -import Data.ByteString (ByteString, pack, unpack, concat, hGet, hPut, singleton) -import Data.ByteString.Lazy (fromStrict, fromChunks, toStrict) -import Data.ByteString.Char8 as BC (splitAt) -import qualified Data.ByteString.Char8 as BC (replicate, pack) -import Control.Monad (replicateM, liftM) -import Control.Applicative (liftA3) - -import Data.Binary (Binary(..), decode, encode) -import Data.Binary.Put (putWord32be, putWord16be, putWord8) -import Data.Binary.Get (getWord32be, getWord16be, getWord8, runGet) - -import FuncTorrent.Utils (toIP, toPort) - --- | Peer is a IP address, port tuple -data Peer = Peer IP Port - deriving (Show, Eq) - -type ID = String -type IP = String -type Port = Integer - -data PeerMsg = KeepAliveMsg - | ChokeMsg - | UnChokeMsg - | InterestedMsg - | NotInterestedMsg - | HaveMsg Integer - | BitFieldMsg ByteString - | RequestMsg Integer Integer Integer - | PieceMsg Integer Integer ByteString - | CancelMsg Integer Integer Integer - | PortMsg Port - deriving (Show) - -instance Binary PeerMsg where - put msg = case msg of - KeepAliveMsg -> putWord32be 0 - ChokeMsg -> do putWord32be 1 - putWord8 0 - UnChokeMsg -> do putWord32be 1 - putWord8 1 - InterestedMsg -> do putWord32be 1 - putWord8 2 - NotInterestedMsg -> do putWord32be 1 - putWord8 3 - HaveMsg i -> do putWord32be 5 - putWord8 4 - putWord32be (fromIntegral i) - BitFieldMsg bf -> do putWord32be $ fromIntegral (1 + bfListLen) - putWord8 5 - mapM_ putWord8 bfList - where bfList = unpack bf - bfListLen = length bfList - RequestMsg i o l -> do putWord32be 13 - putWord8 6 - putIndexOffsetLength i o l - PieceMsg i o b -> do putWord32be $ fromIntegral (9 + blocklen) - putWord8 7 - putWord32be (fromIntegral i) - putWord32be (fromIntegral o) - mapM_ putWord8 blockList - where blockList = unpack b - blocklen = length blockList - CancelMsg i o l -> do putWord32be 13 - putWord8 8 - putIndexOffsetLength i o l - PortMsg p -> do putWord32be 3 - putWord8 9 - putWord16be (fromIntegral p) - where putIndexOffsetLength i o l = do - putWord32be (fromIntegral i) - putWord32be (fromIntegral o) - putWord32be (fromIntegral l) - - get = do - l <- getWord32be - msgid <- getWord8 - case msgid of - 0 -> return ChokeMsg - 1 -> return UnChokeMsg - 2 -> return InterestedMsg - 3 -> return NotInterestedMsg - 4 -> fmap (HaveMsg . fromIntegral) getWord32be - 5 -> fmap (BitFieldMsg . pack) (replicateM (fromIntegral l - 1) getWord8) - 6 -> liftA3 RequestMsg getInteger getInteger getInteger - where getInteger = fromIntegral <$> getWord32be - 7 -> liftA3 PieceMsg getInteger getInteger (pack <$> replicateM (fromIntegral l - 9) getWord8) - where getInteger = fromIntegral <$> getWord32be - 8 -> liftA3 CancelMsg getInteger getInteger getInteger - where getInteger = fromIntegral <$> getWord32be - 9 -> fmap (PortMsg . fromIntegral) getWord16be - _ -> error ("unknown message ID: " ++ show msgid) - -getMsg :: Handle -> IO PeerMsg -getMsg h = do - lBS <- hGet h 4 - let l = bsToInt lBS - if l == 0 - then return KeepAliveMsg - else do - msg <- hGet h l - return $ decode $ fromStrict $ concat [lBS, msg] - -sendMsg :: Handle -> PeerMsg -> IO () -sendMsg h msg = hPut h bsMsg - where bsMsg = toStrict $ encode msg - -genHandshakeMsg :: ByteString -> String -> ByteString -genHandshakeMsg infoHash peer_id = concat [pstrlen, pstr, reserved, infoHash, peerID] - where pstrlen = singleton 19 - pstr = BC.pack "BitTorrent protocol" - reserved = BC.replicate 8 '\0' - peerID = BC.pack peer_id - -bsToInt :: ByteString -> Int -bsToInt x = fromIntegral (runGet getWord32be (fromChunks (return x))) - -makePeer :: ByteString -> Peer -makePeer peer = Peer (toIP ip') (toPort port') - where (ip', port') = splitAt 4 peer diff --git a/src/FuncTorrent/PieceManager.hs b/src/FuncTorrent/PieceManager.hs deleted file mode 100644 index c4617ca..0000000 --- a/src/FuncTorrent/PieceManager.hs +++ /dev/null @@ -1,88 +0,0 @@ -{- - - Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan - - - - This file is part of FuncTorrent. - - - - FuncTorrent 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. - - - - FuncTorrent 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 FuncTorrent; if not, see - -} - -module FuncTorrent.PieceManager - (PieceDlState(..), - PieceData(..), - PieceMap, - pieceNumToOffset, - updatePieceAvailability, - pickPiece, - bytesDownloaded, - initPieceMap, - ) where - -import Prelude hiding (filter) - -import qualified Data.ByteString.Char8 as BC (length) -import Control.Monad (liftM) -import Data.ByteString (ByteString) -import Data.Map (Map, (!), fromList, toList, mapWithKey, filter) -import Safe (headMay) - -import FuncTorrent.PeerMsgs (Peer) -import FuncTorrent.Utils (splitN, splitNum) - -data PieceDlState = Pending - | Downloading - | Have - deriving (Show, Eq) - --- todo - map with index to a new data structure (peers who have that piece and state) -data PieceData = PieceData { peers :: [Peer] -- ^ list of peers who have this piece - , dlstate :: PieceDlState -- ^ state of the piece from download perspective. - , hash :: ByteString -- ^ piece hash - , len :: Integer } -- ^ piece length - --- which piece is with which peers -type PieceMap = Map Integer PieceData - -pieceNumToOffset :: PieceMap -> Integer -> Integer -pieceNumToOffset _ 0 = 0 -pieceNumToOffset pieceMap k = k * len (pieceMap ! (k - 1)) - --- simple algorithm to pick piece. --- pick the first piece from 0 that is not downloaded yet. -pickPiece :: PieceMap -> Maybe Integer -pickPiece = - (fst `liftM`) . headMay . toList . filter (\v -> dlstate v == Pending) - -bytesDownloaded :: PieceMap -> Integer -bytesDownloaded = - sum . map (len . snd) . toList . filter (\v -> dlstate v == Have) - -updatePieceAvailability :: PieceMap -> Peer -> [Integer] -> PieceMap -updatePieceAvailability pieceStatus p pieceList = - mapWithKey (\k pd -> if k `elem` pieceList - then (pd { peers = p : peers pd }) - else pd) pieceStatus - --- Make the initial Piece map, with the assumption that no peer has the --- piece and that every piece is pending download. -initPieceMap :: ByteString -> Integer -> Integer -> PieceMap -initPieceMap pieceHash fileLen pieceLen = fromList kvs - where - numPieces = (toInteger . (`quot` 20) . BC.length) pieceHash - kvs = [(i, PieceData { peers = [] - , dlstate = Pending - , hash = h - , len = pLen }) - | (i, h, pLen) <- zip3 [0..numPieces] hashes pLengths] - hashes = splitN 20 pieceHash - pLengths = splitNum fileLen pieceLen diff --git a/src/FuncTorrent/Server.hs b/src/FuncTorrent/Server.hs deleted file mode 100644 index d8a18ff..0000000 --- a/src/FuncTorrent/Server.hs +++ /dev/null @@ -1,48 +0,0 @@ -{- - - Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan - - - - This file is part of FuncTorrent. - - - - FuncTorrent 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. - - - - FuncTorrent 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 FuncTorrent; if not, see - -} - -{-# LANGUAGE OverloadedStrings #-} - -module FuncTorrent.Server where - -import Control.Concurrent (forkIO) -import Control.Monad (forever) -import Network (withSocketsDo, listenOn, accept, Socket, PortID ( PortNumber )) -import System.IO (hSetBuffering, BufferMode ( NoBuffering )) - -import FuncTorrent.Metainfo (Metainfo) -import FuncTorrent.Peer (handlePeerMsgs) -import FuncTorrent.PeerMsgs (Peer(..)) -import FuncTorrent.PieceManager (PieceMap) -import qualified FuncTorrent.FileSystem as FS (MsgChannel) - --- server is listening on any port from 6881 - 6889 --- return the port number used -start :: IO (Socket, PortID) -start = withSocketsDo $ do - let portnums = [6881 .. 6889] - sock <- listenOn $ PortNumber $ fromIntegral (head portnums) - return (sock, PortNumber $ head portnums) - -run :: Socket -> String -> Metainfo -> PieceMap -> FS.MsgChannel -> IO () -run listenSock peerid m pieceMap c = forever $ do - (handle, ip, port) <- accept listenSock - let peer = Peer ip (fromIntegral port) - hSetBuffering handle NoBuffering - forkIO $ handlePeerMsgs peer peerid m pieceMap False c diff --git a/src/FuncTorrent/Tracker.hs b/src/FuncTorrent/Tracker.hs deleted file mode 100644 index b9e977a..0000000 --- a/src/FuncTorrent/Tracker.hs +++ /dev/null @@ -1,90 +0,0 @@ -{- - - Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan - - - - This file is part of FuncTorrent. - - - - FuncTorrent 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. - - - - FuncTorrent 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 FuncTorrent; if not, see - -} - -{-# LANGUAGE OverloadedStrings #-} -module FuncTorrent.Tracker - (runTracker - , getConnectedPeers - , newTracker - ) where - -import Control.Concurrent(forkIO) -import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan) -import Control.Concurrent.MVar (newEmptyMVar, putMVar, readMVar) -import Control.Monad.State (StateT, liftIO, get, runStateT) -import Control.Monad (forever) -import Data.ByteString.Char8 (ByteString) -import Data.List (isPrefixOf) -import Network (PortNumber) - -import qualified FuncTorrent.Tracker.Http as HT (trackerLoop) -import qualified FuncTorrent.Tracker.Udp as UT (trackerLoop) -import FuncTorrent.Tracker.Types (TState(..), TrackerEventState(..), TrackerProtocol(..), TrackerMsg(..)) -import qualified FuncTorrent.FileSystem as FS (MsgChannel) -import FuncTorrent.PeerMsgs (Peer) - -type MsgChannel = Chan TrackerMsg - -newTracker :: IO MsgChannel -newTracker = newChan - -runTracker :: MsgChannel -> FS.MsgChannel -> ByteString -> PortNumber - -> String -> [String] -> Integer -> IO () -runTracker msgChannel fsChan infohash port peerId announceList sz = do - let fn = getTrackerLoopFn turl - ps <- newEmptyMVar - _ <- forkIO $ fn turl port peerId infohash fsChan (initialTState ps) - _ <- runStateT (msgHandler msgChannel) (initialTState ps) - return () - where getTrackerLoopFn turl' = - case getTrackerType turl' of - Http -> HT.trackerLoop - Udp -> UT.trackerLoop - _ -> error "Tracker Protocol unimplemented" - initialTState ps' = TState { currentState = None - , connectedPeers = ps' - , left = sz } - turl = head announceList - -getTrackerType :: String -> TrackerProtocol -getTrackerType url | "http://" `isPrefixOf` url = Http - | "udp://" `isPrefixOf` url = Udp - | otherwise = UnknownProtocol - - -msgHandler :: MsgChannel -> StateT TState IO () -msgHandler c = forever $ do - st <- get - peers <- liftIO $ readMVar (connectedPeers st) - msg <- liftIO recvMsg - liftIO $ sendResponse msg peers - where - recvMsg = readChan c - sendResponse msg peers = - case msg of - GetConnectedPeersMsg var -> - putMVar var peers - _ -> - putStrLn "Unhandled Tracker Msg" - -getConnectedPeers :: MsgChannel -> IO [Peer] -getConnectedPeers c = do - v <- newEmptyMVar - writeChan c (GetConnectedPeersMsg v) - readMVar v diff --git a/src/FuncTorrent/Tracker/Http.hs b/src/FuncTorrent/Tracker/Http.hs deleted file mode 100644 index 13395cc..0000000 --- a/src/FuncTorrent/Tracker/Http.hs +++ /dev/null @@ -1,113 +0,0 @@ -{- - - Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan - - - - This file is part of FuncTorrent. - - - - FuncTorrent 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. - - - - FuncTorrent 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 FuncTorrent; if not, see - -} - -{-# LANGUAGE OverloadedStrings #-} - -module FuncTorrent.Tracker.Http - (trackerLoop - ) where - -import Prelude hiding (lookup) - -import Control.Concurrent (threadDelay) -import Control.Concurrent.MVar (readMVar, putMVar, isEmptyMVar, swapMVar) -import Control.Monad (forever, void) -import qualified Data.ByteString.Base16 as B16 (encode) -import Data.ByteString (ByteString) -import Data.ByteString.Char8 as BC (pack, unpack) -import Data.Char (chr) -import Data.Map as M (lookup) -import Network (PortNumber) -import Network.HTTP.Base (urlEncode) - -import qualified FuncTorrent.Bencode as Benc -import FuncTorrent.Bencode (BVal(..)) -import qualified FuncTorrent.FileSystem as FS (MsgChannel, Stats(..), getStats) -import FuncTorrent.Network (sendGetRequest) -import FuncTorrent.PeerMsgs (makePeer) -import FuncTorrent.Utils (splitN, IP, Port) -import FuncTorrent.Tracker.Types(TState(..), HttpTrackerResponse(..)) - - ---- | URL encode hash as per RFC1738 ---- TODO: Add tests ---- REVIEW: Why is this not written in terms of `Network.HTTP.Base.urlEncode` or ---- equivalent library function? -urlEncodeHash :: ByteString -> String -urlEncodeHash bs = concatMap (encode' . unpack) (splitN 2 bs) - where encode' b@[c1, c2] = let c = chr (read ("0x" ++ b)) - in escape c c1 c2 - encode' _ = "" - escape i c1 c2 | i `elem` nonSpecialChars = [i] - | otherwise = "%" ++ [c1] ++ [c2] - - nonSpecialChars = ['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ "-_.~" - --- | Make arguments that should be posted to tracker. --- This is a separate pure function for testability. -mkArgs :: PortNumber -> String -> Integer -> Integer -> Integer -> ByteString -> [(String, ByteString)] -mkArgs port peer_id up down left' infoHash = - [("info_hash", pack . urlEncodeHash . B16.encode $ infoHash), - ("peer_id", pack . urlEncode $ peer_id), - ("port", pack $ show port), - ("uploaded", pack $ show up), - ("downloaded", pack $ show down), - ("left", pack $ show left'), - ("compact", "1"), - ("event", "started")] - -trackerLoop :: String -> PortNumber -> String -> ByteString -> FS.MsgChannel -> TState -> IO () -trackerLoop url sport peerId infohash fschan tstate = forever $ do - st <- readMVar <$> FS.getStats fschan - up <- fmap FS.bytesRead st - down <- fmap FS.bytesWritten st - resp <- sendGetRequest url $ mkArgs sport peerId up down (left tstate) infohash - case Benc.decode resp of - Left e -> - return () -- $ pack (show e) - Right trackerInfo -> - case parseTrackerResponse trackerInfo of - Left e -> return () - Right tresp -> do - ps <- isEmptyMVar $ connectedPeers tstate - if ps - then - putMVar (connectedPeers tstate) (peers tresp) - else - void $ swapMVar (connectedPeers tstate) (peers tresp) - threadDelay $ fromIntegral (interval tresp) - -parseTrackerResponse :: BVal -> Either ByteString HttpTrackerResponse -parseTrackerResponse resp = - case lookup "failure reason" body of - Just (Bstr err) -> Left err - Just _ -> Left "Unknown failure" - Nothing -> - let (Just (Bint i)) = lookup "interval" body - (Just (Bstr peersBS)) = lookup "peers" body - pl = map makePeer (splitN 6 peersBS) - in Right HttpTrackerResponse { - interval = i - , peers = pl - , complete = Nothing - , incomplete = Nothing - } - where - (Bdict body) = resp - diff --git a/src/FuncTorrent/Tracker/Types.hs b/src/FuncTorrent/Tracker/Types.hs deleted file mode 100644 index 1c47d31..0000000 --- a/src/FuncTorrent/Tracker/Types.hs +++ /dev/null @@ -1,69 +0,0 @@ -{- - - Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan - - - - This file is part of FuncTorrent. - - - - FuncTorrent 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. - - - - FuncTorrent 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 FuncTorrent; if not, see - -} - -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE DuplicateRecordFields #-} -module FuncTorrent.Tracker.Types - ( TrackerProtocol(..) - , HttpTrackerResponse(..) - , UdpTrackerResponse(..) - , TrackerEventState(..) - , TState(..) - , TrackerMsg(..) - ) where - -import Data.ByteString (ByteString) -import Data.Word (Word32) -import Control.Concurrent.MVar (MVar) - -import FuncTorrent.PeerMsgs (Peer) - -data TrackerProtocol = Http - | Udp - | UnknownProtocol - deriving (Show) - -data TrackerEventState = None - | Started - | Completed - | Stopped - deriving (Show, Eq) - -data TrackerMsg = GetStatusMsg TrackerEventState - | GetConnectedPeersMsg (MVar [Peer]) - -data TState = TState { left :: Integer - , currentState :: TrackerEventState - , connectedPeers :: MVar [Peer] - } - --- | Tracker response -data HttpTrackerResponse = HttpTrackerResponse { - interval :: Integer - , peers :: [Peer] - , complete :: Maybe Integer - , incomplete :: Maybe Integer - } deriving (Show, Eq) - -data UdpTrackerResponse = UdpTrackerResponse { - leechers :: Word32 - , seeders :: Word32 - , interval :: Word32 - , peers :: [Peer] - } deriving (Show) diff --git a/src/FuncTorrent/Tracker/Udp.hs b/src/FuncTorrent/Tracker/Udp.hs deleted file mode 100644 index de99ce2..0000000 --- a/src/FuncTorrent/Tracker/Udp.hs +++ /dev/null @@ -1,232 +0,0 @@ -{- - - Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan - - - - This file is part of FuncTorrent. - - - - FuncTorrent 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. - - - - FuncTorrent 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 FuncTorrent; if not, see - -} - -{-# LANGUAGE OverloadedStrings #-} -module FuncTorrent.Tracker.Udp - (trackerLoop - ) where - -import Control.Applicative (liftA2) -import Control.Monad (forever, void) -import Control.Concurrent (threadDelay) -import Control.Concurrent.MVar (readMVar, putMVar, isEmptyMVar, swapMVar) -import Control.Monad.Reader (ReaderT, runReaderT, ask, liftIO) -import Data.Binary (Binary(..), encode, decode) -import Data.Binary.Get (Get, isEmpty, getWord32be, getWord64be, getByteString) -import Data.Binary.Put (putWord16be, putWord64be, putWord32be, putByteString) -import Data.ByteString (ByteString) -import qualified Data.ByteString.Char8 as BC -import Data.ByteString.Lazy (fromStrict, toStrict) -import Data.Word (Word16, Word32, Word64) -import Network (PortNumber) -import Network.Socket (Socket, Family( AF_INET ), SocketType( Datagram ), defaultProtocol, SockAddr(..), socket, close, getAddrInfo, addrAddress, SockAddr(..)) -import Network.Socket.ByteString (sendTo, recvFrom) -import System.Random (randomIO) -import System.Timeout (timeout) - -import FuncTorrent.PeerMsgs (Peer(..)) -import FuncTorrent.Tracker.Types (TrackerEventState(..), TState(..), UdpTrackerResponse(..)) -import FuncTorrent.Utils (Port, toIP, toPort, getHostname, getPort) -import qualified FuncTorrent.FileSystem as FS (MsgChannel, Stats(..), getStats) - --- UDP tracker: http://bittorrent.org/beps/bep_0015.html -data Action = Connect - | Announce - | Scrape - deriving (Show, Eq) - -data UDPRequest = ConnectReq Word32 - | AnnounceReq Word64 Word32 ByteString String Word64 Word64 Word64 TrackerEventState Word16 - | ScrapeReq Integer Integer ByteString - deriving (Show, Eq) - -data UDPResponse = ConnectResp Word32 Word64 -- transaction_id connection_id - | AnnounceResp Word32 Word32 Word32 Word32 [Peer] -- transaction_id interval leechers seeders [(ip, port)] - | ScrapeResp Integer Integer Integer Integer - | ErrorResp Integer String - deriving (Show, Eq) - -data UDPTrackerHandle = UDPTrackerHandle { sock :: Socket - , addr :: SockAddr - } - -actionToInteger :: Action -> Integer -actionToInteger Connect = 0 -actionToInteger Announce = 1 -actionToInteger Scrape = 2 - -eventToInteger :: TrackerEventState -> Integer -eventToInteger None = 0 -eventToInteger Completed = 1 -eventToInteger Started = 2 -eventToInteger Stopped = 3 - -instance Binary UDPRequest where - put (ConnectReq transId) = do - putWord64be 0x41727101980 - putWord32be $ fromIntegral (actionToInteger Connect) - putWord32be (fromIntegral transId) - put (AnnounceReq connId transId infohash peerId down left' up event port) = do - putWord64be $ fromIntegral connId - putWord32be $ fromIntegral (actionToInteger Announce) - putWord32be $ fromIntegral transId - putByteString infohash - putByteString (BC.pack peerId) - putWord64be (fromIntegral down) - putWord64be (fromIntegral left') - putWord64be (fromIntegral up) - putWord32be $ fromIntegral (eventToInteger event) - putWord32be 0 - putWord32be 0 - putWord32be 10 - putWord16be $ fromIntegral port - put ScrapeReq {} = undefined - get = undefined - -instance Binary UDPResponse where - put = undefined - get = do - a <- getWord32be -- action - case a of - 0 -> liftA2 ConnectResp (fromIntegral <$> getWord32be) (fromIntegral <$> getWord64be) - 1 -> do - tid' <- fromIntegral <$> getWord32be - interval' <- fromIntegral <$> getWord32be - l <- getWord32be -- leechers - s <- getWord32be -- seeders - ipportpairs <- getIPPortPairs -- [(ip, port)] - return $ AnnounceResp tid' interval' l s ipportpairs - 2 -> do - tid' <- fromIntegral <$> getWord32be - _ <- getWord32be - _ <- getWord32be - _ <- getWord32be - return $ ScrapeResp tid' 0 0 0 - 3 -> do -- error response - tid' <- fromIntegral <$> getWord32be - bs <- getByteString 4 - return $ ErrorResp tid' $ BC.unpack bs - _ -> error ("unknown response action type: " ++ show a) - -sendRequest :: UDPTrackerHandle -> ByteString -> IO () -sendRequest h req = do - n <- sendTo (sock h) req (addr h) - -- sanity check with n? - return () - -recvResponse :: UDPTrackerHandle -> IO UDPResponse -recvResponse h = do - (bs, saddr) <- recvFrom (sock h) (16*1024) - return $ decode $ fromStrict bs - -connectRequest :: ReaderT UDPTrackerHandle IO Word32 -connectRequest = do - h <- ask - tidi <- liftIO randomIO - let pkt = encode $ ConnectReq tidi - liftIO $ sendRequest h (toStrict pkt) - return tidi - -connectResponse :: Word32 -> ReaderT UDPTrackerHandle IO Word64 -connectResponse tid = do - h <- ask - resp <- liftIO $ recvResponse h - -- check if nbytes is at least 16 bytes long - case resp of - (ConnectResp tidr cid) -> - if tidr == tid - then do - liftIO $ putStrLn "connect succeeded" - return cid - else - return 0 - _ -> return 0 - -announceRequest :: Word64 -> ByteString -> String -> Word64 -> Word64 -> Word64 -> Word16 -> ReaderT UDPTrackerHandle IO Word32 -announceRequest cid infohash peerId up down left' port = do - h <- ask - tidi <- liftIO randomIO - let pkt = encode $ AnnounceReq cid tidi infohash peerId down left' up None port - liftIO $ sendRequest h (toStrict pkt) - return tidi - -announceResponse :: Word32 -> ReaderT UDPTrackerHandle IO UdpTrackerResponse -announceResponse tid = do - h <- ask - resp <- liftIO $ recvResponse h - case resp of - (AnnounceResp tidr interval' ss ls xs) -> - if tidr == tid - then do - liftIO $ putStrLn "announce succeeded" - return $ UdpTrackerResponse ls ss interval' xs - else - return $ UdpTrackerResponse 0 0 0 [] - _ -> return $ UdpTrackerResponse 0 0 0 [] - -getIPPortPairs :: Get [Peer] -getIPPortPairs = do - empty <- isEmpty - if empty - then return [] - else do - ip <- toIP <$> getByteString 4 - port <- toPort <$> getByteString 2 - ipportpairs <- getIPPortPairs - return $ Peer ip port : ipportpairs - -startSession :: String -> Port -> IO UDPTrackerHandle -startSession host port = do - s <- socket AF_INET Datagram defaultProtocol - addrinfos <- getAddrInfo Nothing (Just host) (Just (show port)) - let (SockAddrInet p ip) = addrAddress $ head addrinfos - putStrLn "connected to tracker" - return UDPTrackerHandle { sock = s - , addr = SockAddrInet (fromIntegral port) ip } - -closeSession :: UDPTrackerHandle -> IO () -closeSession (UDPTrackerHandle s _) = close s - -trackerLoop :: String -> PortNumber -> String -> ByteString -> FS.MsgChannel -> TState -> IO () -trackerLoop url sport peerId infohash fschan tstate = forever $ do - st <- readMVar <$> FS.getStats fschan - up <- fmap FS.bytesRead st - down <- fmap FS.bytesWritten st - handle <- startSession host port - stats <- timeout (15*oneSec) $ worker handle up down - case stats of - Nothing -> closeSession handle - Just stats' -> do - ps <- isEmptyMVar $ connectedPeers tstate - if ps - then - putMVar (connectedPeers tstate) (peers stats') - else - void $ swapMVar (connectedPeers tstate) (peers stats') - threadDelay $ fromIntegral (interval stats') * oneSec - return () - where - oneSec = 1000000 - port = getPort url - host = getHostname url - worker handle up down = flip runReaderT handle $ do - t1 <- connectRequest - cid <- connectResponse t1 - t2 <- announceRequest cid infohash peerId (fromIntegral up) (fromIntegral down) (fromIntegral (left tstate)) (fromIntegral sport) - announceResponse t2 diff --git a/src/FuncTorrent/Utils.hs b/src/FuncTorrent/Utils.hs deleted file mode 100644 index 30fd160..0000000 --- a/src/FuncTorrent/Utils.hs +++ /dev/null @@ -1,98 +0,0 @@ -{- - - Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan - - - - This file is part of FuncTorrent. - - - - FuncTorrent 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. - - - - FuncTorrent 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 FuncTorrent; if not, see - -} - -module FuncTorrent.Utils - ( createDummyFile - , writeFileAtOffset - , readFileAtOffset - , splitNum - , splitN - , verifyHash - , IP - , Port - , toIP - , toPort - , getHostname - , getPort - ) - where - -import Prelude hiding (writeFile, take) - -import qualified Crypto.Hash.SHA1 as SHA1 (hash) -import Control.Exception.Base (IOException, try) -import Data.ByteString (ByteString, writeFile, hPut, hGet, take) -import qualified Data.ByteString.Base16 as B16 (encode) -import qualified Data.ByteString.Char8 as BC -import Data.List (intercalate) -import System.IO (Handle, hSeek, SeekMode(..)) -import System.Directory (doesFileExist) - -type IP = String -type Port = Integer - -splitN :: Int -> BC.ByteString -> [BC.ByteString] -splitN n bs | BC.null bs = [] - | otherwise = BC.take n bs : splitN n (BC.drop n bs) - -splitNum :: Integer -> Integer -> [Integer] -splitNum n d | n == 0 = [] - | n < d = [n] - | otherwise = d : splitNum (n - d) d - -createDummyFile :: FilePath -> Int -> IO (Either IOException ()) -createDummyFile path size = do - dfe <- doesFileExist path - if not dfe - then - try $ writeFile path (BC.replicate size '\0') - else - return $ Right () - --- write into a file at a specific offet -writeFileAtOffset :: Handle -> Integer -> ByteString -> IO () -writeFileAtOffset h offset block = do - hSeek h AbsoluteSeek offset - hPut h block - -readFileAtOffset :: Handle -> Integer -> Integer -> IO ByteString -readFileAtOffset h offset len = do - hSeek h AbsoluteSeek offset - hGet h (fromInteger len) - -verifyHash :: ByteString -> ByteString -> Bool -verifyHash bs pieceHash = - take 20 (SHA1.hash bs) == pieceHash - -toPort :: ByteString -> Port -toPort = read . ("0x" ++) . BC.unpack . B16.encode - -toIP :: ByteString -> IP -toIP = Data.List.intercalate "." . - map (show . toInt . ("0x" ++) . BC.unpack) . - splitN 2 . B16.encode - -toInt :: String -> Integer -toInt = read - -getHostname :: String -> String -getHostname url = takeWhile (/= ':') $ drop 2 $ dropWhile (/= '/') url - -getPort :: String -> Port -getPort url = read $ takeWhile (/= '/') $ drop 1 $ dropWhile (/= ':') $ drop 2 $ dropWhile (/= '/') url diff --git a/src/main/Main.hs b/src/main/Main.hs deleted file mode 100644 index 71c9841..0000000 --- a/src/main/Main.hs +++ /dev/null @@ -1,112 +0,0 @@ -{-# LANGUAGE OverloadedStrings #-} -{- -Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan - -This file is part of FuncTorrent. - -FuncTorrent 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. - -FuncTorrent 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 FuncTorrent; if not, see --} - -module Main where - -import Prelude hiding (log, length, readFile, getContents) - -import Control.Concurrent (forkIO, killThread) -import Control.Concurrent.MVar (readMVar) -import Data.ByteString.Char8 (ByteString, getContents, readFile) -import qualified FuncTorrent.FileSystem as FS (createMsgChannel, pieceMapFromFile, run) -import FuncTorrent.Logger (initLogger, logMessage, logStop) -import FuncTorrent.Metainfo (Info(..), Metainfo(..), torrentToMetainfo) -import FuncTorrent.Peer (handlePeerMsgs) -import FuncTorrent.PieceManager (initPieceMap) -import qualified FuncTorrent.Server as Server -import FuncTorrent.Tracker (runTracker, getConnectedPeers, newTracker) -import Network (PortID (PortNumber)) -import System.IO (withFile, IOMode (ReadWriteMode)) -import System.Directory (doesFileExist) -import System.Environment (getArgs) -import System.Exit (exitSuccess) -import System.Random (getStdGen, randomRs) - -logError :: String -> (String -> IO ()) -> IO () -logError e logMsg = logMsg $ "parse error: \n" ++ e - -exit :: IO ByteString -exit = exitSuccess - -usage :: IO () -usage = putStrLn "usage: functorrent torrent-file" - -parse :: [String] -> IO ByteString -parse [] = getContents -parse [a] = do - fileExist <- doesFileExist a - if fileExist - then readFile a - else error "file does not exist" -parse _ = exit - --- peer id is exactly 20 bytes long. --- peer id starts with '-', followed by 2 char client id' --- followed by 4 ascii digits for version number, followed by --- a '-'. Rest are random digits to fill the 20 bytes. -mkPeerID :: IO String -mkPeerID = do - stdgen <- getStdGen - let digits = randomRs (0, 9) stdgen :: [Integer] - return $ "-HS9001-" ++ (concatMap show $ take (20 - 8) digits) - -main :: IO () -main = do - args <- getArgs - logR <- initLogger - peerId <- mkPeerID - let log = logMessage logR - log "Starting up functorrent" - log $ "Parsing arguments " ++ concat args - torrentStr <- parse args - case torrentToMetainfo torrentStr of - Left e -> logError e log - Right m -> do - -- if we had downloaded the file before (partly or completely) - -- then we should check the current directory for the existence - -- of the file and then update the map of each piece' availability. - -- This can be done by reading each piece and verifying the checksum. - -- If the checksum does not match, we don't have that piece. - let filePath = name (info m) -- really this is just the file name, not file path - fileLen = lengthInBytes (info m) - pieceHash = pieces (info m) - pLen = pieceLength (info m) - infohash = infoHash m - defaultPieceMap = initPieceMap pieceHash fileLen pLen - log $ "create FS msg channel" - fsMsgChannel <- FS.createMsgChannel - log $ "Downloading file : " ++ filePath - pieceMap <- FS.pieceMapFromFile filePath fileLen defaultPieceMap - log $ "start filesystem manager thread" - fsTid <- forkIO $ withFile filePath ReadWriteMode (FS.run pieceMap fsMsgChannel) - log $ "starting server" - (serverSock, (PortNumber portnum)) <- Server.start - log $ "server started on " ++ show portnum - log "Trying to fetch peers" - _ <- forkIO $ Server.run serverSock peerId m pieceMap fsMsgChannel - log $ "Trackers: " ++ head (announceList m) - trackerMsgChan <- newTracker - _ <- forkIO $ runTracker trackerMsgChan fsMsgChannel infohash portnum peerId (announceList m) fileLen - ps <- getConnectedPeers trackerMsgChan - log $ "Peers List : " ++ (show ps) - let p1 = head ps - handlePeerMsgs p1 peerId m pieceMap True fsMsgChannel - logStop logR - killThread fsTid diff --git a/stack.yaml b/stack.yaml deleted file mode 100644 index 5b69a9a..0000000 --- a/stack.yaml +++ /dev/null @@ -1,37 +0,0 @@ -# For more information, see: https://github.com/commercialhaskell/stack/blob/release/doc/yaml_configuration.md - -# Override default flag values for local packages and extra-deps -flags: {} - -# Local packages, usually specified by relative directory name -packages: - -# Local packages, usually specified by relative directory name -- '.' - -# Packages to be pulled from upstream that are not in the resolver (e.g., acme-missiles-0.3) -extra-deps: [] - -# Specifies the GHC version and set of packages available (e.g., lts-3.5, nightly-2015-09-21, ghc-7.10.2) -resolver: nightly-2016-06-19 - -rebuild-ghc-options: true -ghc-options: - # All packages - "*": -Wall # -fwarn-incomplete-uni-patterns -fwarn-incomplete-record-updates -fwarn-monomorphism-restriction -fwarn-auto-orphans -fwarn-implicit-prelude -fwarn-missing-local-sigs -fwarn-missing-exported-sigs -fwarn-missing-import-lists -fwarn-identities - some-package: -DSOME_CPP_FLAG - -# Control whether we use the GHC we find on the path -# system-ghc: true - -# Require a specific version of stack, using version ranges -# require-stack-version: -any # Default -# require-stack-version: >= 1.0.0 - -# Override the architecture used by stack, especially useful on Windows -# arch: i386 -# arch: x86_64 - -# Extra directories used by stack for building -# extra-include-dirs: [/path/to/dir] -# extra-lib-dirs: [/path/to/dir] diff --git a/test/BencodeTests.hs b/test/BencodeTests.hs deleted file mode 100644 index c83e9cc..0000000 --- a/test/BencodeTests.hs +++ /dev/null @@ -1,17 +0,0 @@ -module BencodeTests (tests) where - -import FuncTorrent.Bencode (encode, decode, BVal(..)) - -import Test.Tasty (TestTree, testGroup) -import Test.Tasty.QuickCheck (testProperty) - -propEncodeDecode :: BVal -> Bool -propEncodeDecode bval = let encoded = encode bval - decoded = decode encoded - in Right bval == decoded - -qcTests :: TestTree -qcTests = testGroup "QuickCheck tests" [ testProperty "encode/decode" propEncodeDecode ] - -tests :: TestTree -tests = testGroup "Tests" [qcTests] diff --git a/test/Test.hs b/test/Test.hs deleted file mode 100644 index 71b9f1c..0000000 --- a/test/Test.hs +++ /dev/null @@ -1,101 +0,0 @@ -{-# LANGUAGE OverloadedStrings #-} -module Main where - -import Prelude hiding (readFile) - -import Data.ByteString (ByteString, readFile) -import Data.Map.Strict (fromList) - -import Test.Tasty (TestTree, testGroup, defaultMain) -import Test.Tasty.HUnit (testCase, (@?=)) - -import FuncTorrent.Bencode (encode, decode, BVal(..)) -import FuncTorrent.Metainfo (Info(..), Metainfo(..), mkMetaInfo) -import FuncTorrent.Peer (Peer(..)) -import FuncTorrent.Tracker - -import qualified BencodeTests - --- Parsed .torrent file -file :: BVal -file = Bdict (fromList [ - ("announce",Bstr "http://9.rarbg.com:2710/announce"), - ("comment",Bstr "hello world"), - ("created by",Bstr "Jaseem Abid"), - ("creation date",Bint 1428717851), - ("encoding",Bstr "UTF-8"), - ("info",Bdict (fromList [ - ("length",Bint 12), - ("name",Bstr "hello.txt"), - ("piece length",Bint 32768), - ("pieces",Bstr "\"Ycc\179\222@\176o\152\US\184]\130\&1.\140\SO\213\DC1"), - ("private",Bint 0)]))]) - -hello :: Metainfo -hello = Metainfo { - info = Info { - pieceLength = 32768, - pieces = "\"Ycc\179\222@\176o\152\US\184]\130\&1.\140\SO\213\DC1", - private = Nothing, - name = "hello.txt", - lengthInBytes = 12, - md5sum = Nothing - }, - announceList = ["http://9.rarbg.com:2710/announce"], - creationDate = Just 1428717851, - comment = Just "hello world", - createdBy = Just "Jaseem Abid", - encoding = Just "UTF-8", - infoHash = "\205CX(;\163 expected @?= file - Left _ -> error "Failed parsing test file" - - -testMkMetaInfo :: TestTree -testMkMetaInfo = testCase "Should mkInfo valid torrent files" $ do - str <- readFile "./data/hello.txt.torrent" - case decode str of - Right expected -> mkMetaInfo expected @?= Just hello - Left _ -> error "Failed parsing test file" - -testResponse1 :: TestTree -testResponse1 = testCase "Should parse valid tracker response" $ do - str <- readFile "./data/debian-7.8.0-amd64-CD-1.iso.cache" - case decode str of - Right bval -> expectation @?= mkTrackerResponse bval - Left _ -> error "Failed parsing test file" - where - expectation :: Either a TrackerResponse - expectation = Right TrackerResponse { - interval = Just 900, - peers = [Peer "" "85.25.201.101" 51413, Peer "" "37.59.28.236" 22222, Peer "" "76.21.149.43" 51866, Peer "" "31.183.33.205" 43467, Peer "" "213.210.120.86" 27480, Peer "" "213.239.216.205" 6914, Peer "" "91.192.163.152" 11834, Peer "" "62.210.240.65" 6999, Peer "" "84.250.103.161" 6949, Peer "" "88.195.241.192" 51413, Peer "" "88.165.61.223" 6881, Peer "" "86.157.234.243" 59583, Peer "" "213.41.137.242" 51413, Peer "" "91.10.84.195" 46941, Peer "" "64.56.249.183" 7023, Peer "" "202.62.16.71" 59929, Peer "" "31.43.126.122" 57816, Peer "" "68.169.133.72" 50222, Peer "" "223.135.97.177" 58813, Peer "" "5.166.93.118" 64459, Peer "" "200.148.109.141" 51413, Peer "" "109.226.236.160" 44444, Peer "" "78.58.139.154" 22818, Peer "" "188.244.47.186" 39643, Peer "" "203.86.204.111" 52411, Peer "" "80.110.40.98" 6918, Peer "" "68.187.142.217" 58352, Peer "" "71.115.139.180" 63065, Peer "" "70.169.35.173" 51413, Peer "" "185.3.135.186" 10889, Peer "" "88.198.224.202" 51413, Peer "" "183.157.65.217" 9179, Peer "" "87.251.189.150" 46680, Peer "" "87.114.202.174" 12393, Peer "" "93.58.5.16" 51411, Peer "" "89.102.9.69" 10044, Peer "" "94.159.19.222" 15783, Peer "" "95.28.49.176" 58794, Peer "" "217.114.58.135" 6881, Peer "" "79.141.162.38" 35806, Peer "" "136.169.50.72" 54927, Peer "" "187.67.188.151" 51413, Peer "" "79.111.218.50" 53636, Peer "" "62.75.137.129" 51413, Peer "" "14.204.20.156" 11600, Peer "" "79.141.162.34" 24531, Peer "" "82.144.192.7" 63208, Peer "" "212.34.231.10" 20684, Peer "" "95.225.246.221" 51413, Peer "" "124.41.237.102" 24874], - complete = Nothing, - incomplete = Nothing - } - -testResponse2 :: TestTree -testResponse2 = testCase "Should parse invalid tracker response" $ do - str <- readFile "./data/debian-7.8.0-amd64-CD-1.iso.error" - case decode str of - Right bval -> expectation @?= mkTrackerResponse bval - Left _ -> error "Failed parsing test file" - where - expectation :: Either ByteString a - expectation = Left "torrent not found" - - -unitTests :: TestTree -unitTests = testGroup "Unit tests" [testFile, testMkMetaInfo, testResponse1, - testResponse2] - -tests :: TestTree -tests = testGroup "Tests" [unitTests, BencodeTests.tests] - -main :: IO () -main = defaultMain tests