├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── go.mod ├── go.sum ├── main.go └── pkg ├── command ├── command.go └── torrent │ ├── command.go │ ├── create.go │ ├── download.go │ ├── peers.go │ └── showinfo.go └── helper └── unit.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | 26 | # Intellij IDE 27 | .idea/ 28 | *.iml 29 | 30 | # VS Code 31 | .vscode/ 32 | bttools 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Golang Env Variables 2 | GO111MODULE=on 3 | GOSUMDB=sum.golang.google.cn 4 | GOPROXY=https://goproxy.cn,direct 5 | 6 | # Build Version Information 7 | COMMIT=$(shell git rev-parse HEAD 2>/dev/null) 8 | VERSION=$(shell git describe --tags 2>/dev/null) 9 | BUILD_DATE=$(shell date +"%s") 10 | 11 | BUILD_FLAGS_DATE=-X github.com/xgfone/gover.BuildTime=$(BUILD_DATE) 12 | BUILD_FLAGS_COMMIT=-X github.com/xgfone/gover.Commit=$(COMMIT) 13 | BUILD_FLAGS_VERSION=-X github.com/xgfone/gover.Version=$(VERSION) 14 | BUILD_FLAGS_X=$(BUILD_FLAGS_DATE) $(BUILD_FLAGS_COMMIT) $(BUILD_FLAGS_VERSION) 15 | 16 | .PHONY: all install build download 17 | all: build 18 | 19 | install: download 20 | go install -ldflags "-w $(BUILD_FLAGS_X)" 21 | 22 | build: download 23 | go build -ldflags "-w $(BUILD_FLAGS_X)" 24 | 25 | download: 26 | go mod download 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # bttools 2 | 3 | A command tool collection about BitTorrent. And you can consider it as the example of the development library [`bt`](https://github.com/xgfone/bt). 4 | 5 | ## 1 Install 6 | 7 | ```shell 8 | $ make 9 | ``` 10 | 11 | ## 2 Commands 12 | 13 | ### 2.1 Command `torrent` 14 | 15 | ```shell 16 | $ bttools torrent -h 17 | NAME: 18 | bttools torrent - The torrent tools 19 | 20 | USAGE: 21 | bttools torrent command [command options] [arguments...] 22 | 23 | COMMANDS: 24 | create Generate a .torrent file from a file or directory 25 | download Download the file from the remote peers by the .torrent file 26 | getpeers Get the peers of the torrent from the tracker 27 | showinfo Print the metainfo information of the .torrent file and exit 28 | help, h Shows a list of commands or help for one command 29 | 30 | OPTIONS: 31 | --help, -h show help 32 | ``` 33 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/xgfone/bttools 2 | 3 | require ( 4 | github.com/urfave/cli/v2 v2.24.4 5 | github.com/xgfone/bt v0.5.0 6 | github.com/xgfone/gover v0.4.0 7 | ) 8 | 9 | go 1.15 10 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= 2 | github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= 3 | github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= 4 | github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= 5 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 6 | github.com/urfave/cli/v2 v2.24.4 h1:0gyJJEBYtCV87zI/x2nZCPyDxD51K6xM8SkwjHFCNEU= 7 | github.com/urfave/cli/v2 v2.24.4/go.mod h1:GHupkWPMM0M/sj1a2b4wUrWBPzazNrIjouW6fmdJLxc= 8 | github.com/xgfone/bt v0.5.0 h1:mIJr+N3b3WHqu0PIYX4/IiiuqSbKMvcErx01UVEB0aU= 9 | github.com/xgfone/bt v0.5.0/go.mod h1:/GuvKo3WdkvlVahN84cjVWyia9ZJoxx/3BFIFZ5eGI4= 10 | github.com/xgfone/gover v0.4.0 h1:+4n+7pp79Dd1csfrv4Qh1OCdBMYBJ2b4VoweKK3Eobk= 11 | github.com/xgfone/gover v0.4.0/go.mod h1:yqAjNjXWuDib6SYKFvCdZY13nxkxKRNwIEjNPQFKWHw= 12 | github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= 13 | github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= 14 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 15 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 16 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 xgfone 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package main 16 | 17 | import ( 18 | "fmt" 19 | "os" 20 | 21 | "github.com/urfave/cli/v2" 22 | "github.com/xgfone/bttools/pkg/command" 23 | "github.com/xgfone/gover" 24 | ) 25 | 26 | func printVersion(c *cli.Context) { 27 | fmt.Fprintln(c.App.Writer, c.App.Version) 28 | } 29 | 30 | func main() { 31 | app := cli.NewApp() 32 | app.Usage = "A BitTorrent Tools" 33 | app.Version = gover.Version 34 | app.Commands = command.Commands 35 | app.EnableBashCompletion = true 36 | cli.VersionPrinter = printVersion 37 | if err := app.Run(os.Args); err != nil { 38 | fmt.Println(err) 39 | os.Exit(1) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /pkg/command/command.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 xgfone 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Package command is used to collect all the commands. 16 | package command 17 | 18 | import ( 19 | "github.com/urfave/cli/v2" 20 | "github.com/xgfone/bttools/pkg/command/torrent" 21 | ) 22 | 23 | // Commands is the set of all the sub-commands. 24 | var Commands []*cli.Command 25 | 26 | // RegisterCmd registers the command as the sub-command of the root. 27 | func RegisterCmd(cmd *cli.Command) { 28 | Commands = append(Commands, cmd) 29 | } 30 | 31 | func init() { 32 | RegisterCmd(torrent.Command) 33 | } 34 | -------------------------------------------------------------------------------- /pkg/command/torrent/command.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 xgfone 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Package torrent provides the sub-commands about torrent. 16 | package torrent 17 | 18 | import "github.com/urfave/cli/v2" 19 | 20 | var defaultTrackers = []string{"udp://tracker.openbittorrent.com:80/announce"} 21 | 22 | // Command is the sub-command torrent. 23 | var Command = &cli.Command{ 24 | Name: "torrent", 25 | Usage: "The torrent tools", 26 | } 27 | 28 | // registerCmd registers the command as the sub-command of the root. 29 | func registerCmd(cmd *cli.Command) { 30 | Command.Subcommands = append(Command.Subcommands, cmd) 31 | } 32 | -------------------------------------------------------------------------------- /pkg/command/torrent/create.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 xgfone 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package torrent 16 | 17 | import ( 18 | "bytes" 19 | "fmt" 20 | "io/ioutil" 21 | "path/filepath" 22 | "time" 23 | 24 | "github.com/urfave/cli/v2" 25 | "github.com/xgfone/bt/bencode" 26 | "github.com/xgfone/bt/metainfo" 27 | ) 28 | 29 | func init() { registerCmd(createCmd) } 30 | 31 | var createCmd = &cli.Command{ 32 | Name: "create", 33 | Usage: "Generate a .torrent file from a file or directory", 34 | ArgsUsage: "[ ...]", 35 | Flags: []cli.Flag{ 36 | &cli.BoolFlag{ 37 | Name: "no-date", 38 | Usage: "Leave the date field unset", 39 | }, 40 | &cli.StringSliceFlag{ 41 | Name: "webseed", 42 | Usage: "List of possible webseed URLs to use", 43 | }, 44 | &cli.StringSliceFlag{ 45 | Name: "announce", 46 | Value: cli.NewStringSlice(defaultTrackers...), 47 | Usage: "List of announce URLs to use", 48 | }, 49 | &cli.StringSliceFlag{ 50 | Name: "dhtnode", 51 | Usage: "List of the DHT nodes", 52 | }, 53 | &cli.StringFlag{ 54 | Name: "comment", 55 | Aliases: []string{"c"}, 56 | Value: "", 57 | Usage: "Add a comment to the torrent file", 58 | }, 59 | &cli.StringFlag{ 60 | Name: "creator", 61 | Value: "", 62 | Usage: "The creator to create the torrent", 63 | }, 64 | &cli.StringFlag{ 65 | Name: "output", 66 | Aliases: []string{"o"}, 67 | Value: "", 68 | Usage: "The path of .torrent file to be output", 69 | }, 70 | &cli.StringFlag{ 71 | Name: "name", 72 | Aliases: []string{"n"}, 73 | Value: "", 74 | Usage: "The name of the torrent", 75 | }, 76 | &cli.Int64Flag{ 77 | Name: "length", 78 | Value: 256, 79 | Usage: "Piece length to use in kilobytes, default is 256. mktorrent syntax(powers of 2, 15-32) are also supported", 80 | }, 81 | }, 82 | Action: func(ctx *cli.Context) (err error) { 83 | dirs := ctx.Args().Slice() 84 | if len(dirs) == 0 { 85 | dirs = []string{"."} 86 | } 87 | 88 | mi := metainfo.MetaInfo{ 89 | Comment: ctx.String("comment"), 90 | CreatedBy: ctx.String("creator"), 91 | } 92 | 93 | if !ctx.Bool("no-date") { 94 | mi.CreationDate = time.Now().Unix() 95 | } 96 | 97 | switch announces := ctx.StringSlice("announce"); len(announces) { 98 | case 0: 99 | case 1: 100 | mi.Announce = announces[0] 101 | default: 102 | mi.AnnounceList = metainfo.AnnounceList{announces} 103 | } 104 | 105 | for _, seed := range ctx.StringSlice("webseed") { 106 | mi.URLList = append(mi.URLList, seed) 107 | } 108 | for _, node := range ctx.StringSlice("dhtnode") { 109 | hostaddr, err := metainfo.ParseHostAddr(node) 110 | if err != nil { 111 | return err 112 | } 113 | mi.Nodes = append(mi.Nodes, hostaddr) 114 | } 115 | 116 | var pieceLength int64 117 | if length := ctx.Int64("length"); length < 64 { 118 | pieceLength = length ^ 2 119 | } else { 120 | pieceLength = length * 1024 121 | } 122 | 123 | name := ctx.String("name") 124 | if len(dirs) > 1 { 125 | name = "" 126 | } 127 | 128 | mis := make([]metainfo.MetaInfo, len(dirs)) 129 | for i, dir := range dirs { 130 | mis[i] = mi 131 | err = updateMetaInfo(&mis[i], dir, name, pieceLength) 132 | if err != nil { 133 | return 134 | } 135 | } 136 | 137 | output := ctx.String("output") 138 | for _, mi := range mis { 139 | filename := filepath.Join(output, mi.InfoHash().String()+".torrent") 140 | err = outputMetaInfo(mi, filename) 141 | if err != nil { 142 | return 143 | } 144 | 145 | fmt.Printf("successfully create the .torrent file to %s\n", filename) 146 | } 147 | 148 | return nil 149 | }, 150 | } 151 | 152 | func updateMetaInfo(mi *metainfo.MetaInfo, dir, name string, pieceLength int64) (err error) { 153 | dir, err = filepath.Abs(dir) 154 | if err != nil { 155 | return 156 | } 157 | 158 | info, err := metainfo.NewInfoFromFilePath(dir, pieceLength) 159 | if err != nil { 160 | return err 161 | } 162 | 163 | if name != "" { 164 | info.Name = name 165 | } 166 | 167 | mi.InfoBytes, err = bencode.EncodeBytes(info) 168 | return 169 | } 170 | 171 | func outputMetaInfo(mi metainfo.MetaInfo, filename string) (err error) { 172 | buf := bytes.NewBuffer(make([]byte, 0, 16*32)) 173 | if err = mi.Write(buf); err == nil { 174 | err = ioutil.WriteFile(filename, buf.Bytes(), 0600) 175 | } 176 | return 177 | } 178 | -------------------------------------------------------------------------------- /pkg/command/torrent/download.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 xgfone 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package torrent 16 | 17 | import ( 18 | "context" 19 | "crypto/sha1" 20 | "fmt" 21 | "path/filepath" 22 | "sync" 23 | "time" 24 | 25 | "github.com/urfave/cli/v2" 26 | "github.com/xgfone/bt/downloader" 27 | "github.com/xgfone/bt/metainfo" 28 | pp "github.com/xgfone/bt/peerprotocol" 29 | "github.com/xgfone/bt/tracker" 30 | ) 31 | 32 | func init() { registerCmd(downloadCmd) } 33 | 34 | var downloadCmd = &cli.Command{ 35 | Name: "download", 36 | Usage: "Download the file from the remote peers by the .torrent file", 37 | ArgsUsage: "", 38 | Flags: []cli.Flag{ 39 | &cli.StringSliceFlag{ 40 | Name: "tracker", 41 | Value: cli.NewStringSlice(defaultTrackers...), 42 | Usage: "The URL of the default tracker", 43 | }, 44 | &cli.StringFlag{ 45 | Name: "output", 46 | Aliases: []string{"w"}, 47 | Value: "", 48 | Usage: "The output directory to save the torrent files", 49 | }, 50 | &cli.StringSliceFlag{ 51 | Name: "peer", 52 | Usage: "The address of the peers", 53 | }, 54 | }, 55 | 56 | Action: func(ctx *cli.Context) (err error) { 57 | args := ctx.Args().Slice() 58 | if len(args) != 1 { 59 | cli.ShowSubcommandHelpAndExit(ctx, 1) 60 | } 61 | 62 | mi, err := metainfo.LoadFromFile(args[0]) 63 | if err != nil { 64 | return 65 | } 66 | 67 | info, err := mi.Info() 68 | if err != nil { 69 | return 70 | } 71 | 72 | infohash := mi.InfoHash() 73 | nodeid := metainfo.NewRandomHash() 74 | 75 | peers := ctx.StringSlice("peer") 76 | if len(peers) == 0 { 77 | trackers := mi.Announces().Unique() 78 | if len(trackers) == 0 { 79 | trackers = []string{ctx.String("tracker")} 80 | } 81 | 82 | peers, err = getPeersFromTrackers(infohash, nodeid, info, trackers) 83 | if err != nil { 84 | return 85 | } 86 | 87 | if len(peers) == 0 { 88 | fmt.Println("no found peers") 89 | return 90 | } 91 | } 92 | 93 | c, cancel := context.WithCancel(context.Background()) 94 | defer cancel() 95 | 96 | tasks := make(chan metainfo.Piece, len(info.Pieces)) 97 | for i := range info.Pieces { 98 | tasks <- info.Piece(i) 99 | } 100 | 101 | wg := new(sync.WaitGroup) 102 | wg.Add(len(peers)) 103 | results := make(chan downloadResult) 104 | for _, peer := range peers { 105 | go startDownloadWorker(c, wg, nodeid, infohash, peer, tasks, results) 106 | } 107 | go func() { 108 | wg.Wait() 109 | fmt.Println("no peer workers and exit.") 110 | cancel() 111 | }() 112 | 113 | outputdir := ctx.String("output") 114 | w := metainfo.NewWriter(outputdir, info, 0600) 115 | defer w.Close() 116 | 117 | var donePieces int 118 | LOOP: 119 | for { 120 | select { 121 | case <-c.Done(): 122 | break LOOP 123 | 124 | case result := <-results: 125 | _, err := w.WriteBlock(uint32(result.Index), 0, result.Data) 126 | if err != nil { 127 | fmt.Printf("fail to write the data of piece #%d\n", result.Index) 128 | break LOOP 129 | } 130 | 131 | donePieces++ 132 | total := info.CountPieces() 133 | percent := 100 * float64(donePieces) / float64(total) 134 | fmt.Printf("(%0.2f) successfully download piece %d/%d \n", percent, donePieces, total) 135 | 136 | if donePieces >= total { 137 | fmt.Printf("the torrent file is saved at %s\n", filepath.Join(outputdir, info.Name)) 138 | break LOOP 139 | } 140 | } 141 | } 142 | 143 | return 144 | }, 145 | } 146 | 147 | func getPeersFromTrackers(infohash, nodeid metainfo.Hash, info metainfo.Info, trackers []string) (peers []string, err error) { 148 | c, cancel := context.WithTimeout(context.Background(), time.Second*10) 149 | defer cancel() 150 | 151 | totalLength := info.TotalLength() 152 | for _, t := range trackers { 153 | resp, err := tracker.GetPeers(c, t, nodeid, infohash, totalLength) 154 | if err != nil { 155 | fmt.Printf("fail to try tracker '%s': %v\n", t, err) 156 | continue 157 | } else if len(resp.Addresses) == 0 { 158 | fmt.Printf("WARNING: no peers from tracker '%s': incomplete=%d, complete=%d\n", 159 | t, resp.Leechers, resp.Seeders) 160 | continue 161 | } 162 | 163 | for _, addr := range resp.Addresses { 164 | peers = append(peers, addr.String()) 165 | } 166 | } 167 | return 168 | } 169 | 170 | type downloadResult struct { 171 | Index int 172 | Data []byte 173 | } 174 | 175 | func startDownloadWorker(ctx context.Context, wg *sync.WaitGroup, 176 | nodeid metainfo.Hash, infohash metainfo.Hash, addr string, 177 | tasks chan metainfo.Piece, results chan<- downloadResult) { 178 | defer wg.Done() 179 | 180 | conn, err := pp.NewPeerConnByDial(addr, nodeid, infohash, time.Second*3) 181 | if err != nil { 182 | fmt.Printf("fail to connect to the peer '%s': %v\n", addr, err) 183 | return 184 | } 185 | defer conn.Close() 186 | 187 | if err = conn.Handshake(); err != nil { 188 | fmt.Printf("fail to handshake with the peer '%s': %v\n", addr, err) 189 | return 190 | } 191 | 192 | msg, err := conn.ReadMsg() 193 | if err != nil { 194 | fmt.Printf("fail to read the bitfield message from peer '%s': %v\n", addr, err) 195 | return 196 | } 197 | 198 | if msg.Type != pp.MTypeBitField { 199 | fmt.Printf("the first msg from peer '%s' after handshake is not bitfield: msgtype=%s\n", addr, msg.Type.String()) 200 | return 201 | } 202 | conn.BitField = msg.BitField 203 | 204 | // Notice the peer that we can recieve the data. 205 | conn.SetUnchoked() 206 | conn.SetInterested() 207 | 208 | for { 209 | select { 210 | case <-ctx.Done(): 211 | return 212 | 213 | case piece := <-tasks: 214 | index := uint32(piece.Index()) 215 | 216 | // Check whether the peer has the piece. 217 | if !conn.PeerHasPiece(index) { 218 | tasks <- piece 219 | continue 220 | } 221 | 222 | // Try to download the piece. 223 | data := make([]byte, piece.Length()) 224 | err = tryDownloadPiece(conn, 0, piece, data) 225 | if err != nil { 226 | fmt.Printf("fail to download piece #%d: %v\n", index, err) 227 | return 228 | } 229 | 230 | // Chech the hash of piece. 231 | if hash := sha1.Sum(data); piece.Hash() != hash { 232 | fmt.Printf("piece #%d expects hash %s, but got %x\n", index, piece.Hash().String(), hash) 233 | tasks <- piece 234 | continue 235 | } 236 | 237 | conn.SendHave(index) 238 | results <- downloadResult{Index: piece.Index(), Data: data} 239 | } 240 | } 241 | } 242 | 243 | func tryDownloadPiece(conn *pp.PeerConn, pieceNum int, piece metainfo.Piece, data []byte) (err error) { 244 | conn.SetTimeout(time.Minute) 245 | defer conn.SetTimeout(0) 246 | 247 | fmt.Printf("start to try download piece #%d\n", piece.Index()) 248 | 249 | var downloaded, offset, backoff int 250 | for length := int(piece.Length()); downloaded < length; { 251 | if !conn.PeerChoked { 252 | if backoff < 5 && offset < length { 253 | blockSize := metainfo.BlockSize 254 | if rest := length - offset; rest < blockSize { 255 | blockSize = rest 256 | } 257 | 258 | err = conn.SendRequest(uint32(piece.Index()), uint32(offset), uint32(blockSize)) 259 | if err != nil { 260 | return 261 | } 262 | 263 | backoff++ 264 | offset += blockSize 265 | } 266 | } 267 | 268 | msg, err := conn.ReadMsg() 269 | if err != nil { 270 | return err 271 | } else if msg.Keepalive { 272 | continue 273 | } 274 | 275 | handler := downloader.NewBlockDownloadHandler(pieceNum, nil, func(i, o uint32, b []byte) error { 276 | if index := piece.Index(); index != int(i) { 277 | return fmt.Errorf("expect the data of index %d, but got index %d", index, i) 278 | } else if int(o) >= len(data) { 279 | return fmt.Errorf("got an unknown piece block data") 280 | } 281 | 282 | copy(data[o:], b) 283 | downloaded += len(b) 284 | backoff-- 285 | return nil 286 | }) 287 | 288 | err = conn.HandleMessage(msg, bep3Handler{handler}) 289 | if err != nil { 290 | return err 291 | } 292 | } 293 | 294 | return 295 | } 296 | 297 | type bep3Handler struct { 298 | downloader.BlockDownloadHandler 299 | } 300 | 301 | func (h bep3Handler) OnMessage(conn *pp.PeerConn, msg pp.Message) error { 302 | fmt.Printf("recieved a unhandled torrent message: type=%s, raddr=%s", msg.Type, conn.RemoteAddr()) 303 | return nil 304 | } 305 | -------------------------------------------------------------------------------- /pkg/command/torrent/peers.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 xgfone 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package torrent 16 | 17 | import ( 18 | "context" 19 | "fmt" 20 | "time" 21 | 22 | "github.com/urfave/cli/v2" 23 | "github.com/xgfone/bt/metainfo" 24 | "github.com/xgfone/bt/tracker" 25 | ) 26 | 27 | func init() { registerCmd(getpeersCmd) } 28 | 29 | var getpeersCmd = &cli.Command{ 30 | Name: "getpeers", 31 | Usage: "Get the peers of the torrent from the tracker", 32 | ArgsUsage: "", 33 | Flags: []cli.Flag{ 34 | &cli.StringSliceFlag{ 35 | Name: "tracker", 36 | Value: cli.NewStringSlice(defaultTrackers...), 37 | Usage: "The URL of the default tracker", 38 | }, 39 | &cli.DurationFlag{ 40 | Name: "timeout", 41 | Value: time.Second * 10, 42 | Usage: "The timeout to get peers from the tracker", 43 | }, 44 | }, 45 | 46 | Action: func(ctx *cli.Context) (err error) { 47 | args := ctx.Args().Slice() 48 | if len(args) != 1 { 49 | cli.ShowCommandHelpAndExit(ctx, "getpeers", 1) 50 | } 51 | 52 | mi, err := metainfo.LoadFromFile(args[0]) 53 | if err != nil { 54 | return 55 | } 56 | 57 | info, err := mi.Info() 58 | if err != nil { 59 | return 60 | } 61 | 62 | trackers := mi.Announces().Unique() 63 | if len(trackers) == 0 { 64 | trackers = ctx.StringSlice("tracker") 65 | } 66 | 67 | timeout := ctx.Duration("timeout") 68 | c, cancel := context.WithTimeout(context.Background(), timeout) 69 | defer cancel() 70 | 71 | infohash := mi.InfoHash() 72 | totalLength := info.TotalLength() 73 | nodeid := metainfo.NewRandomHash() 74 | for i, t := range trackers { 75 | resp, err := tracker.GetPeers(c, t, nodeid, infohash, totalLength) 76 | if err != nil { 77 | fmt.Printf("fail to try tracker '%s': %v\n", t, err) 78 | continue 79 | } else if len(resp.Addresses) == 0 { 80 | fmt.Printf("WARNING: no peers from tracker '%s': incomplete=%d, complete=%d\n", 81 | t, resp.Leechers, resp.Seeders) 82 | continue 83 | } 84 | 85 | if i > 0 { 86 | fmt.Println() 87 | } 88 | 89 | fmt.Printf("Tracker %s:\n", t) 90 | fmt.Printf(" Interval: %ds\n", resp.Interval) 91 | fmt.Printf(" Complete: %d\n", resp.Seeders) 92 | fmt.Printf(" Incomplete: %d\n", resp.Leechers) 93 | fmt.Printf(" Peers:\n") 94 | for _, addr := range resp.Addresses { 95 | fmt.Printf(" %s\n", addr.String()) 96 | } 97 | } 98 | 99 | return 100 | }, 101 | } 102 | -------------------------------------------------------------------------------- /pkg/command/torrent/showinfo.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 xgfone 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package torrent 16 | 17 | import ( 18 | "fmt" 19 | "path/filepath" 20 | "reflect" 21 | "time" 22 | 23 | "github.com/urfave/cli/v2" 24 | "github.com/xgfone/bt/metainfo" 25 | "github.com/xgfone/bttools/pkg/helper" 26 | ) 27 | 28 | func init() { 29 | registerCmd(&cli.Command{ 30 | Name: "showinfo", 31 | Usage: "Print the metainfo information of the .torrent file and exit", 32 | ArgsUsage: " [TORRENT_FILES_PERTTERN ...]", 33 | Action: func(ctx *cli.Context) error { 34 | return printTorrentFiles(ctx.Args().Slice()) 35 | }, 36 | }) 37 | } 38 | 39 | func printTorrentFiles(patterns []string) (err error) { 40 | // Get all the torrent files 41 | files := make([]string, 0, len(patterns)) 42 | for _, s := range patterns { 43 | ss, err := filepath.Glob(s) 44 | if err != nil { 45 | return err 46 | } 47 | files = append(files, ss...) 48 | } 49 | 50 | for i, file := range files { 51 | if i > 0 { 52 | fmt.Println() 53 | } 54 | 55 | err = printTorrentFile(file) 56 | if err != nil { 57 | return 58 | } 59 | } 60 | 61 | return 62 | } 63 | 64 | func printTorrentFile(filename string) (err error) { 65 | mi, err := metainfo.LoadFromFile(filename) 66 | if err != nil { 67 | return fmt.Errorf("fail to load the torrent file '%s': %w", filename, err) 68 | } 69 | 70 | info, err := mi.Info() 71 | if err != nil { 72 | return fmt.Errorf("fail to decode metainfo of '%s': %s", filename, err) 73 | } 74 | 75 | infohash := mi.InfoHash() 76 | fmt.Printf("Magnet: %s\n", mi.Magnet(info.Name, infohash).String()) 77 | fmt.Printf("InfoHash: %s\n", infohash) 78 | printValue("Encoding: ", mi.Encoding) 79 | printValue("CreatedBy: ", mi.CreatedBy) 80 | printValue("CreationDate: ", time.Unix(mi.CreationDate, 0).Format(time.RFC3339)) 81 | printValue("Comment: ", mi.Comment) 82 | printTrackers(mi) 83 | printDHTNodes(mi) 84 | printURLList(mi) 85 | 86 | // Print the info part 87 | fmt.Println("Info:") 88 | fmt.Printf(" Name: %s\n", info.Name) 89 | fmt.Printf(" TotalLength: %s\n", helper.FormatSize(info.TotalLength())) 90 | fmt.Printf(" PieceLength: %s\n", helper.FormatSize(info.PieceLength)) 91 | fmt.Printf(" PieceNumber: %d\n", info.CountPieces()) 92 | printFiles(" ", info) 93 | 94 | return 95 | } 96 | 97 | func printValue(name string, v interface{}) { 98 | if !reflect.ValueOf(v).IsZero() { 99 | fmt.Printf("%s%v\n", name, v) 100 | } 101 | } 102 | 103 | func printTrackers(mi metainfo.MetaInfo) { 104 | announces := mi.Announces().Unique() 105 | if len(announces) == 0 { 106 | return 107 | } 108 | 109 | fmt.Println("Trackers:") 110 | for _, s := range announces { 111 | printValue(" ", s) 112 | } 113 | } 114 | 115 | func printDHTNodes(mi metainfo.MetaInfo) { 116 | if len(mi.Nodes) == 0 { 117 | return 118 | } 119 | 120 | fmt.Println("DHT Nodes:") 121 | for _, n := range mi.Nodes { 122 | printValue(" ", n) 123 | } 124 | } 125 | 126 | func printURLList(mi metainfo.MetaInfo) { 127 | if len(mi.URLList) == 0 { 128 | return 129 | } 130 | 131 | fmt.Println("WebSeed URLs:") 132 | for _, s := range mi.URLList { 133 | printValue(" ", s) 134 | } 135 | } 136 | 137 | func printFiles(prefix string, info metainfo.Info) { 138 | if !info.IsDir() { 139 | return 140 | } 141 | 142 | fmt.Printf("%sFiles:\n", prefix) 143 | for i, file := range info.AllFiles() { 144 | if i > 0 { 145 | fmt.Println() 146 | } 147 | 148 | fmt.Printf("%s Path: %s\n", prefix, file.Path(info)) 149 | fmt.Printf("%s Length: %s\n", prefix, helper.FormatSize(file.Length)) 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /pkg/helper/unit.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 xgfone 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Package helper provides some convenient helpful functions. 16 | package helper 17 | 18 | import ( 19 | "fmt" 20 | "strconv" 21 | ) 22 | 23 | const ( 24 | kb = 1024 25 | mb = kb * 1024 26 | gb = mb * 1024 27 | tb = gb * 1024 28 | pb = tb * 1024 29 | ) 30 | 31 | // FormatSize formats the size followed by the unit. 32 | func FormatSize(size int64) string { 33 | var base int64 34 | var unit string 35 | switch { 36 | case size < kb: 37 | return strconv.FormatInt(size, 10) 38 | 39 | case size < mb: 40 | base = kb 41 | unit = "KB" 42 | 43 | case size < gb: 44 | base = mb 45 | unit = "MB" 46 | 47 | case size < tb: 48 | base = gb 49 | unit = "GB" 50 | 51 | case size < pb: 52 | base = tb 53 | unit = "TB" 54 | 55 | default: 56 | base = pb 57 | unit = "PB" 58 | } 59 | 60 | if size%base == 0 { 61 | return fmt.Sprintf("%.0f%s", float64(size)/float64(base), unit) 62 | } 63 | return fmt.Sprintf("%.2f%s", float64(size)/float64(base), unit) 64 | } 65 | --------------------------------------------------------------------------------