├── .gitignore ├── .travis.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── Makefile ├── README.md ├── main.go └── pluto ├── fixtures └── testfile ├── pluto.go ├── pluto_test.go └── worker.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | 7 | # Test binary, build with `go test -c` 8 | *.test 9 | 10 | # Output of the go coverage tool, specifically when used with LiteIDE 11 | *.out 12 | 13 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 14 | .glide/ 15 | test 16 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.7.x 5 | - 1.8.x 6 | - 1.9.x 7 | - master 8 | 9 | install: 10 | - go get github.com/dustin/go-humanize 11 | - go get github.com/jessevdk/go-flags -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at ishanjain28@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | When contributing to this repository, please first discuss the change you wish to make via issue, 4 | email, or any other method with the owners of this repository before making a change. 5 | 6 | Please note we have a code of conduct, please follow it in all your interactions with the project. 7 | 8 | ## Pull Request Process 9 | 10 | 1. Ensure any install or build dependencies are removed before the end of the layer when doing a 11 | build. 12 | 2. Update the README.md with details of changes to the interface, this includes new environment 13 | variables, exposed ports, useful file locations and container parameters. 14 | 3. Increase the version numbers in any examples files and the README.md to the new version that this 15 | Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/). 16 | 4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you 17 | do not have permission to do that, you may request the second reviewer to merge it for you. 18 | 19 | ## Code of Conduct 20 | 21 | ### Our Pledge 22 | 23 | In the interest of fostering an open and welcoming environment, we as 24 | contributors and maintainers pledge to making participation in our project and 25 | our community a harassment-free experience for everyone, regardless of age, body 26 | size, disability, ethnicity, gender identity and expression, level of experience, 27 | nationality, personal appearance, race, religion, or sexual identity and 28 | orientation. 29 | 30 | ### Our Standards 31 | 32 | Examples of behavior that contributes to creating a positive environment 33 | include: 34 | 35 | * Using welcoming and inclusive language 36 | * Being respectful of differing viewpoints and experiences 37 | * Gracefully accepting constructive criticism 38 | * Focusing on what is best for the community 39 | * Showing empathy towards other community members 40 | 41 | Examples of unacceptable behavior by participants include: 42 | 43 | * The use of sexualized language or imagery and unwelcome sexual attention or 44 | advances 45 | * Trolling, insulting/derogatory comments, and personal or political attacks 46 | * Public or private harassment 47 | * Publishing others' private information, such as a physical or electronic 48 | address, without explicit permission 49 | * Other conduct which could reasonably be considered inappropriate in a 50 | professional setting 51 | 52 | ### Our Responsibilities 53 | 54 | Project maintainers are responsible for clarifying the standards of acceptable 55 | behavior and are expected to take appropriate and fair corrective action in 56 | response to any instances of unacceptable behavior. 57 | 58 | Project maintainers have the right and responsibility to remove, edit, or 59 | reject comments, commits, code, wiki edits, issues, and other contributions 60 | that are not aligned to this Code of Conduct, or to ban temporarily or 61 | permanently any contributor for other behaviors that they deem inappropriate, 62 | threatening, offensive, or harmful. 63 | 64 | ### Scope 65 | 66 | This Code of Conduct applies both within project spaces and in public spaces 67 | when an individual is representing the project or its community. Examples of 68 | representing a project or community include using an official project e-mail 69 | address, posting via an official social media account, or acting as an appointed 70 | representative at an online or offline event. Representation of a project may be 71 | further defined and clarified by project maintainers. 72 | 73 | ### Enforcement 74 | 75 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 76 | reported by contacting the project team at [INSERT EMAIL ADDRESS]. All 77 | complaints will be reviewed and investigated and will result in a response that 78 | is deemed necessary and appropriate to the circumstances. The project team is 79 | obligated to maintain confidentiality with regard to the reporter of an incident. 80 | Further details of specific enforcement policies may be posted separately. 81 | 82 | Project maintainers who do not follow or enforce the Code of Conduct in good 83 | faith may face temporary or permanent repercussions as determined by other 84 | members of the project's leadership. 85 | 86 | ### Attribution 87 | 88 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 89 | available at [http://contributor-covenant.org/version/1/4][version] 90 | 91 | [homepage]: http://contributor-covenant.org 92 | [version]: http://contributor-covenant.org/version/1/4/ 93 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PACKAGE=pluto 2 | VERSION=`git describe --tags` 3 | BUILD=`date +%FT%T%z` 4 | 5 | 6 | LDFLAGS=-ldflags "-w -s -X main.Version=${VERSION} -X main.Build=${BUILD}" 7 | 8 | ARCH_LINUX = $(PACKAGE)-linux-amd64 \ 9 | $(PACKAGE)-linux-arm64 \ 10 | $(PACKAGE)-linux-386 11 | 12 | ARCH_WIN = $(PACKAGE)-windows-amd64.exe \ 13 | $(PACKAGE)-windows-386.exe 14 | 15 | TARGET = $(PACKAGE)-linux-amd64 16 | 17 | # TODO: Must write a configure.ac to find target for user end. 18 | # then we can use: 19 | # all: default 20 | # default: $(TARGET) 21 | 22 | all: default 23 | default: $(TARGET) 24 | 25 | dist: dist-linux dist-windows 26 | 27 | dist-windows: $(ARCH_WIN) 28 | dist-linux: $(ARCH_LINUX) 29 | 30 | $(PACKAGE)-linux-arm64: 31 | GOOS=linux \ 32 | GOARCH=arm64 \ 33 | go build ${LDFLAGS} -o=$@ 34 | 35 | $(PACKAGE)-linux-amd64: 36 | GOOS=linux \ 37 | GOARCH=amd64 \ 38 | go build ${LDFLAGS} -o=$@ 39 | 40 | $(PACKAGE)-linux-386: 41 | GOOS=linux \ 42 | GOARCH=386 \ 43 | go build ${LDFLAGS} -o=$@ 44 | 45 | $(PACKAGE)-windows-amd64.exe: 46 | GOOS=windows \ 47 | GOARCH=amd64 \ 48 | go build ${LDFLAGS} -o=$@ 49 | 50 | $(PACKAGE)-windows-386.exe: 51 | GOOS=windows \ 52 | GOARCH=386 \ 53 | go build ${LDFLAGS} -o=$@ 54 | 55 | dist-clean: 56 | rm -f $(ARCH_WIN) $(ARCH_LINUX) 57 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pluto 2 | A CLI and Library for super fast, Multi part downloads. 3 | 4 | Pluto is a Multipart File Downloader. It comes in form of a package and a CLI. It works by dividing the file into a given number of parts, Each part is given a range of bytes to download, As all the parts are downloading they are also written to the file in correct order. 5 | 6 | There are a lot of tool similar and better than Pluto but most of them have an upper limit of 16 or 32 parts whereas Pluto has no upper limit. 7 | 8 | [![GoDoc](https://godoc.org/github.com/ishanjain28/pluto/pluto?status.svg)](https://godoc.org/github.com/ishanjain28/pluto/pluto) 9 | [![Go Report Card](https://goreportcard.com/badge/github.com/ishanjain28/pluto)](https://goreportcard.com/report/github.com/ishanjain28/pluto) 10 | [![Build Status](https://travis-ci.org/ishanjain28/pluto.svg?branch=master)](https://travis-ci.org/ishanjain28/pluto) 11 | 12 | ## Features 13 | 14 | 1. Fast download speed. 15 | 2. Multi Part Downloading 16 | 3. High tolerance for low quality internet connection. 17 | 4. A Stats API that makes getting parameters like current download speed and number of bytes downloaded easier 18 | 5. Guarantees reliable file downloads 19 | 6. It can be used to download files from servers which require authorization in form of a value in Request Header. 20 | 7. It can load URLs from a file. 21 | 22 | 23 | ## Installation 24 | 25 | 1. You have a working Go Environment 26 | 27 | go get github.com/ishanjain28/pluto 28 | 29 | 2. You don't have a working Go Environment 30 | 1. See the [Releases](https://github.com/ishanjain28/pluto/releases) section for Precompiled Binaries 31 | 2. Download a binary for your platform 32 | 3. Put the binary in `/usr/bin` or `/usr/local/bin` on Unix like systems and add the path to binary to `PATH` variable on Windows. 33 | 4. Done. Now type `pluto -v` in terminal to see if it is installed correctly. :) 34 | 35 | 36 | ### CLI Example 37 | Usage: 38 | pluto [OPTIONS] [urls...] 39 | 40 | Application Options: 41 | --verbose Enable Verbose Mode 42 | -n, --connections= Number of concurrent connections 43 | --name= Path or Name of save file 44 | -f, --load-from-file= Load URLs from a file 45 | -H, --Headers= Headers to send with each request. Useful if a server requires some information in headers 46 | -v, --version Print Pluto Version and exit 47 | 48 | Help Options: 49 | -h, --help Show this help message 50 | 51 | ### Package Example: 52 | 53 | See cli.go for an example of this package 54 | 55 | 56 | ## Default Behaviours 57 | 58 | 1. When an error occurs in downloading stage of a part, It is automatically retried, unless there is an error that retrying won't fix. For example, If the server sends a 404, 400 or 500 HTTP response, It stop and return an error. 59 | 60 | 2. It now uses 256kb buffers instead of a 64kb buffer to reduce CPU Usage. 61 | 62 | 3. When a part download fails for reason that is recoverable(see 1) reason, Only the bytes that have not been downloaded yet are requested from server. 63 | 64 | 65 | ## Motivation 66 | 67 | Almost all Download Managers have an upper limit on number of parts. This is usually done to for the following reasons: 68 | 69 | 1. Prevent DDoS detection systems on servers from falsely marking the client's IP address as a hostile machine. 70 | 2. Prevent internet experience degradtion on other Machines on the same local network and in other applications on the same PC. 71 | 3. This is just a guess, But maybe People saw that after a certain limit increasing number of parts doesn't really increase anymore speed which is true but the 16/32 part limit is very low and much better speed can be achieved by increasing part limit upto 100 on a 50Mbit Connection. 72 | 73 | But when I am downloading a file from my private servers I need the absolute maximum speed and I could not find a good tool for it. So, I built one myself. A benchmark b/w Pluto, axel and aria2c will be added shortly. 74 | 75 | ## Future Plans 76 | 77 | 1. Pause and resume support. 78 | 2. Intelligent redistribution of remaining bytes when one of the connections finishes downloading data assigned to it. This would result in much better speed utilisation as it approaches the end of download. 79 | 80 | 81 | ##### Please use this package responsibly because it can cause all the bad things mentioned above and if you encounter any problems, Feel free to create an issue. 82 | 83 | # License 84 | 85 | GPLv2 86 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "context" 6 | "fmt" 7 | "io" 8 | "log" 9 | "net/url" 10 | "os" 11 | "os/signal" 12 | "path/filepath" 13 | "strings" 14 | "syscall" 15 | 16 | "github.com/ishanjain28/pluto/pluto" 17 | 18 | humanize "github.com/dustin/go-humanize" 19 | flag "github.com/jessevdk/go-flags" 20 | ) 21 | 22 | var Version string 23 | var Build string 24 | 25 | var options struct { 26 | Verbose bool `long:"verbose" description:"Enable Verbose Mode"` 27 | Connections uint `short:"n" long:"connections" default:"1" description:"Number of concurrent connections"` 28 | Name string `long:"name" description:"Path or Name of save file"` 29 | LoadFromFile string `short:"f" long:"load-from-file" description:"Load URLs from a file"` 30 | Headers []string `short:"H" long:"headers" description:"Headers to send with each request. Useful if a server requires some information in headers"` 31 | Version bool `short:"v" long:"version" description:"Print Pluto Version and exit"` 32 | urls []string 33 | } 34 | 35 | func parseArgs() error { 36 | args, err := flag.ParseArgs(&options, os.Args) 37 | if err != nil { 38 | return fmt.Errorf("error parsing args: %v", err) 39 | } 40 | 41 | args = args[1:] 42 | 43 | options.urls = []string{} 44 | 45 | if options.LoadFromFile != "" { 46 | f, err := os.OpenFile(options.LoadFromFile, os.O_RDONLY, 0x444) 47 | if err != nil { 48 | return fmt.Errorf("error in opening file %s: %v", options.LoadFromFile, err) 49 | } 50 | defer f.Close() 51 | reader := bufio.NewReader(f) 52 | 53 | for { 54 | str, err := reader.ReadString('\n') 55 | if err != nil { 56 | if err == io.EOF { 57 | break 58 | } 59 | return fmt.Errorf("error in reading file: %v", err) 60 | } 61 | u := str[:len(str)-1] 62 | if u != "" { 63 | options.urls = append(options.urls, u) 64 | } 65 | } 66 | 67 | fmt.Printf("queued %d urls\n", len(options.urls)) 68 | } else { 69 | for _, v := range args { 70 | if v != "" && v != "\n" { 71 | options.urls = append(options.urls, v) 72 | } 73 | } 74 | 75 | } 76 | if len(options.urls) == 0 { 77 | return fmt.Errorf("nothing to do. Please pass some url to fetch") 78 | } 79 | 80 | if options.Connections == 0 { 81 | return fmt.Errorf("connections should be > 0") 82 | } 83 | if len(options.urls) > 1 && options.Name != "" { 84 | return fmt.Errorf("it is not possible to specify 'name' with more than one url") 85 | } 86 | return nil 87 | } 88 | func main() { 89 | 90 | sig := make(chan os.Signal, 1) 91 | signal.Notify(sig, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) 92 | ctx, cancel := context.WithCancel(context.Background()) 93 | 94 | go func() { 95 | <-sig 96 | fmt.Printf("Interrupt Detected, Shutting Down.") 97 | cancel() 98 | }() 99 | 100 | err := parseArgs() 101 | if err != nil { 102 | log.Fatalf("error parsing args: %v", err) 103 | } 104 | 105 | if options.Version { 106 | fmt.Println("Pluto - A Fast Multipart File Downloader") 107 | fmt.Printf("Version: %s\n", Version) 108 | fmt.Printf("Build: %s\n", Build) 109 | return 110 | } 111 | 112 | UrlLoop: 113 | for _, v := range options.urls { 114 | select { 115 | case <-ctx.Done(): 116 | break UrlLoop 117 | default: 118 | } 119 | up, err := url.Parse(v) 120 | if err != nil { 121 | log.Printf("Invalid URL: %v", err) 122 | continue 123 | } 124 | p, err := pluto.New(up, options.Headers, options.Connections, options.Verbose) 125 | if err != nil { 126 | log.Fatalf("error creating pluto instance for url %s: %v\n", v, err) 127 | } 128 | 129 | go func() { 130 | if p.StatsChan == nil { 131 | return 132 | } 133 | 134 | for { 135 | select { 136 | case <-p.Finished: 137 | 138 | // Once download is finished, We don't need any data currently in channel. 139 | for range p.StatsChan { 140 | } 141 | 142 | break 143 | case v := <-p.StatsChan: 144 | os.Stdout.WriteString(fmt.Sprintf("\r%.2f%% - %s/%s - %s/s\r", float64(v.Downloaded)/float64(v.Size)*100, humanize.IBytes(v.Downloaded), humanize.IBytes(v.Size), humanize.IBytes(v.Speed))) 145 | os.Stdout.Sync() 146 | } 147 | } 148 | }() 149 | 150 | var fileName string 151 | if options.Name != "" { 152 | fileName = options.Name 153 | } else if p.MetaData.Name != "" { 154 | fileName = p.MetaData.Name 155 | } else { 156 | fileName = strings.Split(filepath.Base(up.String()), "?")[0] 157 | } 158 | fileName = strings.Replace(fileName, "/", "\\/", -1) 159 | writer, err := os.Create(fileName) 160 | if err != nil { 161 | log.Fatalf("unable to create file %s: %v\n", fileName, err) 162 | } 163 | defer writer.Close() 164 | 165 | if !p.MetaData.MultipartSupported && options.Connections > 1 { 166 | fmt.Printf("Downloading %s(%s) with 1 connection(Multipart downloads not supported)\n", fileName, humanize.Bytes(p.MetaData.Size)) 167 | } 168 | 169 | result, err := p.Download(ctx, writer) 170 | if err != nil { 171 | log.Printf("error downloading url %s: %v", v, err) 172 | } else { 173 | s := humanize.IBytes(result.Size) 174 | htime := result.TimeTaken.String() 175 | 176 | as := humanize.IBytes(uint64(result.AvgSpeed)) 177 | 178 | fmt.Printf("\nDownloaded %s in %s. Avg. Speed - %s/s\n", s, htime, as) 179 | fmt.Printf("File saved in %s\n", result.FileName) 180 | 181 | } 182 | 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /pluto/fixtures/testfile: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ishanjain28/pluto/2ef8b60460fb6ff4d8f921584f63ce71121f2140/pluto/fixtures/testfile -------------------------------------------------------------------------------- /pluto/pluto.go: -------------------------------------------------------------------------------- 1 | // Package pluto provides a way to download files at high speeds by using http ranged requests. 2 | package pluto 3 | 4 | import ( 5 | "context" 6 | "fmt" 7 | "io" 8 | "log" 9 | "net/http" 10 | "net/url" 11 | "path/filepath" 12 | "runtime" 13 | "strings" 14 | "sync" 15 | "sync/atomic" 16 | 17 | humanize "github.com/dustin/go-humanize" 18 | 19 | "time" 20 | ) 21 | 22 | var ( 23 | 24 | // ErrOverflow is when server sends more data than what was requested 25 | ErrOverflow = "error: Server sent extra bytes" 26 | ) 27 | 28 | // Stats is returned in a channel by Download function every 250ms and contains details like Current download speed in bytes/sec and amount of data Downloaded 29 | type Stats struct { 30 | Downloaded uint64 31 | Speed uint64 32 | Size uint64 33 | } 34 | 35 | type fileMetaData struct { 36 | url *url.URL 37 | Size uint64 38 | Name string 39 | MultipartSupported bool 40 | } 41 | 42 | // Pluto contains all the details that Download needs. 43 | // Connections is the number of connections to use to download a file 44 | // Verbose is to enable verbose mode. 45 | // Writer is the place where downloaded data is written. 46 | // Headers is any header that you may need to send to download the file. 47 | // StatsChan is a channel to which Stats are sent, It can be nil or a channel that can hold data of type *() 48 | type Pluto struct { 49 | StatsChan chan *Stats 50 | Finished chan struct{} 51 | connections uint 52 | verbose bool 53 | headers []string 54 | downloaded uint64 55 | MetaData fileMetaData 56 | startTime time.Time 57 | workers []*worker 58 | } 59 | 60 | //Result is the download results 61 | type Result struct { 62 | FileName string 63 | Size uint64 64 | AvgSpeed float64 65 | TimeTaken time.Duration 66 | } 67 | 68 | //New returns a pluto instance 69 | func New(up *url.URL, headers []string, connections uint, verbose bool) (*Pluto, error) { 70 | 71 | p := &Pluto{ 72 | connections: connections, 73 | headers: headers, 74 | verbose: verbose, 75 | StatsChan: make(chan *Stats), 76 | Finished: make(chan struct{}), 77 | } 78 | 79 | err := p.fetchMeta(up, headers) 80 | if err != nil { 81 | return nil, err 82 | } 83 | 84 | if !p.MetaData.MultipartSupported { 85 | p.connections = 1 86 | fmt.Printf("Downloading %s(%s) with %d connection\n", p.MetaData.Name, humanize.Bytes(p.MetaData.Size), p.connections) 87 | } else { 88 | p.connections = 1 89 | } 90 | 91 | return p, nil 92 | 93 | } 94 | 95 | // Download takes Config struct 96 | // then downloads the file by dividing it into given number of parts and downloading all parts concurrently. 97 | // If any error occurs in the downloading stage of any part, It'll check if the the program can recover from error by retrying download 98 | // And if an error occurs which the program can not recover from, it'll return that error 99 | func (p *Pluto) Download(ctx context.Context, w io.WriterAt) (*Result, error) { 100 | p.startTime = time.Now() 101 | // Limit number of CPUs it can use 102 | runtime.GOMAXPROCS(runtime.NumCPU() / 2) 103 | 104 | perPartLimit := p.MetaData.Size / uint64(p.connections) 105 | difference := p.MetaData.Size % uint64(p.connections) 106 | 107 | p.workers = make([]*worker, p.connections) 108 | 109 | for i := uint(0); i < p.connections; i++ { 110 | begin := perPartLimit * uint64(i) 111 | end := perPartLimit * (uint64(i) + 1) 112 | 113 | if i == p.connections-1 { 114 | end += difference 115 | } 116 | 117 | p.workers[i] = &worker{ 118 | begin: begin, 119 | end: end, 120 | url: p.MetaData.url, 121 | writer: w, 122 | headers: p.headers, 123 | verbose: p.verbose, 124 | ctx: ctx, 125 | } 126 | } 127 | 128 | err := p.startDownload() 129 | if err != nil { 130 | return nil, err 131 | } 132 | 133 | tt := time.Since(p.startTime) 134 | filename, err := filepath.Abs(p.MetaData.Name) 135 | if err != nil { 136 | log.Printf("unable to get absolute path for %s: %v", p.MetaData.Name, err) 137 | filename = p.MetaData.Name 138 | } 139 | 140 | r := &Result{ 141 | TimeTaken: tt, 142 | FileName: filename, 143 | Size: p.MetaData.Size, 144 | AvgSpeed: float64(p.MetaData.Size) / float64(tt.Seconds()), 145 | } 146 | 147 | close(p.Finished) 148 | return r, nil 149 | } 150 | 151 | func (p *Pluto) startDownload() error { 152 | 153 | var wg sync.WaitGroup 154 | wg.Add(len(p.workers)) 155 | var err error 156 | 157 | errdl := make(chan error, 1) 158 | errcopy := make(chan error, 1) 159 | 160 | var downloaded uint64 161 | 162 | // Stats system, It writes stats to the stats channel 163 | go func() { 164 | 165 | var oldSpeed uint64 166 | counter := 0 167 | for { 168 | 169 | dled := atomic.LoadUint64(&downloaded) 170 | speed := dled - p.downloaded 171 | 172 | if speed == 0 && counter < 4 { 173 | speed = oldSpeed 174 | counter++ 175 | } else { 176 | counter = 0 177 | } 178 | 179 | p.StatsChan <- &Stats{ 180 | Downloaded: p.downloaded, 181 | Speed: speed * 2, 182 | Size: p.MetaData.Size, 183 | } 184 | 185 | p.downloaded = dled 186 | oldSpeed = speed 187 | time.Sleep(500 * time.Millisecond) 188 | } 189 | }() 190 | 191 | for _, w := range p.workers { 192 | // This loop keeps trying to download a file if a recoverable error occurs 193 | go func(w *worker, wgroup *sync.WaitGroup, dl *uint64, cerr, dlerr chan error) { 194 | 195 | defer func() { 196 | 197 | wgroup.Done() 198 | cerr <- nil 199 | dlerr <- nil 200 | }() 201 | 202 | for { 203 | downloadPart, err := w.download() 204 | if err != nil { 205 | if err.Error() == "status code: 400" || err.Error() == "status code: 500" || err.Error() == ErrOverflow { 206 | cerr <- err 207 | return 208 | } 209 | 210 | if p.verbose { 211 | log.Println(err) 212 | } 213 | continue 214 | } 215 | 216 | d, err := w.copyAt(downloadPart, &downloaded) 217 | if err != nil { 218 | cerr <- fmt.Errorf("error copying data at offset %d: %v", w.begin, err) 219 | } 220 | 221 | if p.verbose { 222 | fmt.Printf("Copied %d bytes\n", d) 223 | } 224 | 225 | downloadPart.Close() 226 | break 227 | } 228 | 229 | }(w, &wg, &downloaded, errcopy, errdl) 230 | } 231 | 232 | err = <-errcopy 233 | if err != nil { 234 | return err 235 | } 236 | 237 | err = <-errdl 238 | if err != nil { 239 | return err 240 | } 241 | wg.Wait() 242 | return nil 243 | } 244 | 245 | func (p *Pluto) fetchMeta(u *url.URL, headers []string) error { 246 | 247 | req, err := http.NewRequest("HEAD", u.String(), nil) 248 | if err != nil { 249 | return fmt.Errorf("error in creating HEAD request: %v", err) 250 | } 251 | 252 | for _, v := range headers { 253 | vsp := strings.Index(v, ":") 254 | 255 | key := v[:vsp] 256 | value := v[vsp:] 257 | 258 | req.Header.Set(key, value) 259 | } 260 | 261 | client := &http.Client{} 262 | 263 | resp, err := client.Do(req) 264 | if err != nil { 265 | return fmt.Errorf("error in sending HEAD request: %v", err) 266 | } 267 | defer resp.Body.Close() 268 | 269 | if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent { 270 | return fmt.Errorf("status code is %d", resp.StatusCode) 271 | } 272 | 273 | size := resp.ContentLength 274 | if size == 0 { 275 | return fmt.Errorf("Incompatible URL, file size is 0") 276 | } 277 | 278 | msupported := false 279 | 280 | if resp.Header.Get("Accept-Range") != "" || resp.Header.Get("Accept-Ranges") != "" { 281 | msupported = true 282 | } 283 | 284 | resp, err = http.Get(u.String()) 285 | if err != nil { 286 | return fmt.Errorf("error in sending GET request: %v", err) 287 | } 288 | 289 | name := "" 290 | 291 | dispositionHeader := resp.Header.Get("Content-Disposition") 292 | 293 | if dispositionHeader != "" { 294 | cDispose := strings.Split(dispositionHeader, "filename=") 295 | 296 | if len(cDispose) > 0 { 297 | cdfilename := cDispose[1] 298 | cdfilename = cdfilename[1:] 299 | cdfilename = cdfilename[:len(cdfilename)-1] 300 | name = cdfilename 301 | } 302 | } 303 | 304 | resp.Body.Close() 305 | p.MetaData = fileMetaData{ 306 | Size: uint64(size), 307 | Name: name, 308 | url: u, 309 | MultipartSupported: msupported, 310 | } 311 | return nil 312 | } 313 | -------------------------------------------------------------------------------- /pluto/pluto_test.go: -------------------------------------------------------------------------------- 1 | package pluto_test 2 | 3 | import ( 4 | "context" 5 | "io/ioutil" 6 | "log" 7 | "net/http" 8 | "net/url" 9 | "os" 10 | "reflect" 11 | "testing" 12 | 13 | "github.com/ishanjain28/pluto/pluto" 14 | ) 15 | 16 | func setupHTTPServer() *http.Server { 17 | srv := &http.Server{Addr: "127.0.0.1:5050"} 18 | 19 | http.HandleFunc("/testfile", func(w http.ResponseWriter, r *http.Request) { 20 | http.ServeFile(w, r, "fixtures/testfile") 21 | }) 22 | go func() { 23 | err := srv.ListenAndServe() 24 | if err != nil { 25 | log.Printf("error setingup the httpServer: %v", err) 26 | } 27 | }() 28 | return srv 29 | } 30 | 31 | func TestMain(m *testing.M) { 32 | srv := setupHTTPServer() 33 | 34 | retCode := m.Run() 35 | srv.Shutdown(nil) 36 | 37 | os.Exit(retCode) 38 | } 39 | 40 | func TestFetchMeta(t *testing.T) { 41 | u, _ := url.Parse("http://127.0.0.1:5050/testfile") 42 | 43 | resp, err := http.Head(u.String()) 44 | if err != nil { 45 | t.Fatalf("error sending request: %v", err) 46 | 47 | } 48 | defer resp.Body.Close() 49 | p, err := pluto.New(u, []string{}, 1, false) 50 | if err != nil { 51 | t.Fatalf("unable to create pluto instance: %v", err) 52 | } 53 | 54 | if p.MetaData.Size != uint64(resp.ContentLength) { 55 | t.Fatalf("fetched metadata size does not match with the response.ContentLength") 56 | } 57 | } 58 | 59 | func TestDownload(t *testing.T) { 60 | u, _ := url.Parse("http://127.0.0.1:5050/testfile") 61 | p, err := pluto.New(u, []string{}, 1, false) 62 | if err != nil { 63 | t.Fatalf("unable to create pluto instance: %v", err) 64 | } 65 | f, err := ioutil.TempFile("/tmp", "pluto") 66 | if err != nil { 67 | t.Fatalf("unable to create temp file: %v", err) 68 | } 69 | defer f.Close() 70 | r, err := p.Download(context.Background(), f) 71 | if err != nil { 72 | t.Fatalf("unable to download file: %v", err) 73 | } 74 | t.Logf("Result: %v\n", r) 75 | download, err := ioutil.ReadAll(f) 76 | if err != nil { 77 | t.Fatalf("unable to read downloaded file: %v", err) 78 | } 79 | original, err := ioutil.ReadFile("fixtures/testfile") 80 | if err != nil { 81 | t.Fatalf("unable to read original file") 82 | } 83 | if !reflect.DeepEqual(download, original) { 84 | t.Errorf("downloaded file and original file are not equal!") 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /pluto/worker.go: -------------------------------------------------------------------------------- 1 | package pluto 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "io" 7 | "net/http" 8 | "net/url" 9 | "strings" 10 | "sync/atomic" 11 | ) 12 | 13 | type worker struct { 14 | begin uint64 15 | end uint64 16 | url *url.URL 17 | writer io.WriterAt 18 | headers []string 19 | verbose bool 20 | ctx context.Context 21 | } 22 | 23 | // copyAt reads 64 kilobytes from source and copies them to destination at a given offset 24 | func (w *worker) copyAt(src io.Reader, dlcounter *uint64) (uint64, error) { 25 | bufBytes := make([]byte, 256*1024) 26 | 27 | var bytesWritten uint64 28 | var err error 29 | 30 | for { 31 | nsr, serr := src.Read(bufBytes) 32 | if nsr > 0 { 33 | ndw, derr := w.writer.WriteAt(bufBytes[:nsr], int64(w.begin)) 34 | if ndw > 0 { 35 | u64ndw := uint64(ndw) 36 | w.begin += u64ndw 37 | bytesWritten += u64ndw 38 | atomic.AddUint64(dlcounter, u64ndw) 39 | } 40 | if derr != nil { 41 | err = derr 42 | break 43 | } 44 | if nsr != ndw { 45 | fmt.Printf("Short write error. Read: %d, Wrote: %d", nsr, ndw) 46 | err = io.ErrShortWrite 47 | break 48 | } 49 | } 50 | 51 | if serr != nil { 52 | if serr != io.EOF { 53 | err = serr 54 | } 55 | break 56 | } 57 | } 58 | 59 | return bytesWritten, err 60 | } 61 | 62 | func (w *worker) download() (io.ReadCloser, error) { 63 | 64 | client := &http.Client{} 65 | req, err := http.NewRequest("GET", w.url.String(), nil) 66 | if err != nil { 67 | return nil, fmt.Errorf("error in creating GET request: %v", err) 68 | } 69 | req = req.WithContext(w.ctx) 70 | req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", w.begin, w.end)) 71 | 72 | for _, v := range w.headers { 73 | vsp := strings.Index(v, ":") 74 | 75 | key := v[:vsp] 76 | value := v[vsp:] 77 | 78 | req.Header.Set(key, value) 79 | } 80 | 81 | resp, err := client.Do(req) 82 | if err != nil { 83 | 84 | if w.verbose { 85 | fmt.Printf("Requested Bytes %d in range %d-%d. Got %d bytes\n", w.end-w.begin, w.begin, w.end, resp.ContentLength) 86 | } 87 | 88 | return nil, fmt.Errorf("error in sending download request: %v", err) 89 | } 90 | 91 | if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent { 92 | return nil, fmt.Errorf("status code: %d", resp.StatusCode) 93 | } 94 | 95 | if uint64(resp.ContentLength) != (w.end - w.begin) { 96 | return nil, fmt.Errorf(ErrOverflow) 97 | } 98 | return resp.Body, nil 99 | } 100 | --------------------------------------------------------------------------------