]> Sergey Matveev's repositories - btrtrc.git/blob - cmd/torrentfs/main.go
Update external use of ClientConfig
[btrtrc.git] / cmd / torrentfs / main.go
1 // Mounts a FUSE filesystem backed by torrents and magnet links.
2 package main
3
4 import (
5         "log"
6         "net"
7         "net/http"
8         _ "net/http/pprof"
9         "os"
10         "os/signal"
11         "os/user"
12         "path/filepath"
13         "syscall"
14         "time"
15
16         "bazil.org/fuse"
17         fusefs "bazil.org/fuse/fs"
18         _ "github.com/anacrolix/envpprof"
19         "github.com/anacrolix/tagflag"
20
21         "github.com/anacrolix/torrent"
22         "github.com/anacrolix/torrent/fs"
23         "github.com/anacrolix/torrent/util/dirwatch"
24 )
25
26 var (
27         args = struct {
28                 MetainfoDir string `help:"torrent files in this location describe the contents of the mounted filesystem"`
29                 DownloadDir string `help:"location to save torrent data"`
30                 MountDir    string `help:"location the torrent contents are made available"`
31
32                 DisableTrackers bool
33                 TestPeer        *net.TCPAddr
34                 ReadaheadBytes  tagflag.Bytes
35                 ListenAddr      *net.TCPAddr
36         }{
37                 MetainfoDir: func() string {
38                         _user, err := user.Current()
39                         if err != nil {
40                                 log.Fatal(err)
41                         }
42                         return filepath.Join(_user.HomeDir, ".config/transmission/torrents")
43                 }(),
44                 ReadaheadBytes: 10 << 20,
45                 ListenAddr:     &net.TCPAddr{},
46         }
47 )
48
49 func exitSignalHandlers(fs *torrentfs.TorrentFS) {
50         c := make(chan os.Signal, 1)
51         signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
52         for {
53                 <-c
54                 fs.Destroy()
55                 err := fuse.Unmount(args.MountDir)
56                 if err != nil {
57                         log.Print(err)
58                 }
59         }
60 }
61
62 func addTestPeer(client *torrent.Client) {
63         for _, t := range client.Torrents() {
64                 t.AddPeers([]torrent.Peer{{
65                         IP:   args.TestPeer.IP,
66                         Port: args.TestPeer.Port,
67                 }})
68         }
69 }
70
71 func main() {
72         os.Exit(mainExitCode())
73 }
74
75 func mainExitCode() int {
76         tagflag.Parse(&args)
77         if args.MountDir == "" {
78                 os.Stderr.WriteString("y u no specify mountpoint?\n")
79                 return 2
80         }
81         log.SetFlags(log.LstdFlags | log.Lshortfile)
82         conn, err := fuse.Mount(args.MountDir)
83         if err != nil {
84                 log.Fatal(err)
85         }
86         defer fuse.Unmount(args.MountDir)
87         // TODO: Think about the ramifications of exiting not due to a signal.
88         defer conn.Close()
89         cfg := torrent.NewDefaultClientConfig()
90         cfg.DataDir = args.DownloadDir
91         cfg.DisableTrackers = args.DisableTrackers
92         cfg.NoUpload = true // Ensure that downloads are responsive.
93         cfg.SetListenAddr(args.ListenAddr.String())
94         client, err := torrent.NewClient(cfg)
95         if err != nil {
96                 log.Print(err)
97                 return 1
98         }
99         // This is naturally exported via GOPPROF=http.
100         http.DefaultServeMux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
101                 client.WriteStatus(w)
102         })
103         dw, err := dirwatch.New(args.MetainfoDir)
104         if err != nil {
105                 log.Printf("error watching torrent dir: %s", err)
106                 return 1
107         }
108         go func() {
109                 for ev := range dw.Events {
110                         switch ev.Change {
111                         case dirwatch.Added:
112                                 if ev.TorrentFilePath != "" {
113                                         _, err := client.AddTorrentFromFile(ev.TorrentFilePath)
114                                         if err != nil {
115                                                 log.Printf("error adding torrent to client: %s", err)
116                                         }
117                                 } else if ev.MagnetURI != "" {
118                                         _, err := client.AddMagnet(ev.MagnetURI)
119                                         if err != nil {
120                                                 log.Printf("error adding magnet: %s", err)
121                                         }
122                                 }
123                         case dirwatch.Removed:
124                                 T, ok := client.Torrent(ev.InfoHash)
125                                 if !ok {
126                                         break
127                                 }
128                                 T.Drop()
129                         }
130                 }
131         }()
132         fs := torrentfs.New(client)
133         go exitSignalHandlers(fs)
134
135         if args.TestPeer != nil {
136                 go func() {
137                         for {
138                                 addTestPeer(client)
139                                 time.Sleep(10 * time.Second)
140                         }
141                 }()
142         }
143
144         if err := fusefs.Serve(conn, fs); err != nil {
145                 log.Fatal(err)
146         }
147         <-conn.Ready
148         if err := conn.MountError; err != nil {
149                 log.Fatal(err)
150         }
151         return 0
152 }