-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
106 lines (90 loc) · 1.95 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"net/netip"
"os"
"time"
"github.com/samber/lo"
"github.com/xmddhs/qBittorrent-nat/qbittorrent"
"github.com/xmdhs/natupnp/natmap"
)
var (
configPath string
stun string
)
func init() {
flag.StringVar(&configPath, "c", "config.json", "")
flag.StringVar(&stun, "s", "turn.cloudflare.com:3478", "stun")
flag.Parse()
}
func main() {
c := config{}
b := lo.Must(os.ReadFile(configPath))
lo.Must0(json.Unmarshal(b, &c))
ctx := context.Background()
for {
func() {
defer time.Sleep(1 * time.Second)
err := openPort(ctx, func(pub, pri netip.AddrPort) {
if pub.Port() == pri.Port() {
log.Println("公网,无需转发")
return
}
err := Forward(pub.Port(), pri.Port())
if err != nil {
log.Println(err)
return
}
q, err := qbittorrent.Login(ctx, c.Root, http.Client{Timeout: 10 * time.Second}, c.UserName, c.PassWord)
if err != nil {
log.Println(err)
return
}
log.Printf("change qBittorrent port to: %v", pub.Port())
err = q.ChangePort(ctx, pub.Port())
if err != nil {
log.Println(err)
return
}
log.Printf("%v --> %v --> 127.0.0.1:%v", pub, pri, pub.Port())
})
if err != nil {
log.Println(err)
time.Sleep(5 * time.Second)
return
}
}()
}
}
func openPort(ctx context.Context, finish func(pub, pri netip.AddrPort)) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
la, err := natmap.GetLocalAddr()
if err != nil {
return fmt.Errorf("openPort: %w", err)
}
laddr := netip.MustParseAddrPort(la.String())
errCh := make(chan error, 1)
m, maddr, err := natmap.NatMap(ctx, stun, laddr, func(err error) {
cancel()
select {
case errCh <- err:
default:
}
})
if err != nil {
return fmt.Errorf("openPort: %w", err)
}
defer m.Close()
finish(maddr, laddr)
err = <-errCh
if err != nil {
return fmt.Errorf("openPort: %w", err)
}
return nil
}