From e90e6eaf1fd40bc43751700f3384cd3a5ee7cb58 Mon Sep 17 00:00:00 2001 From: Antonio Navarro Perez Date: Thu, 9 Dec 2021 17:45:25 +0100 Subject: [PATCH] Improve server. (#103) --- cmd/distribyted/main.go | 7 ++++++- torrent/client.go | 4 ++-- torrent/id.go | 30 ++++++++++++++++++++++++++++++ torrent/server.go | 14 ++++++++------ 4 files changed, 46 insertions(+), 9 deletions(-) create mode 100644 torrent/id.go diff --git a/cmd/distribyted/main.go b/cmd/distribyted/main.go index c5bf435..a97eab8 100644 --- a/cmd/distribyted/main.go +++ b/cmd/distribyted/main.go @@ -116,7 +116,12 @@ func load(configPath string, port, webDAVPort int, fuseAllowOther bool) error { return fmt.Errorf("error starting item store: %w", err) } - c, err := torrent.NewClient(st, fis, conf.Torrent) + id, err := torrent.GetOrCreatePeerID(filepath.Join(conf.Torrent.MetadataFolder, "ID")) + if err != nil { + return fmt.Errorf("error creating node ID: %w", err) + } + + c, err := torrent.NewClient(st, fis, conf.Torrent, id) if err != nil { return fmt.Errorf("error starting torrent client: %w", err) } diff --git a/torrent/client.go b/torrent/client.go index e469f2e..fe49807 100644 --- a/torrent/client.go +++ b/torrent/client.go @@ -13,11 +13,11 @@ import ( "github.com/rs/zerolog/log" ) -func NewClient(st storage.ClientImpl, fis bep44.Store, cfg *config.TorrentGlobal) (*torrent.Client, error) { +func NewClient(st storage.ClientImpl, fis bep44.Store, cfg *config.TorrentGlobal, id [20]byte) (*torrent.Client, error) { // TODO download and upload limits torrentCfg := torrent.NewDefaultClientConfig() torrentCfg.Seed = true - // torrentCfg.DisableWebseeds = true + torrentCfg.PeerID = string(id[:]) torrentCfg.DefaultStorage = st torrentCfg.DisableIPv6 = cfg.DisableIPv6 diff --git a/torrent/id.go b/torrent/id.go new file mode 100644 index 0000000..e18471c --- /dev/null +++ b/torrent/id.go @@ -0,0 +1,30 @@ +package torrent + +import ( + "crypto/rand" + "os" +) + +var emptyBytes [20]byte + +func GetOrCreatePeerID(p string) ([20]byte, error) { + idb, err := os.ReadFile(p) + if err == nil { + var out [20]byte + copy(out[:], idb) + + return out, nil + } + + if !os.IsNotExist(err) { + return emptyBytes, err + } + + var out [20]byte + _, err = rand.Read(out[:]) + if err != nil { + return emptyBytes, err + } + + return out, os.WriteFile(p, out[:], 0755) +} diff --git a/torrent/server.go b/torrent/server.go index 8a0ec3b..f16a441 100644 --- a/torrent/server.go +++ b/torrent/server.go @@ -94,12 +94,14 @@ func (s *Server) Start() error { } s.fw = w + go func() { + if err := s.makeMagnet(); err != nil { + s.updateState(ERROR) + s.log.Error().Err(err).Msg("error generating magnet on start") + } - if err := s.makeMagnet(); err != nil { - return err - } - - go s.watch() + s.watch() + }() go func() { for { @@ -149,7 +151,7 @@ func (s *Server) makeMagnet() error { s.log.Info().Msg("starting serving new torrent") info := metainfo.Info{ - PieceLength: 1 << 8, + PieceLength: 2 << 18, } s.updateState(READING)