forked from spieglt/FlyingCarpet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
202 lines (180 loc) · 4.81 KB
/
main.go
File metadata and controls
202 lines (180 loc) · 4.81 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
201
202
package main
import (
"bufio"
"crypto/md5"
"flag"
"fmt"
"log"
"math/rand"
"net"
"os"
"runtime"
"strconv"
"strings"
"time"
)
const DIAL_TIMEOUT = 60
const JOIN_ADHOC_TIMEOUT = 60
const FIND_MAC_TIMEOUT = 60
func main() {
if len(os.Args) == 1 {
printUsage()
return
}
var p_outFile = flag.String("send", "", "File to be sent.")
var p_inFile = flag.String("receive", "", "Destination path of file to be received.")
var p_port = flag.Int("port", 3290, "TCP port to use (must match on both ends).")
var p_peer = flag.String("peer", "", "Use \"-peer mac\" or \"-peer windows\" to match the other computer.")
flag.Parse()
outFile := *p_outFile
inFile := *p_inFile
port := *p_port
peer := *p_peer
receiveChan := make(chan bool)
sendChan := make(chan bool)
if peer == "" || ( peer != "mac" && peer != "windows" ) {
log.Fatal("Must choose [ -peer mac ] or [ -peer windows ].")
}
t := Transfer{
Port: port,
Peer: peer,
AdHocChan: make(chan bool),
}
var n Network
// sending
if outFile != "" && inFile == "" {
t.Passphrase = getPassword()
pwBytes := md5.Sum([]byte(t.Passphrase))
prefix := pwBytes[:3]
t.SSID = fmt.Sprintf("flyingCarpet_%x", prefix)
t.Filepath = outFile
if runtime.GOOS == "windows" {
w := WindowsNetwork{Mode: "sending"}
w.PreviousSSID = w.getCurrentWifi()
n = w
} else if runtime.GOOS == "darwin" {
n = MacNetwork{Mode: "sending"}
}
n.connectToPeer(&t)
if connected := t.sendFile(sendChan, n); connected == false {
fmt.Println("Could not establish TCP connection with peer")
return
}
<-sendChan
fmt.Println("Send complete, resetting WiFi and exiting.")
//receiving
} else if inFile != "" && outFile == "" {
t.Passphrase = generatePassword()
pwBytes := md5.Sum([]byte(t.Passphrase))
prefix := pwBytes[:3]
t.SSID = fmt.Sprintf("flyingCarpet_%x", prefix)
fmt.Printf("=============================\n" +
"Transfer password: %s\nPlease use this password on sending end when prompted to start transfer.\n" +
"=============================\n",t.Passphrase)
if runtime.GOOS == "windows" {
n = WindowsNetwork{Mode: "receiving"}
} else if runtime.GOOS == "darwin" {
n = MacNetwork{Mode: "receiving"}
}
n.connectToPeer(&t)
t.Filepath = inFile
go t.receiveFile(receiveChan, n)
// wait for listener to be up
<-receiveChan
// wait for reception to finish
<-receiveChan
fmt.Println("Reception complete, resetting WiFi and exiting.")
} else {
printUsage()
return
}
n.resetWifi(&t)
}
func (t *Transfer) receiveFile(receiveChan chan bool, n Network) {
ln, err := net.Listen("tcp", ":"+strconv.Itoa(t.Port))
if err != nil {
n.teardown(t)
log.Fatal("Could not listen on :",t.Port)
}
fmt.Println("Listening on", ":"+strconv.Itoa(t.Port))
receiveChan <- true
for {
conn, err := ln.Accept()
if err != nil {
n.teardown(t)
log.Fatal("Error accepting connection on :",t.Port)
}
t.Conn = conn
fmt.Println("Connection accepted")
go t.receiveAndAssemble(receiveChan, n)
}
}
func (t *Transfer) sendFile(sendChan chan bool, n Network) bool {
var conn net.Conn
var err error
for i := 0; i < DIAL_TIMEOUT; i++ {
err = nil
conn, err = net.DialTimeout("tcp", t.RecipientIP+":"+strconv.Itoa(t.Port), time.Millisecond * 10)
if err != nil {
fmt.Printf("\rFailed connection %2d to %s, retrying.", i, t.RecipientIP)
time.Sleep(time.Second * 1)
continue
} else {
fmt.Printf("\n")
t.Conn = conn
go t.chunkAndSend(sendChan, n)
return true
}
}
fmt.Printf("Waited %d seconds, no connection. Exiting.", DIAL_TIMEOUT)
return false
}
func generatePassword() string {
const chars = "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ"
rand.Seed(time.Now().UTC().UnixNano())
pwBytes := make([]byte, 8)
for i := range pwBytes {
pwBytes[i] = chars[rand.Intn(len(chars))]
}
return string(pwBytes)
}
func getPassword() (pw string) {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter password from receiving end: ")
pw,err := reader.ReadString('\n')
if err != nil {
panic("Error getting password.")
}
pw = strings.TrimSpace(pw)
return
}
func printUsage() {
fmt.Println("\nUsage (Windows): flyingcarpet.exe -send ./picture.jpg -peer mac")
fmt.Println("[Enter password from receiving end.]\n")
fmt.Println("Usage (Mac): ./flyingcarpet -receive ./newpicture.jpg -peer windows")
fmt.Println("[Enter password into sending end.]\n")
return
}
type Transfer struct {
Filepath string
Passphrase string
SSID string
Conn net.Conn
Port int
RecipientIP string
Peer string
AdHocChan chan bool
}
type Network interface {
connectToPeer(*Transfer)
getCurrentWifi() string
resetWifi(*Transfer)
teardown(*Transfer)
}
type WindowsNetwork struct {
Mode string // sending or receiving
PreviousSSID string
}
type MacNetwork struct {
Mode string // sending or receiving
}