├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── Setup.hs ├── data ├── debian-7.8.0-amd64-CD-1.iso.cache ├── debian-7.8.0-amd64-CD-1.iso.error ├── debian-7.8.0-amd64-CD-1.iso.torrent ├── hello.txt ├── hello.txt.cache ├── hello.txt.torrent ├── ubuntu-14.10-desktop-amd64.iso.torrent └── ubuntu-14.10-desktop-i386.iso.torrent ├── default.nix ├── doc └── Concurrency.org ├── functorrent.cabal ├── shell.nix ├── src ├── FuncTorrent.hs ├── FuncTorrent │ ├── Bencode.hs │ ├── ControlThread.hs │ ├── Core.hs │ ├── Logger.hs │ ├── Metainfo.hs │ ├── Peer.hs │ ├── Tracker.hs │ ├── Utils.hs │ └── Writer.hs └── Main.hs ├── stack.yaml └── test ├── BencodeTests.hs └── Test.hs /.gitignore: -------------------------------------------------------------------------------- 1 | # Build files 2 | *.chi 3 | *.chi.h 4 | *.hi 5 | *.o 6 | *.p_hi 7 | *.prof 8 | *.tix 9 | .cabal-sandbox/ 10 | .stack-work/ 11 | .hpc/ 12 | cabal-dev/ 13 | cabal.sandbox.config 14 | dist 15 | dist-sandbox 16 | 17 | /Cabal/dist/ 18 | /Cabal/tests/Setup 19 | /Cabal/Setup 20 | 21 | /cabal-install/dist/ 22 | /cabal-install/Setup 23 | 24 | # editor temp files 25 | 26 | *# 27 | .#* 28 | *~ 29 | .*.swp 30 | 31 | # GHC build 32 | 33 | Cabal/GNUmakefile 34 | Cabal/dist-boot/ 35 | Cabal/dist-install/ 36 | Cabal/ghc.mk 37 | 38 | # TAGS files 39 | 40 | TAGS 41 | tags 42 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: haskell 2 | ghc: 7.8 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # A bittorrent client. 2 | 3 | [![Join the chat at https://gitter.im/vu3rdd/functorrent](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/vu3rdd/functorrent?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) 4 | 5 | [![Build Status](https://travis-ci.org/vu3rdd/functorrent.svg?branch=master)](https://travis-ci.org/vu3rdd/functorrent) 6 | 7 | ## Building 8 | 9 | Functorrent can be build with [Cabal](https://www.haskell.org/cabal/) sandbox or 10 | [Nix](https://nixos.org/nix/). 11 | 12 | ### Cabal sandbox 13 | 14 | Sandboxes give you per project independent containers, just like Python's 15 | virtualenv. 16 | 17 | 18 | $ git clone https://github.com/vu3rdd/functorrent && cd functorrent 19 | $ cabal sandbox init 20 | $ cabal update 21 | $ cabal install --only-dependencies --enable-tests 22 | $ cabal build # binaries in ./dist/built/functorrent/* 23 | 24 | ### Building with Nix 25 | 26 | ``$ nix-shell``` at the root of the source code repo should drop you into a 27 | shell which has all the package dependencies installed. 28 | 29 | 30 | $ nix-shell --pure 31 | [...] 32 | [nix-shell] $ cabal configure && cabal build 33 | 34 | ## Goals 35 | 36 | - [Optimized for Fun](http://www.slideshare.net/autang/ofun-optimizing-for-fun). 37 | (should have called it "funtorrent") 38 | - Become more profient with Haskell. 39 | - Implement something non-trivial with Haskell (crypto, file operations, network 40 | operations, concurrency, bit twiddling, DHT). 41 | - Follow the spec ([official spec](http://bittorrent.org/beps/bep_0003.html), [unofficial spec](https://wiki.theory.org/BitTorrentSpecification)) 42 | - Easy for newbies like me to read and understand along side the spec. 43 | - doctest and quickcheck tests. 44 | - Follow Haskell Style Guide - https://github.com/tibbe/haskell-style-guide/blob/master/haskell-style.md 45 | 46 | ## Current Status 47 | 48 | - can decode torrent files (bencoding) 49 | - talk to the tracker and get the peer list 50 | - the `main' program takes a torrent file (in the local file system) as input and 51 | prints the {ip,port} for each peer, after talking to the tracker. 52 | - can handshake with the peer. 53 | - peer wire protocol (in progress) 54 | 55 | ## TODO 56 | 57 | * Test suite. 58 | * Peer protocol (in progress). 59 | * Get the file download working in the simplest possible way. 60 | * Concurrency (threads per peer) 61 | * other advanced features of Bit Torrent (like DHT). 62 | -------------------------------------------------------------------------------- /Setup.hs: -------------------------------------------------------------------------------- 1 | import Distribution.Simple 2 | main = defaultMain 3 | -------------------------------------------------------------------------------- /data/debian-7.8.0-amd64-CD-1.iso.cache: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bangalore-haskell-user-group/functorrent/c92357b85b5e585f80bb4b798e10a81f40aba26f/data/debian-7.8.0-amd64-CD-1.iso.cache -------------------------------------------------------------------------------- /data/debian-7.8.0-amd64-CD-1.iso.error: -------------------------------------------------------------------------------- 1 | d14:failure reason17:torrent not founde -------------------------------------------------------------------------------- /data/debian-7.8.0-amd64-CD-1.iso.torrent: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bangalore-haskell-user-group/functorrent/c92357b85b5e585f80bb4b798e10a81f40aba26f/data/debian-7.8.0-amd64-CD-1.iso.torrent -------------------------------------------------------------------------------- /data/hello.txt: -------------------------------------------------------------------------------- 1 | hello world 2 | -------------------------------------------------------------------------------- /data/hello.txt.cache: -------------------------------------------------------------------------------- 1 | d8:completei0e10:incompletei0e8:intervali130e12:min intervali130e5:peers0:e 2 | -------------------------------------------------------------------------------- /data/hello.txt.torrent: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bangalore-haskell-user-group/functorrent/c92357b85b5e585f80bb4b798e10a81f40aba26f/data/hello.txt.torrent -------------------------------------------------------------------------------- /data/ubuntu-14.10-desktop-amd64.iso.torrent: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bangalore-haskell-user-group/functorrent/c92357b85b5e585f80bb4b798e10a81f40aba26f/data/ubuntu-14.10-desktop-amd64.iso.torrent -------------------------------------------------------------------------------- /data/ubuntu-14.10-desktop-i386.iso.torrent: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bangalore-haskell-user-group/functorrent/c92357b85b5e585f80bb4b798e10a81f40aba26f/data/ubuntu-14.10-desktop-i386.iso.torrent -------------------------------------------------------------------------------- /default.nix: -------------------------------------------------------------------------------- 1 | # This file was auto-generated by cabal2nix. Please do NOT edit manually! 2 | 3 | { cabal, base16Bytestring, binary, cryptohash, doctest, hlint, HTTP 4 | , networkUri, parsec, QuickCheck, tasty, tastyHunit 5 | , tastyQuickcheck, testFrameworkQuickcheck2 6 | }: 7 | 8 | cabal.mkDerivation (self: { 9 | pname = "functorrent"; 10 | version = "0.1.0.0"; 11 | src = ./.; 12 | isLibrary = true; 13 | isExecutable = true; 14 | buildDepends = [ 15 | base16Bytestring binary cryptohash HTTP networkUri parsec 16 | QuickCheck tasty tastyHunit 17 | ]; 18 | testDepends = [ 19 | doctest hlint QuickCheck tasty tastyHunit tastyQuickcheck 20 | testFrameworkQuickcheck2 21 | ]; 22 | meta = { 23 | description = "A Bit-torrent client"; 24 | license = self.stdenv.lib.licenses.gpl3; 25 | platforms = self.ghc.meta.platforms; 26 | }; 27 | }) 28 | -------------------------------------------------------------------------------- /doc/Concurrency.org: -------------------------------------------------------------------------------- 1 | * Concurrency model, v1 2 | 3 | This is a channel based approach for managing concurrency in Functorrent. 4 | 5 | The rational is that keeping state in MVars and polling for them in a loop with 6 | a sleep feels very counter intuitive. 7 | 8 | A channel based implementation is very similar to producer consumer model, 9 | message passing or Erlang's actor model. 10 | 11 | Channels are typed and can be drained in a blocking manner by a worker thread 12 | with only a few lines of code. (See [[https://github.com/bangalore-haskell-user-group/functorrent/blob/concurrency/src/FuncTorrent/Writer.hs][functorrent/Writer.hs]]) A `control thread` 13 | (CT) is spawned per torrent file. CT spawns a writer thread (WT) per file and a 14 | peer thread (PT) per peer. Peers report available blocks to control thread via 15 | the `availability` channel. Control thread can schedule block downloads taking 16 | into consideration the state of all active peers. We must be able to do some 17 | smart scheduling here, like fetching a rare piece first. Requests to fetch 18 | blocks arrive peer threads via the `reader` channel, and a download thread 19 | drains this channel and downloads a block at a time. Retrieved blocks are 20 | written to `writer` channel. Writer drains it to disk. 21 | 22 | A key advantage of the design is that a lot of the modules become stateless and 23 | safe to be killed at any time. Peer thread is an example. It gets data from a 24 | channel, writes data to another channel. A PT crash should be perfectly fine. 25 | 26 | A known issue is the inability to close channels at the moment. If the consumer 27 | dies, the producer ideally shouldn't be pushing more work in the same channel. 28 | This might lead to silent issues. 29 | -------------------------------------------------------------------------------- /functorrent.cabal: -------------------------------------------------------------------------------- 1 | -- Initial functorrent.cabal generated by cabal init. For further documentation, 2 | -- see http://haskell.org/cabal/users-guide/ 3 | 4 | name: functorrent 5 | version: 0.1.0.0 6 | synopsis: A Bit-torrent client 7 | description: A bittorrent client 8 | license: GPL-3 9 | license-file: LICENSE 10 | author: Ramakrishnan Muthukrishnan 11 | maintainer: ram@rkrishnan.org 12 | -- copyright: 13 | category: Network 14 | build-type: Simple 15 | extra-source-files: README.md 16 | cabal-version: >=1.18 17 | 18 | library 19 | exposed-modules: FuncTorrent 20 | FuncTorrent.Bencode, 21 | FuncTorrent.ControlThread, 22 | FuncTorrent.Logger, 23 | FuncTorrent.Metainfo, 24 | FuncTorrent.Peer, 25 | FuncTorrent.Tracker, 26 | FuncTorrent.Writer 27 | 28 | other-modules: FuncTorrent.Utils 29 | other-extensions: OverloadedStrings, CPP 30 | hs-source-dirs: src 31 | ghc-options: -Wall -fwarn-incomplete-patterns -fno-warn-orphans 32 | default-language: Haskell2010 33 | build-depends: base, 34 | base16-bytestring, 35 | binary, 36 | bytestring, 37 | containers, 38 | cryptohash, 39 | directory, 40 | HTTP, 41 | network, 42 | network-uri, 43 | parsec, 44 | QuickCheck, 45 | random, 46 | transformers, 47 | unix 48 | 49 | executable functorrent 50 | main-is: Main.hs 51 | other-extensions: OverloadedStrings 52 | hs-source-dirs: src 53 | ghc-options: -Wall -fwarn-incomplete-patterns -optc-Os -fno-warn-orphans 54 | default-language: Haskell2010 55 | build-depends: base, 56 | base16-bytestring, 57 | binary, 58 | bytestring, 59 | containers, 60 | cryptohash, 61 | directory, 62 | HTTP, 63 | QuickCheck, 64 | network, 65 | network-uri, 66 | parsec, 67 | random, 68 | transformers, 69 | unix 70 | 71 | test-suite functorrent-test 72 | type: exitcode-stdio-1.0 73 | default-language: Haskell2010 74 | hs-source-dirs: test 75 | main-is: Test.hs 76 | other-modules: BencodeTests 77 | build-depends: base, 78 | functorrent, 79 | bytestring, 80 | containers, 81 | directory, 82 | doctest, 83 | QuickCheck, 84 | random, 85 | tasty, 86 | tasty-hunit, 87 | QuickCheck, 88 | tasty-quickcheck, 89 | test-framework-quickcheck2 90 | -------------------------------------------------------------------------------- /shell.nix: -------------------------------------------------------------------------------- 1 | let pkgs = (import {}); 2 | haskellPackages = pkgs.recurseIntoAttrs (pkgs.haskellPackages.override { 3 | extension = self : super : 4 | let callPackage = self.callPackage; 5 | in { 6 | thisPackage = haskellPackages.callPackage (import ./default.nix) {}; 7 | };}); 8 | in pkgs.lib.overrideDerivation haskellPackages.thisPackage (old: { 9 | buildInputs = old.buildInputs ++ [ 10 | haskellPackages.cabalInstall 11 | ]; 12 | }) 13 | -------------------------------------------------------------------------------- /src/FuncTorrent.hs: -------------------------------------------------------------------------------- 1 | module FuncTorrent 2 | (BVal(..), 3 | Info(..), 4 | Metainfo(..), 5 | Peer, 6 | Tracker(..), 7 | tracker, 8 | decode, 9 | encode, 10 | handShake, 11 | initLogger, 12 | logMessage, 13 | logStop, 14 | mkInfo, 15 | mkMetaInfo, 16 | mkTrackerResponse 17 | ) where 18 | 19 | import FuncTorrent.Bencode 20 | import FuncTorrent.Logger 21 | import FuncTorrent.Metainfo 22 | import FuncTorrent.Peer 23 | import FuncTorrent.Tracker 24 | -------------------------------------------------------------------------------- /src/FuncTorrent/Bencode.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE OverloadedStrings #-} 2 | module FuncTorrent.Bencode 3 | (BVal(..) 4 | , bValToBList 5 | , bValToBytestr 6 | , bValToInfoDict 7 | , bValToInteger 8 | , bstrToString 9 | , decode 10 | , encode 11 | ) where 12 | 13 | import Prelude hiding (length, concat) 14 | 15 | import Control.Applicative ((<*)) -- This will cause a warning in 7.10. 16 | import Data.ByteString (ByteString, length, concat) 17 | import Data.ByteString.Char8 (unpack, pack) 18 | import Data.Functor ((<$>)) -- This will cause a warning in 7.10. 19 | import Data.Map.Strict (Map, fromList, toList) 20 | 21 | import Test.QuickCheck 22 | import Text.ParserCombinators.Parsec 23 | import qualified Text.Parsec.ByteString as ParsecBS 24 | 25 | data BVal = Bint Integer 26 | | Bstr ByteString 27 | | Blist [BVal] 28 | | Bdict (Map String BVal) 29 | deriving (Ord, Eq, Show) 30 | 31 | instance Arbitrary ByteString where 32 | arbitrary = pack <$> arbitrary 33 | 34 | instance Arbitrary BVal where 35 | arbitrary = sized bval 36 | where 37 | bval :: Int -> Gen BVal 38 | bval 0 = oneof [ Bint <$> arbitrary 39 | , Bstr <$> arbitrary] 40 | bval n = oneof [ Bint <$> arbitrary 41 | , Bstr <$> arbitrary 42 | , Blist <$> vectorOf n (bval (n `div` 4)) 43 | , do keys <- vectorOf n arbitrary 44 | vals <- vectorOf n (bval (n `div` 4)) 45 | return $ Bdict $ fromList $ zip keys vals ] 46 | 47 | -- getters 48 | bValToInteger :: BVal -> Maybe Integer 49 | bValToInteger (Bint x) = Just x 50 | bValToInteger _ = Nothing 51 | 52 | bValToBytestr :: BVal -> Maybe ByteString 53 | bValToBytestr (Bstr bs) = Just bs 54 | bValToBytestr _ = Nothing 55 | 56 | bValToBList :: BVal -> Maybe [BVal] 57 | bValToBList (Blist lst) = Just lst 58 | bValToBList _ = Nothing 59 | 60 | bValToInfoDict :: BVal -> Maybe (Map String BVal) 61 | bValToInfoDict (Bdict dict) = Just dict 62 | bValToInfoDict _ = Nothing 63 | 64 | bstrToString :: BVal -> Maybe String 65 | bstrToString bval = unpack <$> bValToBytestr bval 66 | 67 | -- $setup 68 | -- >>> import Data.Either 69 | 70 | -- | parse strings 71 | -- 72 | -- >>> parse bencStr "Bstr" (pack "4:spam") 73 | -- Right "spam" 74 | -- >>> parse bencStr "Bstr" (pack "0:") 75 | -- Right "" 76 | -- >>> parse bencStr "Bstr" (pack "0:hello") 77 | -- Right "" 78 | -- 79 | bencStr :: ParsecBS.Parser ByteString 80 | bencStr = do ds <- many1 digit <* char ':' 81 | s <- count (read ds) anyChar 82 | return (pack s) 83 | 84 | -- | parse integers 85 | -- 86 | -- >>> parse bencInt "Bint" (pack "i42e") 87 | -- Right 42 88 | -- >>> parse bencInt "Bint" (pack "i123e") 89 | -- Right 123 90 | -- >>> parse bencInt "Bint" (pack "i1e") 91 | -- Right 1 92 | -- >>> parse bencInt "Bint" (pack "i0e") 93 | -- Right 0 94 | -- >>> parse bencInt "Bint" (pack "i-1e") 95 | -- Right (-1) 96 | -- >>> isLeft $ parse bencInt "Bint" (pack "i01e") 97 | -- True 98 | -- >>> isLeft $ parse bencInt "Bint" (pack "i00e") 99 | -- True 100 | -- >>> isLeft $ parse bencInt "Bint" (pack "i002e") 101 | -- True 102 | bencInt :: ParsecBS.Parser Integer 103 | bencInt = do ds <- between (char 'i') (char 'e') numbers 104 | return (read ds) 105 | where numbers = do d' <- char '-' <|> digit 106 | ds' <- many digit 107 | parseNumber d' ds' 108 | parseNumber '0' [] = return "0" 109 | parseNumber '0' _ = unexpected "numbers cannot be left-padded with zeros" 110 | parseNumber '-' [] = unexpected "sign without any digits" 111 | parseNumber '-' (d'':_) | d'' == '0' = unexpected "numbers cannot be left-padded with zeros" 112 | parseNumber d'' ds'' = return (d'':ds'') 113 | 114 | -- | parse lists 115 | -- 116 | -- >>> parse bencList "Blist" (pack "le") 117 | -- Right [] 118 | -- >>> parse bencList "Blist" (pack "l4:spam4:eggse") 119 | -- Right [Bstr "spam",Bstr "eggs"] 120 | -- >>> parse bencList "Blist" (pack "l4:spami42ee") 121 | -- Right [Bstr "spam",Bint 42] 122 | -- >>> parse bencList "Blist" (pack "l4:spam4:eggsli42eee") 123 | -- Right [Bstr "spam",Bstr "eggs",Blist [Bint 42]] 124 | bencList :: ParsecBS.Parser [BVal] 125 | bencList = between (char 'l') (char 'e') (many bencVal) 126 | 127 | -- | parse dict 128 | -- 129 | -- >>> parse bencDict "Bdict" (pack "de") 130 | -- Right (fromList []) 131 | -- >>> parse bencDict "Bdict" (pack "d3:cow3:moo4:spam4:eggse") 132 | -- Right (fromList [("cow",Bstr "moo"),("spam",Bstr "eggs")]) 133 | -- >>> parse bencDict "Bdict" (pack "d4:spaml1:a1:bee") 134 | -- Right (fromList [("spam",Blist [Bstr "a",Bstr "b"])]) 135 | -- >>> parse bencDict "Bdict" (pack "d9:publisher3:bob17:publisher-webpage15:www.example.com18:publisher.location4:homee") 136 | -- Right (fromList [("publisher",Bstr "bob"),("publisher-webpage",Bstr "www.example.com"),("publisher.location",Bstr "home")]) 137 | bencDict :: ParsecBS.Parser (Map String BVal) 138 | bencDict = between (char 'd') (char 'e') $ fromList <$> many kvpair 139 | where kvpair = do k <- bencStr 140 | v <- bencVal 141 | return (unpack k, v) 142 | 143 | bencVal :: ParsecBS.Parser BVal 144 | bencVal = Bstr <$> bencStr <|> 145 | Bint <$> bencInt <|> 146 | Blist <$> bencList <|> 147 | Bdict <$> bencDict 148 | 149 | decode :: ByteString -> Either String BVal 150 | decode bs = case parse bencVal "BVal" bs of 151 | Left _ -> Left "Unable to parse torrent file" 152 | Right torrent -> Right torrent 153 | 154 | -- Encode BVal into a bencoded ByteString. Inverse of decode 155 | 156 | -- TODO: Use builders and lazy byte string to get O(1) concatenation over O(n) 157 | -- provided by lists. 158 | 159 | -- TODO: encode . decode pair might be a good candidate for Quickcheck. 160 | -- | encode bencoded-values 161 | -- 162 | -- >>> encode (Bstr (pack "")) 163 | -- "0:" 164 | -- >>> encode (Bstr (pack "spam")) 165 | -- "4:spam" 166 | -- >>> encode (Bint 0) 167 | -- "i0e" 168 | -- >>> encode (Bint 42) 169 | -- "i42e" 170 | -- >>> encode (Blist [(Bstr (pack "spam")), (Bstr (pack "eggs"))]) 171 | -- "l4:spam4:eggse" 172 | -- >>> encode (Blist []) 173 | -- "le" 174 | -- >>> encode (Bdict (fromList [("spam", Bstr $ pack "eggs")])) 175 | -- "d4:spam4:eggse" 176 | encode :: BVal -> ByteString 177 | encode (Bstr bs) = pack $ show (length bs) ++ ":" ++ unpack bs 178 | encode (Bint i) = pack $ "i" ++ show i ++ "e" 179 | encode (Blist xs) = concat ["l", concat $ map encode xs, "e"] 180 | encode (Bdict d) = concat ["d", concat kvlist, "e"] 181 | where 182 | kvlist :: [ByteString] 183 | kvlist = [encPair kv | kv <- toList d] 184 | encPair (k, v) = concat [encode . Bstr . pack $ k, encode v] 185 | -------------------------------------------------------------------------------- /src/FuncTorrent/ControlThread.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE OverloadedStrings #-} 2 | 3 | -- Description 4 | -- ControlThread handles all operations for a single torrent 5 | -- It is responsible for 6 | -- 1. Do parsing of torrent file. 7 | -- 2. Communicate with trackers and obtain peers 8 | -- 3. Initiate PeerThreads to do peer communication 9 | -- 4. Control the activity of PeerThreads 10 | -- 5. Maintain cache, etc 11 | -- 6. Handle incoming connections 12 | 13 | -- The overall operation may be divided into following parts 14 | -- 1. Initialization. 15 | -- 2. downloading/seeding. 16 | -- 3. Stopping download/seed. 17 | 18 | module FuncTorrent.ControlThread where 19 | 20 | import Control.Concurrent 21 | import Control.Exception.Base (bracket) 22 | import Control.Monad (void, unless) 23 | import Data.Either (rights) 24 | import Data.Foldable (foldlM) 25 | import Data.Map.Lazy (Map, fromList) 26 | 27 | import FuncTorrent.Core (AvailabilityChannel, DataChannel) 28 | import FuncTorrent.Metainfo (Metainfo(..)) 29 | import FuncTorrent.Peer (Peer(..), PeerThread(..), initPeerThread) 30 | import FuncTorrent.Tracker (Tracker(..), tracker) 31 | import FuncTorrent.Writer (initWriterThread) 32 | 33 | data ControlThread = ControlThread { 34 | -- | Static information about the torrent from the .torrent file 35 | metaInfo :: Metainfo 36 | 37 | -- | List of tracker responses 38 | , trackers :: [Tracker] 39 | 40 | -- | Active peer threads managed by the control thread 41 | , peerThreads :: [(ThreadId, PeerThread)] 42 | 43 | -- | Keeps track of the list of peers having a block 44 | , blocks :: Map Integer [PeerThread] 45 | 46 | -- | Peers report availability of a block on this channel 47 | , blockChan :: AvailabilityChannel 48 | 49 | -- [TODO] - A writer must be spawned per file, change to `Map File Chan` 50 | , writerChan :: DataChannel} 51 | 52 | initControlThread :: Metainfo -> IO (ThreadId, ControlThread) 53 | initControlThread m = do 54 | -- [todo] - This is not right. A control thread should spawn a writer thread 55 | -- per file and shut it down once done. Need a mechanism to map writers to 56 | -- files to peer thread workers. 57 | (_threadID, writerChan') <- initWriterThread "/tmp/functorrent.txt" 2048 58 | blockChan' <- newChan :: IO AvailabilityChannel 59 | let blocks' = fromList [] :: Map Integer [PeerThread] 60 | let ct = ControlThread m [] [] blocks' blockChan' writerChan' 61 | -- bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c 62 | tid <- forkIO $ bracket (initialize ct) cleanup loop 63 | return (tid, ct) 64 | 65 | initialize :: ControlThread -> IO ControlThread 66 | initialize ct = do 67 | trackers' <- mapM (tracker mInfo) (announceList mInfo) 68 | return $ ct {trackers = rights trackers'} 69 | where 70 | mInfo = metaInfo ct 71 | 72 | -- | Control thread loop. This is where all the action happens. 73 | -- 74 | -- CT starts with 4 random peers. CT listens for new blocks from `blockChan` and 75 | -- schedules it to be downloaded. This logic should get a lot smarter to speed 76 | -- up things. 77 | 78 | loop :: ControlThread -> IO () 79 | loop ct = do 80 | putStrLn "Do control thread work" 81 | 82 | -- Spawn block scheduler 83 | _ <- forkIO $ listener ct 84 | 85 | -- Spawn a bunch of peer threads 86 | let fewPeers = take 4 (concatMap peers $ trackers ct) 87 | -- [FIX] - Add this list to state so they can be cleaned up on shutdown 88 | mapM_ (forkPeerThread ct) fewPeers 89 | 90 | -- Drains the availability request channel and schedules them to be downloaded 91 | -- immediately with the same peer. This could get a lot smarter. 92 | listener :: ControlThread -> IO () 93 | listener ct = do 94 | putStrLn "Draining block availability channel" 95 | blocks' <- getChanContents $ blockChan ct 96 | -- List of completed blocks, assume 32 pieces in the torrent 97 | -- [FIX] - Replace with real number of pieces in the torrent 98 | let done = map (const False) [0..31 :: Integer] :: [Bool] 99 | void $ foldlM schedule done blocks' 100 | where 101 | -- | Schedule a block to be downloaded on an available peer 102 | schedule :: [Bool] -> (PeerThread, Integer) -> IO [Bool] 103 | schedule done (PeerThread peer _ requestChan _, index) = do 104 | putStrLn $ concat ["Found block ", show index, " with ", show peer] 105 | unless (done !! fromInteger index) $ writeChan requestChan index 106 | return $ replaceAt done True index 107 | 108 | -- | Replace the nth item with key 109 | replaceAt :: [a] -> a -> Integer -> [a] 110 | replaceAt xs key n = pick ++ [key] ++ rest 111 | where (pick, _replace:rest) = splitAt (fromInteger n) xs 112 | 113 | -- | Called by bracket before the control thread is shutdown 114 | cleanup :: ControlThread -> IO () 115 | cleanup ct = do 116 | putStrLn "Exit control thread killing all peer threads" 117 | 118 | -- [todo] - Kill writer thread here 119 | -- Kill all the peer threads. Synchronous op, no need to wait. 120 | mapM_ (killThread . fst) $ peerThreads ct 121 | 122 | -- Forks a peer-thread and add it to the peerThreads list 123 | forkPeerThread :: ControlThread -> Peer -> IO ControlThread 124 | forkPeerThread ct p = do 125 | pt <- initPeerThread p (blockChan ct) (writerChan ct) 126 | let newPeerThreads = pt : peerThreads ct -- Append pt to peerThreads 127 | return ct { peerThreads = newPeerThreads} 128 | -------------------------------------------------------------------------------- /src/FuncTorrent/Core.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE OverloadedStrings #-} 2 | ----------------------------------------------------------------------------- 3 | -- | 4 | -- Module : FuncTorrent.Core 5 | -- 6 | -- A module for all shared types to prevent cyclic dependencies. 7 | ----------------------------------------------------------------------------- 8 | 9 | module FuncTorrent.Core 10 | ( 11 | -- | Channels 12 | AvailabilityChannel 13 | , DataChannel 14 | , RequestChannel 15 | 16 | -- | Types 17 | , Block(..) 18 | , Peer(..) 19 | , PeerThread(..) 20 | ) where 21 | 22 | import Control.Concurrent (Chan) 23 | import qualified Data.ByteString.Lazy as BL 24 | 25 | -- | A block of data in a file specified by offset and contents. 26 | -- Its the client's responsibility to send the block to the correct writer 27 | -- channel and not to confuse offset with index. 28 | data Block = Block Integer BL.ByteString 29 | 30 | -- | A single Peer, denoted by a IP address and port 31 | data Peer = Peer String Integer 32 | deriving (Eq) 33 | 34 | -- | A steam of available blocks, reported by peers to control thread. 35 | type AvailabilityChannel = Chan (PeerThread, Integer) 36 | 37 | -- | A steam for block request 38 | type RequestChannel = Chan Integer 39 | 40 | -- | A content stream 41 | type DataChannel = Chan Block 42 | 43 | -- | Thread State is a Peer and the trio of channels. A channel to report 44 | -- blocks, one to get block requests and one to write downloaded blocks back. 45 | data PeerThread = PeerThread Peer AvailabilityChannel RequestChannel DataChannel 46 | 47 | -- Instance declarations 48 | instance Show Block where 49 | show (Block offset _) = concat ["Block < ", show offset, " >"] 50 | 51 | instance Show Peer where 52 | show (Peer ip p) = concat ["Peer < ", ip, " ", show p, " >"] 53 | -------------------------------------------------------------------------------- /src/FuncTorrent/Logger.hs: -------------------------------------------------------------------------------- 1 | module FuncTorrent.Logger ( 2 | Log 3 | , initLogger 4 | , logMessage 5 | , logError 6 | , logStop 7 | ) where 8 | 9 | import Control.Concurrent 10 | 11 | -- The below logger implementation has been taken from 12 | -- Parallel and Concurrent Programming in Haskell, Chapter 7 13 | -- The logger is implemented in a concurrent thread. 14 | 15 | -- Here the (MVar LogCommand) is used for actual thread communication 16 | -- So if multiple threads try to log, then the logger will be thread-safe 17 | -- Also the 'loop' in logger will wait for the message to come. 18 | -- 19 | -- The MVar in stop is just to ensure the logger thread executes completely 20 | -- Before exiting the main application. 21 | data Logger = Logger (MVar LogCommand) 22 | data LogCommand = Message String | Stop (MVar ()) 23 | 24 | type Log = String -> IO () 25 | 26 | initLogger :: IO Logger 27 | initLogger = do 28 | m <- newEmptyMVar 29 | let l = Logger m 30 | _ <- forkIO (logger l) 31 | return l 32 | 33 | logger :: Logger -> IO () 34 | logger (Logger m) = loop 35 | where 36 | loop :: IO () 37 | loop = do 38 | cmd <- takeMVar m 39 | case cmd of 40 | Message msg -> do 41 | -- We can alternatively put the message to a file 42 | putStrLn msg 43 | -- Recursive 44 | loop 45 | Stop s -> do 46 | putStrLn "FuncTorrent: Exit succesfully" 47 | putMVar s () 48 | 49 | -- Send log message to logger 50 | logMessage :: Logger -> Log 51 | logMessage (Logger m) s = putMVar m (Message s) 52 | 53 | logError :: Show e => Log -> e-> IO () 54 | logError logM e = logM $ "Error: \n" ++ show e 55 | 56 | logStop :: Logger -> IO () 57 | logStop (Logger m) = do 58 | s <- newEmptyMVar 59 | putMVar m (Stop s) 60 | -- Wait for logger to complete the logging 61 | takeMVar s 62 | -------------------------------------------------------------------------------- /src/FuncTorrent/Metainfo.hs: -------------------------------------------------------------------------------- 1 | module FuncTorrent.Metainfo 2 | (Info(..), 3 | Metainfo(..), 4 | mkInfo, 5 | mkMetaInfo 6 | ) where 7 | 8 | import Prelude hiding (lookup) 9 | import Data.ByteString.Char8 (ByteString, unpack) 10 | import Data.Map as M ((!), lookup) 11 | import Crypto.Hash.SHA1 (hash) 12 | import Data.Maybe (maybeToList) 13 | 14 | import FuncTorrent.Bencode (BVal(..), encode, bstrToString, bValToInteger) 15 | 16 | -- only single file mode supported for the time being. 17 | data Info = Info { pieceLength :: !Integer 18 | , pieces :: !ByteString 19 | , private :: !(Maybe Integer) 20 | , name :: !String 21 | , lengthInBytes :: !Integer 22 | , md5sum :: !(Maybe String) 23 | } deriving (Eq, Show) 24 | 25 | data Metainfo = Metainfo { info :: !Info 26 | , announceList :: ![String] 27 | , creationDate :: !(Maybe Integer) 28 | , comment :: !(Maybe String) 29 | , createdBy :: !(Maybe String) 30 | , encoding :: !(Maybe String) 31 | , infoHash :: !ByteString 32 | } deriving (Eq, Show) 33 | 34 | mkInfo :: BVal -> Maybe Info 35 | mkInfo (Bdict m) = let (Bint pieceLength') = m ! "piece length" 36 | (Bstr pieces') = m ! "pieces" 37 | private' = Nothing 38 | (Bstr name') = m ! "name" 39 | (Bint length') = m ! "length" 40 | md5sum' = Nothing 41 | in Just Info { pieceLength = pieceLength' 42 | , pieces = pieces' 43 | , private = private' 44 | , name = unpack name' 45 | , lengthInBytes = length' 46 | , md5sum = md5sum'} 47 | mkInfo _ = Nothing 48 | 49 | mkMetaInfo :: BVal -> Either String Metainfo 50 | mkMetaInfo (Bdict m) = 51 | let (Just info') = mkInfo $ m ! "info" 52 | announce' = lookup "announce" m 53 | announceList' = lookup "announce-list" m 54 | creationDate' = lookup "creation date" m 55 | comment' = lookup "comment" m 56 | createdBy' = lookup "created by" m 57 | encoding' = lookup "encoding" m 58 | in Right Metainfo { 59 | info = info' 60 | , announceList = maybeToList (announce' >>= bstrToString) 61 | ++ getAnnounceList announceList' 62 | , creationDate = bValToInteger =<< creationDate' 63 | , comment = bstrToString =<< comment' 64 | , createdBy = bstrToString =<< createdBy' 65 | , encoding = bstrToString =<< encoding' 66 | , infoHash = hash . encode $ (m ! "info") 67 | } 68 | 69 | mkMetaInfo _ = Left "Unable to make Metainfo. Corrupt BString" 70 | 71 | getAnnounceList :: Maybe BVal -> [String] 72 | getAnnounceList Nothing = [] 73 | getAnnounceList (Just (Bint _)) = [] 74 | getAnnounceList (Just (Bstr _)) = [] 75 | getAnnounceList (Just (Blist l)) = map (\s -> case s of 76 | (Bstr s') -> unpack s' 77 | (Blist s') -> case s' of 78 | [Bstr s''] -> unpack s'' 79 | _ -> "" 80 | _ -> "") l 81 | 82 | getAnnounceList (Just (Bdict _)) = [] 83 | -------------------------------------------------------------------------------- /src/FuncTorrent/Peer.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE OverloadedStrings #-} 2 | ----------------------------------------------------------------------------- 3 | -- | 4 | -- Module : FuncTorrent.Peer 5 | -- 6 | -- Module to handle operations with one peer. 7 | -- 8 | -- Peer talks peer protocol with one remote peer and reports the availability of 9 | -- blocks to the control thread via `availability` channel. Control thread can 10 | -- schedule block downloads taking into consideration the state of all active 11 | -- peers. Requests to fetch blocks arrive via the `reader` channel, and 12 | -- retrieved blocks are written to `writer` channel. This module is stateless 13 | -- and is perfectly safe to be killed anytime. The only requirement is to close 14 | -- inbound channels, such that control threads cannot request for more downloads 15 | -- after its shutdown. 16 | -- 17 | ----------------------------------------------------------------------------- 18 | module FuncTorrent.Peer 19 | ( 20 | Peer(..), 21 | PeerMsg(..), 22 | PeerState(..), 23 | PeerThread(..), 24 | PieceState(..), 25 | 26 | initPeerThread, 27 | 28 | -- Testing 29 | handShake, 30 | ) where 31 | 32 | import Prelude hiding (lookup, concat, replicate, splitAt) 33 | 34 | import Control.Applicative (liftA3) 35 | import Control.Concurrent 36 | import Control.Exception.Base (bracket) 37 | import Control.Monad (replicateM, liftM) 38 | import Data.Binary (Binary(..), decode) 39 | import Data.Binary.Get (getWord32be, getWord16be, getWord8, runGet) 40 | import Data.Binary.Put (putWord32be, putWord16be, putWord8) 41 | import Data.ByteString (ByteString, pack, unpack, concat, hGet, hPut, singleton) 42 | import Data.ByteString.Lazy (fromStrict, fromChunks) 43 | import Data.List (nub) 44 | import Network (connectTo, PortID(..)) 45 | import System.IO 46 | import System.Random (newStdGen, randomRs) 47 | import qualified Data.ByteString.Char8 as BC (replicate, pack) 48 | 49 | import FuncTorrent.Core (Block(..), Peer(..), PeerThread(..), 50 | AvailabilityChannel, DataChannel) 51 | 52 | data PeerState = PeerState { 53 | handle :: Handle 54 | , amChoking :: Bool 55 | , amInterested :: Bool 56 | , peerChoking :: Bool 57 | , peerInterested :: Bool} 58 | 59 | data PieceState = Pending 60 | | InProgress 61 | | Have 62 | deriving (Show) 63 | 64 | data PeerMsg = KeepAliveMsg 65 | | ChokeMsg 66 | | UnChokeMsg 67 | | InterestedMsg 68 | | NotInterestedMsg 69 | | HaveMsg Integer 70 | | BitFieldMsg ByteString 71 | | RequestMsg Integer Integer Integer 72 | | PieceMsg Integer Integer ByteString 73 | | CancelMsg Integer Integer Integer 74 | | PortMsg Integer 75 | deriving (Show) 76 | 77 | -- Peer thread implementation 78 | 79 | -- | Spawns a new peer thread 80 | -- 81 | -- Requests for fetching new blocks can be sent to the channel and those blocks 82 | -- will be eventually written to the writer channel. 83 | initPeerThread :: Peer -> AvailabilityChannel -> DataChannel -> IO (ThreadId, PeerThread) 84 | initPeerThread p availChan dataChan = do 85 | putStrLn $ "Spawning peer thread for " ++ show p 86 | requestChan <- newChan :: IO (Chan Integer) 87 | let pt = PeerThread p availChan requestChan dataChan 88 | -- bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c 89 | tid <- forkIO $ bracket (initialize pt) cleanup action 90 | return (tid, pt) 91 | where 92 | -- | Spawns two threads to talk peer protocol and download requested blocks 93 | action :: PeerThread -> IO () 94 | action pt = do 95 | _ <- forkIO $ loop pt 96 | _ <- forkIO $ downloader pt 97 | return () 98 | 99 | -- |Initialize module. Resources allocated here must be cleaned up in cleanup 100 | initialize :: PeerThread -> IO PeerThread 101 | initialize pt = putStrLn "Initializing peer" >> return pt 102 | 103 | -- [todo] - Implement the peer protocol here 104 | -- | Talks peer protocol to one peer 105 | -- 106 | -- Reports the list of available pieces back to the control thread, which 107 | -- eventually schedules the pieces to be downloaded depending on various 108 | -- prioritization techniques. 109 | loop :: PeerThread -> IO () 110 | loop pt@(PeerThread _ availabilityChan _ _) = do 111 | -- Assume a torrent with 32 pieces and the remote peer has a few of them. 112 | -- Report those to the control thread. 113 | g <- newStdGen 114 | let available = nub $ take 4 (randomRs (0, 31) g) :: [Integer] 115 | 116 | mapM_ report available 117 | 118 | where 119 | report :: Integer -> IO () 120 | report block = writeChan availabilityChan (pt, block) 121 | 122 | -- Drains the block request channel and writes contents to writer channel. 123 | downloader :: PeerThread -> IO () 124 | downloader (PeerThread _ _ requestChan dataChan) = do 125 | putStrLn "Draining reader" 126 | requests <- getChanContents requestChan 127 | mapM_ download requests 128 | where 129 | download :: Integer -> IO () 130 | download x = do 131 | -- [todo] - Replace with real download implementation 132 | -- | Download a piece and write to writer channel 133 | putStrLn $ "Download block " ++ show x 134 | threadDelay 1000000 135 | writeChan dataChan $ Block x "hello world" 136 | 137 | -- [todo] - Close the channel on shutdown. 138 | -- 139 | -- The writer might be down and the channel will keep accepting more data, 140 | -- leading to ugly hard to track down bugs. 141 | -- 142 | -- | Called by bracket before the writer is shutdown 143 | cleanup :: PeerThread -> IO () 144 | cleanup (PeerThread peer _ _ _) = putStrLn $ "Clean up peer thread for " ++ show peer 145 | 146 | -- Protocol implementation 147 | 148 | genHandShakeMsg :: ByteString -> String -> ByteString 149 | genHandShakeMsg infoHash peer_id = concat [pstrlen, pstr, reserved, infoHash, peerID] 150 | where pstrlen = singleton 19 151 | pstr = BC.pack "BitTorrent protocol" 152 | reserved = BC.replicate 8 '\0' 153 | peerID = BC.pack peer_id 154 | 155 | handShake :: Peer -> ByteString -> String -> IO Handle 156 | handShake (Peer ip port) infoHash peerid = do 157 | let hs = genHandShakeMsg infoHash peerid 158 | h <- connectTo ip (PortNumber (fromIntegral port)) 159 | hSetBuffering h LineBuffering 160 | hPut h hs 161 | rlenBS <- hGet h (length (unpack hs)) 162 | putStrLn $ "got handshake from peer: " ++ show rlenBS 163 | return h 164 | 165 | instance Binary PeerMsg where 166 | put msg = case msg of 167 | KeepAliveMsg -> putWord32be 0 168 | ChokeMsg -> do putWord32be 1 169 | putWord8 0 170 | UnChokeMsg -> do putWord32be 1 171 | putWord8 1 172 | InterestedMsg -> do putWord32be 1 173 | putWord8 2 174 | NotInterestedMsg -> do putWord32be 1 175 | putWord8 3 176 | HaveMsg i -> do putWord32be 5 177 | putWord8 4 178 | putWord32be (fromIntegral i) 179 | BitFieldMsg bf -> do putWord32be $ fromIntegral (1 + bfListLen) 180 | putWord8 5 181 | mapM_ putWord8 bfList 182 | where bfList = unpack bf 183 | bfListLen = length bfList 184 | RequestMsg i o l -> do putWord32be 13 185 | putWord8 6 186 | putWord32be (fromIntegral i) 187 | putWord32be (fromIntegral o) 188 | putWord32be (fromIntegral l) 189 | PieceMsg i o b -> do putWord32be $ fromIntegral (9 + blocklen) 190 | putWord8 7 191 | putWord32be (fromIntegral i) 192 | putWord32be (fromIntegral o) 193 | mapM_ putWord8 blockList 194 | where blockList = unpack b 195 | blocklen = length blockList 196 | CancelMsg i o l -> do putWord32be 13 197 | putWord8 8 198 | putWord32be (fromIntegral i) 199 | putWord32be (fromIntegral o) 200 | putWord32be (fromIntegral l) 201 | PortMsg p -> do putWord32be 3 202 | putWord8 9 203 | putWord16be (fromIntegral p) 204 | get = do 205 | l <- getWord32be 206 | msgid <- getWord8 207 | case msgid of 208 | 0 -> return ChokeMsg 209 | 1 -> return UnChokeMsg 210 | 2 -> return InterestedMsg 211 | 3 -> return NotInterestedMsg 212 | 4 -> liftM (HaveMsg . fromIntegral) getWord32be 213 | 5 -> liftM (BitFieldMsg . pack) (replicateM (fromIntegral l - 1) getWord8) 214 | 6 -> liftA3 RequestMsg getInteger getInteger getInteger 215 | where getInteger = fromIntegral <$> getWord32be 216 | 7 -> liftA3 PieceMsg getInteger getInteger (pack <$> replicateM (fromIntegral l - 9) getWord8) 217 | where getInteger = fromIntegral <$> getWord32be 218 | 8 -> liftA3 CancelMsg getInteger getInteger getInteger 219 | where getInteger = fromIntegral <$> getWord32be 220 | 9 -> liftM (PortMsg . fromIntegral) getWord16be 221 | _ -> error ("unknown message ID: " ++ show msgid) 222 | 223 | getMsg :: Handle -> IO PeerMsg 224 | getMsg h = do 225 | lBS <- hGet h 4 226 | let l = bsToInt lBS 227 | if l == 0 228 | then return KeepAliveMsg 229 | else do 230 | putStrLn $ "len: " ++ show l 231 | msgID <- hGet h 1 232 | putStrLn $ "msg Type: " ++ show msgID 233 | msg <- hGet h (l - 1) 234 | return $ decode $ fromStrict $ concat [lBS, msgID, msg] 235 | 236 | bsToInt :: ByteString -> Int 237 | bsToInt x = fromIntegral (runGet getWord32be (fromChunks (return x))) 238 | -------------------------------------------------------------------------------- /src/FuncTorrent/Tracker.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE OverloadedStrings #-} 2 | ----------------------------------------------------------------------------- 3 | -- | 4 | -- Module : FuncTorrent.Tracker 5 | -- 6 | -- Tracker module, which can be cleaned up a lot. 7 | -- 8 | -- Module exposes only one single type `Tracker` representing a tracker response 9 | -- and one function `tracker` to talk to tracker. 10 | ----------------------------------------------------------------------------- 11 | 12 | module FuncTorrent.Tracker 13 | (Tracker(..), 14 | tracker, 15 | 16 | -- Exposed for testing 17 | mkTrackerResponse, 18 | ) where 19 | 20 | import Prelude hiding (lookup, splitAt) 21 | 22 | import Data.ByteString (ByteString) 23 | import Data.ByteString.Char8 as BC (pack, unpack, splitAt) 24 | import Data.Char (chr) 25 | import Data.List (intercalate) 26 | import Data.Map as M (lookup) 27 | import Network.HTTP (simpleHTTP, defaultGETRequest_, getResponseBody) 28 | import Network.HTTP.Base (urlEncode) 29 | import Network.URI (parseURI) 30 | import qualified Data.ByteString.Base16 as B16 (encode) 31 | import qualified Data.ByteString.Char8 as BC (concat, intercalate) 32 | 33 | import FuncTorrent.Bencode (BVal(..), decode) 34 | import FuncTorrent.Metainfo (Info(..), Metainfo(..)) 35 | import FuncTorrent.Peer (Peer(..)) 36 | import FuncTorrent.Utils (splitN) 37 | 38 | -- | Tracker response. 39 | data Tracker = Tracker 40 | { interval :: Maybe Integer 41 | , peers :: [Peer] 42 | , complete :: Maybe Integer 43 | , incomplete :: Maybe Integer 44 | } deriving (Eq, Show) 45 | 46 | -- | Connect to a tracker and get peer info 47 | -- 48 | -- Primary interface to the module. 49 | tracker :: Metainfo -> String -> IO (Either ByteString Tracker) 50 | tracker mInfo url = do 51 | response <- get url $ mkParams mInfo "-HS0001-*-*-20150215" 52 | 53 | -- TODO: Write to ~/.functorrent/caches 54 | -- writeFile (name (info m) ++ ".cache") response 55 | 56 | return $ case decode response of 57 | Right trackerInfo -> mkTrackerResponse trackerInfo 58 | Left err -> Left $ BC.pack err 59 | 60 | -- | Deserialize tracker response 61 | mkTrackerResponse :: BVal -> Either ByteString Tracker 62 | mkTrackerResponse resp = 63 | case lookup "failure reason" body of 64 | Just (Bstr err) -> Left err 65 | Just _ -> Left "Unknown failure" 66 | Nothing -> 67 | let (Just (Bint i)) = lookup "interval" body 68 | (Just (Bstr peersBS)) = lookup "peers" body 69 | pl = map makePeer (splitN 6 peersBS) 70 | in Right Tracker { 71 | interval = Just i 72 | , peers = pl 73 | , complete = Nothing 74 | , incomplete = Nothing} 75 | where 76 | (Bdict body) = resp 77 | 78 | toInt :: String -> Integer 79 | toInt = read 80 | 81 | toPort :: ByteString -> Integer 82 | toPort = read . ("0x" ++) . unpack . B16.encode 83 | 84 | toIP :: ByteString -> String 85 | toIP = Data.List.intercalate "." . 86 | map (show . toInt . ("0x" ++) . unpack) . 87 | splitN 2 . B16.encode 88 | 89 | makePeer :: ByteString -> Peer 90 | makePeer peer = Peer (toIP ip') (toPort port') 91 | where (ip', port') = splitAt 4 peer 92 | 93 | --- | URL encode hash as per RFC1738 94 | --- TODO: Add tests 95 | --- REVIEW: Why is this not written in terms of `Network.HTTP.Base.urlEncode` or 96 | --- equivalent library function? 97 | urlEncodeHash :: ByteString -> String 98 | urlEncodeHash bs = concatMap (encode' . unpack) (splitN 2 bs) 99 | where encode' b@[c1, c2] = let c = chr (read ("0x" ++ b)) 100 | in escape c c1 c2 101 | encode' _ = "" 102 | escape i c1 c2 | i `elem` nonSpecialChars = [i] 103 | | otherwise = "%" ++ [c1] ++ [c2] 104 | 105 | nonSpecialChars = ['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ "-_.~" 106 | 107 | -- | Make a query string out of the arguments 108 | mkParams :: Metainfo -> String -> ByteString 109 | mkParams m peer_id = 110 | BC.intercalate "&" [BC.concat [f, "=", s] | (f,s) <- params] 111 | where 112 | params = mkArgs m peer_id 113 | 114 | --- | Prepare arguments that should be posted to tracker 115 | mkArgs :: Metainfo -> String -> [(ByteString, ByteString)] 116 | mkArgs m peer_id = [("info_hash", pack . urlEncodeHash . B16.encode . infoHash $ m), 117 | ("peer_id", pack . urlEncode $ peer_id), 118 | ("port", "6881"), 119 | ("uploaded", "0"), 120 | ("downloaded", "0"), 121 | ("left", pack . show . lengthInBytes $ info m), 122 | ("compact", "1"), 123 | ("event", "started")] 124 | 125 | get :: String -> ByteString -> IO ByteString 126 | get url args = simpleHTTP (defaultGETRequest_ url') >>= getResponseBody 127 | where url' = case parseURI $ BC.unpack $ BC.concat [BC.pack url, "?", args] of 128 | Just x -> x 129 | _ -> error "Bad tracker URL" 130 | -------------------------------------------------------------------------------- /src/FuncTorrent/Utils.hs: -------------------------------------------------------------------------------- 1 | module FuncTorrent.Utils where 2 | 3 | import qualified Data.ByteString.Char8 as BC 4 | 5 | splitN :: Int -> BC.ByteString -> [BC.ByteString] 6 | splitN n bs | BC.null bs = [] 7 | | otherwise = BC.take n bs : splitN n (BC.drop n bs) 8 | -------------------------------------------------------------------------------- /src/FuncTorrent/Writer.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE OverloadedStrings #-} 2 | ----------------------------------------------------------------------------- 3 | -- | 4 | -- Module : FuncTorrent.Writer 5 | -- 6 | -- A writer thread that gets pieces of data from the peers and writes it to the 7 | -- file. Ideally the only component that writes to disk. 8 | -- 9 | -- Initialize the module 10 | -- 11 | -- > (threadID, writer) <- initWriterThread file 12 | -- 13 | -- Write to the file by sending data to channel. Could abstract away the low 14 | -- level details sometime later. 15 | -- 16 | -- > writeChan writer (Block 26 "hello world") 17 | -- 18 | -- Stop the channel when done with it. 19 | -- 20 | -- > killThread threadID 21 | ----------------------------------------------------------------------------- 22 | 23 | module FuncTorrent.Writer 24 | ( 25 | initWriterThread 26 | ) where 27 | 28 | import Control.Concurrent (ThreadId, forkIO, getChanContents, newChan) 29 | import Control.Exception.Base (bracket) 30 | import Control.Monad (unless) 31 | import System.Directory (doesFileExist) 32 | import System.IO (Handle, IOMode(..), SeekMode(..), openFile, hSeek, 33 | hFlush, hClose) 34 | import qualified Data.ByteString.Lazy as BL 35 | 36 | import FuncTorrent.Core (Block(..), DataChannel) 37 | 38 | 39 | data Writer = Writer Handle DataChannel 40 | 41 | -- |Initialize writer module 42 | initWriterThread :: FilePath -> Int -> IO (ThreadId, DataChannel) 43 | initWriterThread file size = do 44 | putStrLn "Spawning writer" 45 | chan <- newChan 46 | -- bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c 47 | tid <- forkIO $ bracket (initialize file size chan) cleanup loop 48 | return (tid, chan) 49 | 50 | -- |Initialize module. Resources allocated here must be cleaned up in cleanup 51 | initialize :: FilePath -> Int -> DataChannel -> IO Writer 52 | initialize file size chan = do 53 | putStrLn "Initializing writer" 54 | 55 | -- Create file of specified size to seek anywhere in the file 56 | dfe <- doesFileExist file 57 | unless dfe $ writeFile file (replicate size '\0') 58 | 59 | handle <- openFile file ReadWriteMode 60 | return (Writer handle chan) 61 | 62 | -- | Drains the channel and writes contents to disk 63 | loop :: Writer -> IO () 64 | loop (Writer handle chan) = do 65 | putStrLn "Draining writer" 66 | msgs <- getChanContents chan 67 | mapM_ write' msgs 68 | where 69 | write' :: Block -> IO () 70 | -- [TODO] - Flushing after every write might lead to terrible performance 71 | write' (Block offset contents) = do 72 | putStrLn $ "Writing block " ++ show offset ++ " to disk" 73 | hSeek handle AbsoluteSeek offset 74 | BL.hPut handle contents 75 | hFlush handle 76 | 77 | -- [todo] - Close the channel on shutdown. 78 | -- 79 | -- The writer might be down and the channel will keep accepting more data, 80 | -- leading to ugly hard to track down bugs. 81 | -- 82 | -- | Called by bracket before the writer is shutdown 83 | cleanup :: Writer -> IO () 84 | cleanup (Writer handle _) = 85 | putStrLn "Clean up writer" >> hClose handle 86 | -------------------------------------------------------------------------------- /src/Main.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE OverloadedStrings #-} 2 | {- | 3 | Module : Main 4 | Parses command-line options and starts torrent client 5 | -} 6 | 7 | module Main where 8 | 9 | import Prelude hiding (log, length, readFile, writeFile) 10 | 11 | import Control.Concurrent 12 | import Control.Monad (liftM) 13 | import Data.ByteString (ByteString) 14 | import Data.ByteString.Char8 (readFile) 15 | import System.Directory (doesFileExist) 16 | import System.Environment (getArgs) 17 | import System.Posix.Signals (installHandler, Handler(Catch), sigINT, sigTERM) 18 | 19 | import FuncTorrent.Bencode (decode) 20 | import FuncTorrent.Logger (Log, initLogger, logMessage, logStop) 21 | import FuncTorrent.Metainfo (Metainfo(..), mkMetaInfo) 22 | import FuncTorrent.ControlThread (initControlThread) 23 | 24 | peerId :: String 25 | peerId = "-HS0001-*-*-20150215" 26 | 27 | main :: IO () 28 | main = do 29 | args <- getArgs 30 | logR <- initLogger 31 | let log = logMessage logR 32 | log "Starting up functorrent" 33 | log $ "Parsing input file " ++ concat args 34 | 35 | case args of 36 | [file] -> do 37 | minfo <- parseTorrentFile log file 38 | case minfo of 39 | Right m -> startTorrentConc log m 40 | Left err -> log err 41 | _ -> usage 42 | 43 | logStop logR 44 | 45 | usage :: IO () 46 | usage = putStrLn "Usage: functorrent torrent-file" 47 | 48 | 49 | parseTorrentFile :: Log -> String -> IO (Either String Metainfo) 50 | parseTorrentFile _ file = do 51 | fileExist <- doesFileExist file 52 | if fileExist 53 | then liftM getMetaInfo (readFile file) 54 | else return $ Left "File does not exist" 55 | 56 | where 57 | getMetaInfo :: ByteString -> Either String Metainfo 58 | getMetaInfo torrentStr = decode torrentStr >>= mkMetaInfo 59 | 60 | startTorrentConc :: Log -> Metainfo -> IO () 61 | startTorrentConc _ m = do 62 | -- Handle user-interrupt 63 | interrupt <- newEmptyMVar 64 | _ <- installHandler sigINT (Catch $ putMVar interrupt sigINT) Nothing 65 | _ <- installHandler sigTERM (Catch $ putMVar interrupt sigTERM) Nothing 66 | 67 | -- Fork Control-Thread(s) 68 | (ctid, _ct) <- initControlThread m 69 | 70 | -- Wait For user-interrupt 71 | _ <- takeMVar interrupt 72 | 73 | -- Exit gracefully 74 | killThread ctid 75 | -------------------------------------------------------------------------------- /stack.yaml: -------------------------------------------------------------------------------- 1 | # For more information, see: https://github.com/commercialhaskell/stack/blob/release/doc/yaml_configuration.md 2 | 3 | # Specifies the GHC version and set of packages available (e.g., lts-3.5, nightly-2015-09-21, ghc-7.10.2) 4 | resolver: lts-3.11 5 | 6 | # Local packages, usually specified by relative directory name 7 | packages: 8 | - '.' 9 | 10 | # Packages to be pulled from upstream that are not in the resolver (e.g., acme-missiles-0.3) 11 | extra-deps: [] 12 | 13 | # Override default flag values for local packages and extra-deps 14 | flags: {} 15 | 16 | # Extra package databases containing global packages 17 | extra-package-dbs: [] 18 | 19 | # Control whether we use the GHC we find on the path 20 | # system-ghc: true 21 | 22 | # Require a specific version of stack, using version ranges 23 | # require-stack-version: -any # Default 24 | # require-stack-version: >= 0.1.4.0 25 | 26 | # Override the architecture used by stack, especially useful on Windows 27 | # arch: i386 28 | # arch: x86_64 29 | 30 | # Extra directories used by stack for building 31 | # extra-include-dirs: [/path/to/dir] 32 | # extra-lib-dirs: [/path/to/dir] 33 | -------------------------------------------------------------------------------- /test/BencodeTests.hs: -------------------------------------------------------------------------------- 1 | module BencodeTests (tests) where 2 | 3 | import FuncTorrent.Bencode (encode, decode, BVal(..)) 4 | 5 | import Test.Tasty (TestTree, testGroup) 6 | import Test.Tasty.QuickCheck (testProperty) 7 | 8 | propEncodeDecode :: BVal -> Bool 9 | propEncodeDecode bval = let encoded = encode bval 10 | decoded = decode encoded 11 | in case decoded of 12 | Left _ -> False 13 | Right d -> d == bval 14 | 15 | qcTests :: TestTree 16 | qcTests = testGroup "QuickCheck tests" [ testProperty "encode/decode" propEncodeDecode ] 17 | 18 | tests :: TestTree 19 | tests = testGroup "Tests" [qcTests] 20 | -------------------------------------------------------------------------------- /test/Test.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE OverloadedStrings #-} 2 | module Main where 3 | 4 | import Prelude hiding (readFile) 5 | 6 | import Data.ByteString (ByteString, readFile) 7 | import Data.Map.Strict (fromList) 8 | 9 | import Test.Tasty (TestTree, testGroup, defaultMain) 10 | import Test.Tasty.HUnit (testCase, (@?=)) 11 | 12 | import FuncTorrent.Bencode (encode, decode, BVal(..)) 13 | import FuncTorrent.Metainfo (Info(..), Metainfo(..), mkMetaInfo) 14 | import FuncTorrent.Peer (Peer(..)) 15 | import FuncTorrent.Tracker 16 | 17 | import qualified BencodeTests 18 | 19 | -- Parsed .torrent file 20 | file :: BVal 21 | file = Bdict (fromList [ 22 | ("announce",Bstr "http://9.rarbg.com:2710/announce"), 23 | ("comment",Bstr "hello world"), 24 | ("created by",Bstr "Jaseem Abid"), 25 | ("creation date",Bint 1428717851), 26 | ("encoding",Bstr "UTF-8"), 27 | ("info",Bdict (fromList [ 28 | ("length",Bint 12), 29 | ("name",Bstr "hello.txt"), 30 | ("piece length",Bint 32768), 31 | ("pieces",Bstr "\"Ycc\179\222@\176o\152\US\184]\130\&1.\140\SO\213\DC1"), 32 | ("private",Bint 0)]))]) 33 | 34 | hello :: Metainfo 35 | hello = Metainfo { 36 | info = Info { 37 | pieceLength = 32768, 38 | pieces = "\"Ycc\179\222@\176o\152\US\184]\130\&1.\140\SO\213\DC1", 39 | private = Nothing, 40 | name = "hello.txt", 41 | lengthInBytes = 12, 42 | md5sum = Nothing 43 | }, 44 | announceList = ["http://9.rarbg.com:2710/announce"], 45 | creationDate = Just 1428717851, 46 | comment = Just "hello world", 47 | createdBy = Just "Jaseem Abid", 48 | encoding = Just "UTF-8", 49 | infoHash = "\205CX(;\163 expected @?= file 57 | Left _ -> error "Failed parsing test file" 58 | 59 | 60 | testMkMetaInfo :: TestTree 61 | testMkMetaInfo = testCase "Should mkInfo valid torrent files" $ do 62 | str <- readFile "./data/hello.txt.torrent" 63 | case decode str of 64 | Right expected -> mkMetaInfo expected @?= Right hello 65 | Left _ -> error "Failed parsing test file" 66 | 67 | testResponse1 :: TestTree 68 | testResponse1 = testCase "Should parse valid tracker response" $ do 69 | str <- readFile "./data/debian-7.8.0-amd64-CD-1.iso.cache" 70 | case decode str of 71 | Right bval -> expectation @?= mkTrackerResponse bval 72 | Left _ -> error "Failed parsing test file" 73 | where 74 | expectation :: Either a Tracker 75 | expectation = Right Tracker { 76 | interval = Just 900, 77 | 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], 78 | complete = Nothing, 79 | incomplete = Nothing 80 | } 81 | 82 | testResponse2 :: TestTree 83 | testResponse2 = testCase "Should parse invalid tracker response" $ do 84 | str <- readFile "./data/debian-7.8.0-amd64-CD-1.iso.error" 85 | case decode str of 86 | Right bval -> expectation @?= mkTrackerResponse bval 87 | Left _ -> error "Failed parsing test file" 88 | where 89 | expectation :: Either ByteString a 90 | expectation = Left "torrent not found" 91 | 92 | 93 | unitTests :: TestTree 94 | unitTests = testGroup "Unit tests" [testFile, testMkMetaInfo, testResponse1, 95 | testResponse2] 96 | 97 | tests :: TestTree 98 | tests = testGroup "Tests" [unitTests, BencodeTests.tests] 99 | 100 | main :: IO () 101 | main = defaultMain tests 102 | --------------------------------------------------------------------------------