1
0
mirror of https://github.com/schollz/croc.git synced 2024-11-28 09:35:14 +03:00
croc/connect.go

262 lines
7.3 KiB
Go
Raw Normal View History

2017-10-18 02:50:20 +03:00
package main
import (
"fmt"
"io"
2017-10-18 06:15:48 +03:00
"io/ioutil"
2017-10-18 02:50:20 +03:00
"math"
"net"
"os"
2017-10-18 05:25:33 +03:00
"path"
2017-10-18 02:50:20 +03:00
"strconv"
2017-10-18 02:53:43 +03:00
"strings"
2017-10-18 02:50:20 +03:00
"sync"
"time"
2017-10-18 03:39:50 +03:00
"github.com/gosuri/uiprogress"
2017-10-18 02:50:20 +03:00
log "github.com/sirupsen/logrus"
)
2017-10-18 03:39:50 +03:00
var bars []*uiprogress.Bar
2017-10-18 02:50:20 +03:00
// runClient spawns threads for parallel uplink/downlink via TCP
func runClient(connectionType string, codePhrase string) {
logger := log.WithFields(log.Fields{
"codePhrase": codePhrase,
"connection": connectionType,
})
var wg sync.WaitGroup
wg.Add(numberConnections)
2017-10-18 03:39:50 +03:00
uiprogress.Start()
bars = make([]*uiprogress.Bar, numberConnections)
2017-10-18 02:50:20 +03:00
for id := 0; id < numberConnections; id++ {
go func(id int) {
defer wg.Done()
port := strconv.Itoa(27001 + id)
2017-10-18 03:45:52 +03:00
connection, err := net.Dial("tcp", serverAddress+":"+port)
2017-10-18 02:50:20 +03:00
if err != nil {
panic(err)
}
defer connection.Close()
message := receiveMessage(connection)
2017-10-18 03:39:50 +03:00
logger.Debugf("relay says: %s", message)
logger.Debugf("telling relay: %s", connectionType+"."+codePhrase)
sendMessage(connectionType+"."+Hash(codePhrase), connection)
2017-10-18 02:53:43 +03:00
if connectionType == "s" { // this is a sender
2017-10-18 04:06:59 +03:00
if id == 0 {
fmt.Println("waiting for other to connect")
}
2017-10-18 03:39:50 +03:00
logger.Debug("waiting for ok from relay")
2017-10-18 02:50:20 +03:00
message = receiveMessage(connection)
2017-10-18 03:39:50 +03:00
logger.Debug("got ok from relay")
2017-10-18 02:50:20 +03:00
// wait for pipe to be made
2017-10-18 03:39:50 +03:00
time.Sleep(100 * time.Millisecond)
2017-10-18 02:53:43 +03:00
// Write data from file
2017-10-18 03:39:50 +03:00
logger.Debug("send file")
2017-10-18 05:25:33 +03:00
sendFile(id, connection, codePhrase)
2017-10-18 02:53:43 +03:00
} else { // this is a receiver
// receive file
2017-10-18 03:39:50 +03:00
logger.Debug("receive file")
2017-10-18 06:28:32 +03:00
fileName, fileIV, fileSalt, fileHash = receiveFile(id, connection, codePhrase)
2017-10-18 02:50:20 +03:00
}
}(id)
}
wg.Wait()
2017-10-18 03:39:50 +03:00
if connectionType == "r" {
2017-10-18 06:28:32 +03:00
catFile(fileName)
encrypted, err := ioutil.ReadFile(fileName + ".encrypted")
2017-10-18 06:15:48 +03:00
if err != nil {
log.Error(err)
return
}
fmt.Println("\n\ndecrypting...")
2017-10-18 06:28:32 +03:00
decrypted, err := Decrypt(encrypted, codePhrase, fileSalt, fileIV)
2017-10-18 06:15:48 +03:00
if err != nil {
log.Error(err)
return
}
2017-10-18 06:28:32 +03:00
ioutil.WriteFile(fileName, decrypted, 0644)
os.Remove(fileName + ".encrypted")
log.Debugf("\n\n\ndownloaded hash: %s", HashBytes(decrypted))
log.Debugf("\n\n\nrelayed hash: %s", fileHash)
if fileHash != HashBytes(decrypted) {
fmt.Printf("\nUh oh! %s is corrupted! Sorry, try again.\n", fileName)
} else {
fmt.Printf("\nDownloaded %s!", fileName)
}
2017-10-18 06:15:48 +03:00
} else {
log.Info("cleaning up")
os.Remove(fileName + ".encrypted")
2017-10-18 03:39:50 +03:00
}
}
func catFile(fileNameToReceive string) {
// cat the file
os.Remove(fileNameToReceive)
2017-10-18 06:15:48 +03:00
finished, err := os.Create(fileNameToReceive + ".encrypted")
2017-10-18 03:39:50 +03:00
defer finished.Close()
if err != nil {
log.Fatal(err)
}
for id := 0; id < numberConnections; id++ {
fh, err := os.Open(fileNameToReceive + "." + strconv.Itoa(id))
if err != nil {
log.Fatal(err)
}
_, err = io.Copy(finished, fh)
if err != nil {
log.Fatal(err)
}
fh.Close()
os.Remove(fileNameToReceive + "." + strconv.Itoa(id))
}
2017-10-18 02:50:20 +03:00
}
2017-10-18 06:28:32 +03:00
func receiveFile(id int, connection net.Conn, codePhrase string) (fileNameToReceive string, iv string, salt string, hashOfFile string) {
2017-10-18 03:39:50 +03:00
logger := log.WithFields(log.Fields{
"function": "receiveFile #" + strconv.Itoa(id),
})
2017-10-18 02:53:43 +03:00
2017-10-18 03:39:50 +03:00
logger.Debug("waiting for file size")
2017-10-18 06:15:48 +03:00
bufferFileSize := make([]byte, 10)
2017-10-18 02:53:43 +03:00
connection.Read(bufferFileSize)
fileSize, _ := strconv.ParseInt(strings.Trim(string(bufferFileSize), ":"), 10, 64)
2017-10-18 03:39:50 +03:00
logger.Debugf("filesize: %d", fileSize)
2017-10-18 02:53:43 +03:00
2017-10-18 06:15:48 +03:00
bufferFileName := make([]byte, 64)
2017-10-18 02:53:43 +03:00
connection.Read(bufferFileName)
2017-10-18 06:15:48 +03:00
fileNameToReceive = strings.Trim(string(bufferFileName), ":")
2017-10-18 03:39:50 +03:00
logger.Debugf("fileName: %v", fileNameToReceive)
2017-10-18 06:15:48 +03:00
ivHex := make([]byte, BUFFERSIZE)
connection.Read(ivHex)
iv = strings.Trim(string(ivHex), ":")
2017-10-18 06:28:32 +03:00
logger.Debugf("iv: %s", iv)
2017-10-18 06:15:48 +03:00
saltHex := make([]byte, BUFFERSIZE)
connection.Read(saltHex)
salt = strings.Trim(string(saltHex), ":")
2017-10-18 06:28:32 +03:00
logger.Debugf("salt: %s", salt)
hashOfFileBytes := make([]byte, BUFFERSIZE)
connection.Read(hashOfFileBytes)
hashOfFile = strings.Trim(string(hashOfFileBytes), ":")
logger.Debugf("hashOfFile: %s", hashOfFile)
2017-10-18 06:15:48 +03:00
2017-10-18 03:39:50 +03:00
os.Remove(fileNameToReceive + "." + strconv.Itoa(id))
newFile, err := os.Create(fileNameToReceive + "." + strconv.Itoa(id))
2017-10-18 02:53:43 +03:00
if err != nil {
panic(err)
}
defer newFile.Close()
2017-10-18 03:39:50 +03:00
bars[id] = uiprogress.AddBar(int(fileSize)/1024 + 1).AppendCompleted().PrependElapsed()
logger.Debug("waiting for file")
2017-10-18 02:53:43 +03:00
var receivedBytes int64
for {
2017-10-18 03:39:50 +03:00
bars[id].Incr()
2017-10-18 02:53:43 +03:00
if (fileSize - receivedBytes) < BUFFERSIZE {
2017-10-18 03:39:50 +03:00
logger.Debug("at the end")
2017-10-18 02:53:43 +03:00
io.CopyN(newFile, connection, (fileSize - receivedBytes))
// Empty the remaining bytes that we don't need from the network buffer
2017-10-18 03:39:50 +03:00
if (receivedBytes+BUFFERSIZE)-fileSize < BUFFERSIZE {
logger.Debug("empty remaining bytes from network buffer")
connection.Read(make([]byte, (receivedBytes+BUFFERSIZE)-fileSize))
}
2017-10-18 02:53:43 +03:00
break
}
io.CopyN(newFile, connection, BUFFERSIZE)
//Increment the counter
receivedBytes += BUFFERSIZE
}
2017-10-18 03:39:50 +03:00
logger.Debug("received file")
2017-10-18 06:15:48 +03:00
return
2017-10-18 02:53:43 +03:00
}
2017-10-18 05:25:33 +03:00
func sendFile(id int, connection net.Conn, codePhrase string) {
2017-10-18 02:50:20 +03:00
logger := log.WithFields(log.Fields{
2017-10-18 03:39:50 +03:00
"function": "sendFile #" + strconv.Itoa(id),
2017-10-18 02:50:20 +03:00
})
defer connection.Close()
2017-10-18 05:25:33 +03:00
// Open the file that needs to be send to the client
file, err := os.Open(fileName + ".encrypted")
2017-10-18 02:50:20 +03:00
if err != nil {
2017-10-18 05:33:27 +03:00
logger.Error(err)
2017-10-18 02:50:20 +03:00
return
}
defer file.Close()
2017-10-18 05:25:33 +03:00
// Get the filename and filesize
2017-10-18 02:50:20 +03:00
fileInfo, err := file.Stat()
if err != nil {
2017-10-18 05:33:27 +03:00
logger.Error(err)
2017-10-18 02:50:20 +03:00
return
}
numChunks := math.Ceil(float64(fileInfo.Size()) / float64(BUFFERSIZE))
chunksPerWorker := int(math.Ceil(numChunks / float64(numberConnections)))
bytesPerConnection := int64(chunksPerWorker * BUFFERSIZE)
if id+1 == numberConnections {
bytesPerConnection = fileInfo.Size() - (numberConnections-1)*bytesPerConnection
}
fileSize := fillString(strconv.FormatInt(int64(bytesPerConnection), 10), 10)
2017-10-18 05:25:33 +03:00
fileNameToSend := fillString(path.Base(fileName), 64)
2017-10-18 02:50:20 +03:00
if id == 0 || id == numberConnections-1 {
2017-10-18 03:39:50 +03:00
logger.Debugf("numChunks: %v", numChunks)
logger.Debugf("chunksPerWorker: %v", chunksPerWorker)
logger.Debugf("bytesPerConnection: %v", bytesPerConnection)
2017-10-18 05:25:33 +03:00
logger.Debugf("fileNameToSend: %v", path.Base(fileName))
2017-10-18 02:50:20 +03:00
}
2017-10-18 06:28:32 +03:00
// send file size
2017-10-18 05:33:27 +03:00
logger.Debugf("sending fileSize: %s", fileSize)
2017-10-18 02:50:20 +03:00
connection.Write([]byte(fileSize))
2017-10-18 06:28:32 +03:00
// send fileName
2017-10-18 05:33:27 +03:00
logger.Debugf("sending fileNameToSend: %s", fileNameToSend)
2017-10-18 03:39:50 +03:00
connection.Write([]byte(fileNameToSend))
2017-10-18 06:15:48 +03:00
// send iv
2017-10-18 06:28:32 +03:00
logger.Debugf("sending iv: %s", fileIV)
connection.Write([]byte(fillString(fileIV, BUFFERSIZE)))
2017-10-18 06:15:48 +03:00
// send salt
2017-10-18 06:28:32 +03:00
logger.Debugf("sending salt: %s", fileSalt)
connection.Write([]byte(fillString(fileSalt, BUFFERSIZE)))
// send sha256sum of file
logger.Debugf("sending sha256sum: %s", fileHash)
connection.Write([]byte(fillString(fileHash, BUFFERSIZE)))
2017-10-18 06:15:48 +03:00
2017-10-18 02:50:20 +03:00
sendBuffer := make([]byte, BUFFERSIZE)
chunkI := 0
for {
_, err = file.Read(sendBuffer)
if err == io.EOF {
//End of file reached, break out of for loop
2017-10-18 03:39:50 +03:00
logger.Debug("EOF")
2017-10-18 02:50:20 +03:00
break
}
if (chunkI >= chunksPerWorker*id && chunkI < chunksPerWorker*id+chunksPerWorker) || (id == numberConnections-1 && chunkI >= chunksPerWorker*id) {
connection.Write(sendBuffer)
}
chunkI++
}
2017-10-18 03:39:50 +03:00
logger.Debug("file is sent")
2017-10-18 02:50:20 +03:00
return
}