Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
200 lines (174 loc) · 6.34 KB
/
Copy pathmain.go
File metadata and controls
200 lines (174 loc) · 6.34 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package main
import (
"bufio"
"flag"
"fmt"
"net"
"os"
"path/filepath"
"strings"
)
func main() {
runMatchmakerFlag := flag.Bool("run-matchmaker", false, "Start self-hosted matchmaker server (signalling + STUN)")
matchmakerURL := flag.String("matchmaker", YeetMatchmakerServer, "Custom matchmaker server URL")
noMatchmakerFlag := flag.Bool("no-matchmaker", false, "Do not connect to external matchmaker server (listen locally for direct IP/LAN transfers only)")
receiverIPFlag := flag.String("receiver-ip", "", "Connect directly to receiver IP address (bypasses external matchmaker)")
addr := flag.String("addr", ":8080", "Address for matchmaker HTTP server to listen on")
stunAddr := flag.String("stun-addr", ":3478", "Address for matchmaker STUN server to listen on (UDP)")
behindProxy := flag.Bool("behind-proxy", false, "Trust proxy headers for rate limiting (X-Forwarded-For, X-Real-IP)")
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n\n", filepath.Base(os.Args[0]))
fmt.Fprintf(flag.CommandLine.Output(), "To receive a file:\n")
fmt.Fprintf(flag.CommandLine.Output(), " %s [-matchmaker <url>] [-no-matchmaker]\n\n", filepath.Base(os.Args[0]))
fmt.Fprintf(flag.CommandLine.Output(), "To send files:\n")
fmt.Fprintf(flag.CommandLine.Output(), " %s [-matchmaker <url>] [-receiver-ip <ip_addr>] <filename1> [<filename2> ...]\n\n", filepath.Base(os.Args[0]))
fmt.Fprintf(flag.CommandLine.Output(), "To start a self-hosted match-making server (signalling + STUN):\n")
fmt.Fprintf(flag.CommandLine.Output(), " %s -run-matchmaker [-addr <addr>] [-stun-addr <addr>] [-behind-proxy]\n\n", filepath.Base(os.Args[0]))
fmt.Fprintf(flag.CommandLine.Output(), "Flags:\n")
flag.PrintDefaults()
}
flag.Parse()
if *runMatchmakerFlag {
runMatchmaker(*addr, *stunAddr, *behindProxy)
return
}
var serverURL string
if *noMatchmakerFlag {
serverURL = ""
} else {
serverURL = *matchmakerURL
if serverURL == "" {
serverURL = YeetMatchmakerServer
}
}
args := flag.Args()
if len(args) == 0 {
runReceive(serverURL)
return
}
runSend(serverURL, *receiverIPFlag, args)
}
func runMatchmaker(addr, stunAddr string, behindProxy bool) {
mm := NewMatchmaker()
mm.BehindProxy = behindProxy
err := mm.Start(addr, stunAddr)
if err != nil {
fmt.Fprintf(os.Stderr, "❌ Error starting matchmaker server: %v\n", err)
os.Exit(1)
}
select {}
}
func runSend(serverURL, receiverIP string, filenames []string) {
if receiverIP != "" {
serverURL = FormatReceiverURL(receiverIP)
}
fmt.Printf("Enter Session ID: ")
sessionID := readLine()
sender, err := NewSender(serverURL, SessionID(sessionID))
if err != nil {
errStr := err.Error()
if strings.Contains(errStr, "no such host") || strings.Contains(errStr, "unreachable") {
fmt.Fprintf(os.Stderr, "❌ Error: Signalling server unreachable (offline or DNS failed).\n")
fmt.Fprintf(os.Stderr, "💡 Tip: Check your internet connection, or make sure the receiver is running on the same local network (LAN) and has generated Session ID %s.\n", sessionID)
} else {
fmt.Fprintf(os.Stderr, "❌ Error: %v\n", err)
}
os.Exit(1)
}
defer sender.Close()
sender.OnProgress = newCLIProgressHandler("📤 Yeeting", "yeeted successfully!")
if receiverIP != "" {
fmt.Printf("🔗 Connected directly to receiver at %s! Handshaking...\n", serverURL)
} else {
fmt.Println("🔗 Connected to signalling server! Handshaking with receiver...")
}
for _, filename := range filenames {
if err := sender.Send(filename); err != nil {
fmt.Fprintf(os.Stderr, "\n❌ Error sending file %s: %v\n", filename, err)
os.Exit(1)
}
}
}
func runReceive(serverURL string) {
receiver, err := NewReceiver(serverURL)
if err != nil {
fmt.Fprintf(os.Stderr, "❌ Error starting receiver: %v\n", err)
os.Exit(1)
}
defer receiver.Close()
receiver.OnProgress = newCLIProgressHandler("📥 Downloading", "received successfully!")
fmt.Printf("Your Session ID: %s\n", receiver.SessionID)
if localIP, err := GetLocalIP(); err == nil && localIP != "127.0.0.1" {
_, portStr, _ := net.SplitHostPort(strings.TrimPrefix(receiver.LocalServerURL, "http://"))
if portStr != "" && portStr != DefaultReceiverPort {
fmt.Printf("Local IP: %s:%s\n", localIP, portStr)
} else {
fmt.Printf("Local IP: %s\n", localIP)
}
}
fmt.Println("Waiting for a sender to connect...")
senderName := <-receiver.SenderRequest()
fmt.Printf("\nConnection request from '%s'. Accept? (y/n): ", senderName)
answer := readLine()
if strings.ToLower(answer) != "y" && strings.ToLower(answer) != "yes" {
if err := receiver.RejectConnection(); err != nil {
fmt.Printf("❌ Error rejecting connection: %v\n", err)
}
fmt.Println("❌ Connection rejected.")
return
}
fmt.Println("Connection accepted! Establishing direct P2P link...")
if err := receiver.ApproveConnection(); err != nil {
fmt.Fprintf(os.Stderr, "❌ Error accepting connection: %v\n", err)
os.Exit(1)
}
senderToken := <-receiver.SenderAnswer()
if err := receiver.Connect(senderToken); err != nil {
fmt.Fprintf(os.Stderr, "❌ Error establishing connection: %v\n", err)
os.Exit(1)
}
for tr := range receiver.TransferRequest() {
if err := receiver.Accept(tr); err != nil {
fmt.Fprintf(os.Stderr, "❌ Error accepting file transfer: %v\n", err)
os.Exit(1)
}
if err := <-receiver.Done(); err != nil {
fmt.Printf("❌ Error during transfer: %v\n", err)
os.Exit(1)
}
}
}
func formatSize(bytes int64) string {
const unit = 1024
if bytes < unit {
return fmt.Sprintf("%d B", bytes)
}
div, exp := int64(unit), 0
for n := bytes / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB", float64(bytes)/float64(div), "KMGTPE"[exp])
}
func readLine() string {
reader := bufio.NewReader(os.Stdin)
line, err := reader.ReadString('\n')
if err != nil {
fmt.Fprintf(os.Stderr, "❌ Error reading input: %v\n", err)
os.Exit(1)
}
return strings.TrimSpace(line)
}
func newCLIProgressHandler(actionLabel, completeSuffix string) ProgressFunc {
return func(fileName string, current, total int64) {
if total <= 0 {
return
}
if current >= total {
fmt.Printf("\r✨ %s %s\033[K\n", fileName, completeSuffix)
return
}
percent := float64(current) / float64(total) * 100
fmt.Printf("\r%s %s... %.1f%% (%s / %s)\033[K", actionLabel, truncateString(fileName, 40), percent, formatSize(current), formatSize(total))
}
}